id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_4232_0
/* ** $Id: lgc.c $ ** Garbage Collector ** See Copyright Notice in lua.h */ #define lgc_c #define LUA_CORE #include "lprefix.h" #include <stdio.h> #include <string.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" /* ** Maximum number of elements to sweep in each single step. ** (Large enough to dissipate fixed overheads but small enough ** to allow small steps for the collector.) */ #define GCSWEEPMAX 100 /* ** Maximum number of finalizers to call in each single step. */ #define GCFINMAX 10 /* ** Cost of calling one finalizer. */ #define GCFINALIZECOST 50 /* ** The equivalent, in bytes, of one unit of "work" (visiting a slot, ** sweeping an object, etc.) */ #define WORK2MEM sizeof(TValue) /* ** macro to adjust 'pause': 'pause' is actually used like ** 'pause / PAUSEADJ' (value chosen by tests) */ #define PAUSEADJ 100 /* mask to erase all color bits (plus gen. related stuff) */ #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS | AGEBITS)) /* macro to erase all color bits then sets only the current white bit */ #define makewhite(g,x) \ (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g))) #define white2gray(x) resetbits(x->marked, WHITEBITS) #define black2gray(x) resetbit(x->marked, BLACKBIT) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) #define checkconsistency(obj) \ lua_longassert(!iscollectable(obj) || righttt(obj)) /* ** Protected access to objects in values */ #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) #define markvalue(g,o) { checkconsistency(o); \ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } /* ** mark an object that can be NULL (either because it is really optional, ** or it was stripped as debug info, or inside an uncompleted structure) */ #define markobjectN(g,t) { if (t) markobject(g,t); } static void reallymarkobject (global_State *g, GCObject *o); static lu_mem atomic (lua_State *L); static void entersweep (lua_State *L); /* ** {====================================================== ** Generic functions ** ======================================================= */ /* ** one after last element in a hash array */ #define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) static GCObject **getgclist (GCObject *o) { switch (o->tt) { case LUA_VTABLE: return &gco2t(o)->gclist; case LUA_VLCL: return &gco2lcl(o)->gclist; case LUA_VCCL: return &gco2ccl(o)->gclist; case LUA_VTHREAD: return &gco2th(o)->gclist; case LUA_VPROTO: return &gco2p(o)->gclist; case LUA_VUSERDATA: { Udata *u = gco2u(o); lua_assert(u->nuvalue > 0); return &u->gclist; } default: lua_assert(0); return 0; } } /* ** Link a collectable object 'o' with a known type into list pointed by 'p'. */ #define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o)) /* ** Link a generic collectable object 'o' into list pointed by 'p'. */ #define linkobjgclist(o,p) (*getgclist(o) = (p), (p) = obj2gco(o)) /* ** Clear keys for empty entries in tables. If entry is empty ** and its key is not marked, mark its entry as dead. This allows the ** collection of the key, but keeps its entry in the table (its removal ** could break a chain). The main feature of a dead key is that it must ** be different from any other value, to do not disturb searches. ** Other places never manipulate dead keys, because its associated empty ** value is enough to signal that the entry is logically empty. */ static void clearkey (Node *n) { lua_assert(isempty(gval(n))); if (keyiswhite(n)) setdeadkey(n); /* unused and unmarked key; remove it */ } /* ** tells whether a key or value can be cleared from a weak ** table. Non-collectable objects are never removed from weak ** tables. Strings behave as 'values', so are never removed too. for ** other objects: if really collected, cannot keep them; for objects ** being finalized, keep them in keys, but not in values */ static int iscleared (global_State *g, const GCObject *o) { if (o == NULL) return 0; /* non-collectable value */ else if (novariant(o->tt) == LUA_TSTRING) { markobject(g, o); /* strings are 'values', so are never weak */ return 0; } else return iswhite(o); } /* ** barrier that moves collector forward, that is, mark the white object ** 'v' being pointed by the black object 'o'. (If in sweep phase, clear ** the black object to white [sweep it] to avoid other barrier calls for ** this same object.) In the generational mode, 'v' must also become ** old, if 'o' is old; however, it cannot be changed directly to OLD, ** because it may still point to non-old objects. So, it is marked as ** OLD0. In the next cycle it will become OLD1, and in the next it ** will finally become OLD (regular old). */ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { global_State *g = G(L); lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); if (keepinvariant(g)) { /* must keep invariant? */ reallymarkobject(g, v); /* restore invariant */ if (isold(o)) { lua_assert(!isold(v)); /* white object could not be old */ setage(v, G_OLD0); /* restore generational invariant */ } } else { /* sweep phase */ lua_assert(issweepphase(g)); makewhite(g, o); /* mark main obj. as white to avoid other barriers */ } } /* ** barrier that moves collector backward, that is, mark the black object ** pointing to a white object as gray again. */ void luaC_barrierback_ (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(isblack(o) && !isdead(g, o)); lua_assert(g->gckind != KGC_GEN || (isold(o) && getage(o) != G_TOUCHED1)); if (getage(o) != G_TOUCHED2) /* not already in gray list? */ linkobjgclist(o, g->grayagain); /* link it in 'grayagain' */ black2gray(o); /* make object gray (again) */ setage(o, G_TOUCHED1); /* touched in current cycle */ } void luaC_fix (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ white2gray(o); /* they will be gray forever */ setage(o, G_OLD); /* and old forever */ g->allgc = o->next; /* remove object from 'allgc' list */ o->next = g->fixedgc; /* link it to 'fixedgc' list */ g->fixedgc = o; } /* ** create a new collectable object (with given type and size) and link ** it to 'allgc' list. */ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { global_State *g = G(L); GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz)); o->marked = luaC_white(g); o->tt = tt; o->next = g->allgc; g->allgc = o; return o; } /* }====================================================== */ /* ** {====================================================== ** Mark functions ** ======================================================= */ /* ** Mark an object. Userdata, strings, and closed upvalues are visited ** and turned black here. Other objects are marked gray and added ** to appropriate list to be visited (and turned black) later. (Open ** upvalues are already linked in 'headuv' list. They are kept gray ** to avoid barriers, as their values will be revisited by the thread.) */ static void reallymarkobject (global_State *g, GCObject *o) { white2gray(o); switch (o->tt) { case LUA_VSHRSTR: case LUA_VLNGSTR: { gray2black(o); break; } case LUA_VUPVAL: { UpVal *uv = gco2upv(o); if (!upisopen(uv)) /* open upvalues are kept gray */ gray2black(o); markvalue(g, uv->v); /* mark its content */ break; } case LUA_VUSERDATA: { Udata *u = gco2u(o); if (u->nuvalue == 0) { /* no user values? */ markobjectN(g, u->metatable); /* mark its metatable */ gray2black(o); /* nothing else to mark */ break; } /* else... */ } /* FALLTHROUGH */ case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: case LUA_VTHREAD: case LUA_VPROTO: { linkobjgclist(o, g->gray); break; } default: lua_assert(0); break; } } /* ** mark metamethods for basic types */ static void markmt (global_State *g) { int i; for (i=0; i < LUA_NUMTAGS; i++) markobjectN(g, g->mt[i]); } /* ** mark all objects in list of being-finalized */ static lu_mem markbeingfnz (global_State *g) { GCObject *o; lu_mem count = 0; for (o = g->tobefnz; o != NULL; o = o->next) { count++; markobject(g, o); } return count; } /* ** Mark all values stored in marked open upvalues from non-marked threads. ** (Values from marked threads were already marked when traversing the ** thread.) Remove from the list threads that no longer have upvalues and ** not-marked threads. */ static int remarkupvals (global_State *g) { lua_State *thread; lua_State **p = &g->twups; int work = 0; while ((thread = *p) != NULL) { work++; lua_assert(!isblack(thread)); /* threads are never black */ if (isgray(thread) && thread->openupval != NULL) p = &thread->twups; /* keep marked thread with upvalues in the list */ else { /* thread is not marked or without upvalues */ UpVal *uv; *p = thread->twups; /* remove thread from the list */ thread->twups = thread; /* mark that it is out of list */ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { work++; if (!iswhite(uv)) /* upvalue already visited? */ markvalue(g, uv->v); /* mark its value */ } } } return work; } /* ** mark root set and reset all gray lists, to start a new collection */ static void restartcollection (global_State *g) { g->gray = g->grayagain = NULL; g->weak = g->allweak = g->ephemeron = NULL; markobject(g, g->mainthread); markvalue(g, &g->l_registry); markmt(g); markbeingfnz(g); /* mark any finalizing object left from previous cycle */ } /* }====================================================== */ /* ** {====================================================== ** Traverse functions ** ======================================================= */ /* ** Traverse a table with weak values and link it to proper list. During ** propagate phase, keep it in 'grayagain' list, to be revisited in the ** atomic phase. In the atomic phase, if table has any white value, ** put it in 'weak' list, to be cleared. */ static void traverseweakvalue (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); /* if there is array part, assume it may have white values (it is not worth traversing it now just to check) */ int hasclears = (h->alimit > 0); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ hasclears = 1; /* table will have to be cleared */ } } if (g->gcstate == GCSatomic && hasclears) linkgclist(h, g->weak); /* has to be cleared later */ else linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ } /* ** Traverse an ephemeron table and link it to proper list. Returns true ** iff any object was marked during this traversal (which implies that ** convergence has to continue). During propagation phase, keep table ** in 'grayagain' list, to be visited again in the atomic phase. In ** the atomic phase, if table has any white->white entry, it has to ** be revisited during ephemeron convergence (as that key may turn ** black). Otherwise, if it has any white key, table has to be cleared ** (in the atomic phase). In generational mode, it (like all visited ** tables) must be kept in some gray list for post-processing. */ static int traverseephemeron (global_State *g, Table *h, int inv) { int marked = 0; /* true if an object is marked in this traversal */ int hasclears = 0; /* true if table has white keys */ int hasww = 0; /* true if table has entry "white-key -> white-value" */ unsigned int i; unsigned int asize = luaH_realasize(h); unsigned int nsize = sizenode(h); /* traverse array part */ for (i = 0; i < asize; i++) { if (valiswhite(&h->array[i])) { marked = 1; reallymarkobject(g, gcvalue(&h->array[i])); } } /* traverse hash part; if 'inv', traverse descending (see 'convergeephemerons') */ for (i = 0; i < nsize; i++) { Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ hasclears = 1; /* table must be cleared */ if (valiswhite(gval(n))) /* value not marked yet? */ hasww = 1; /* white-white entry */ } else if (valiswhite(gval(n))) { /* value not marked yet? */ marked = 1; reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ } } /* link table into proper list */ if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ else if (hasww) /* table has white->white entries? */ linkgclist(h, g->ephemeron); /* have to propagate again */ else if (hasclears) /* table has white keys? */ linkgclist(h, g->allweak); /* may have to clean white keys */ else if (g->gckind == KGC_GEN) linkgclist(h, g->grayagain); /* keep it in some list */ else gray2black(h); return marked; } static void traversestrongtable (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) /* traverse array part */ markvalue(g, &h->array[i]); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); markvalue(g, gval(n)); } } if (g->gckind == KGC_GEN) { linkgclist(h, g->grayagain); /* keep it in some gray list */ black2gray(h); } } static lu_mem traversetable (global_State *g, Table *h) { const char *weakkey, *weakvalue; const TValue *mode = gfasttm(g, h->metatable, TM_MODE); markobjectN(g, h->metatable); if (mode && ttisstring(mode) && /* is there a weak mode? */ (cast_void(weakkey = strchr(svalue(mode), 'k')), cast_void(weakvalue = strchr(svalue(mode), 'v')), (weakkey || weakvalue))) { /* is really weak? */ black2gray(h); /* keep table gray */ if (!weakkey) /* strong keys? */ traverseweakvalue(g, h); else if (!weakvalue) /* strong values? */ traverseephemeron(g, h, 0); else /* all weak */ linkgclist(h, g->allweak); /* nothing to traverse now */ } else /* not weak */ traversestrongtable(g, h); return 1 + h->alimit + 2 * allocsizenode(h); } static int traverseudata (global_State *g, Udata *u) { int i; markobjectN(g, u->metatable); /* mark its metatable */ for (i = 0; i < u->nuvalue; i++) markvalue(g, &u->uv[i].uv); if (g->gckind == KGC_GEN) { linkgclist(u, g->grayagain); /* keep it in some gray list */ black2gray(u); } return 1 + u->nuvalue; } /* ** Traverse a prototype. (While a prototype is being build, its ** arrays can be larger than needed; the extra slots are filled with ** NULL, so the use of 'markobjectN') */ static int traverseproto (global_State *g, Proto *f) { int i; markobjectN(g, f->source); for (i = 0; i < f->sizek; i++) /* mark literals */ markvalue(g, &f->k[i]); for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ markobjectN(g, f->upvalues[i].name); for (i = 0; i < f->sizep; i++) /* mark nested protos */ markobjectN(g, f->p[i]); for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ markobjectN(g, f->locvars[i].varname); return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; } static int traverseCclosure (global_State *g, CClosure *cl) { int i; for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ markvalue(g, &cl->upvalue[i]); return 1 + cl->nupvalues; } /* ** Traverse a Lua closure, marking its prototype and its upvalues. ** (Both can be NULL while closure is being created.) */ static int traverseLclosure (global_State *g, LClosure *cl) { int i; markobjectN(g, cl->p); /* mark its prototype */ for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ UpVal *uv = cl->upvals[i]; markobjectN(g, uv); /* mark upvalue */ } return 1 + cl->nupvalues; } /* ** Traverse a thread, marking the elements in the stack up to its top ** and cleaning the rest of the stack in the final traversal. ** That ensures that the entire stack have valid (non-dead) objects. */ static int traversethread (global_State *g, lua_State *th) { UpVal *uv; StkId o = th->stack; if (o == NULL) return 1; /* stack not completely built yet */ lua_assert(g->gcstate == GCSatomic || th->openupval == NULL || isintwups(th)); for (; o < th->top; o++) /* mark live elements in the stack */ markvalue(g, s2v(o)); for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) markobject(g, uv); /* open upvalues cannot be collected */ if (g->gcstate == GCSatomic) { /* final traversal? */ StkId lim = th->stack + th->stacksize; /* real end of stack */ for (; o < lim; o++) /* clear not-marked stack slice */ setnilvalue(s2v(o)); /* 'remarkupvals' may have removed thread from 'twups' list */ if (!isintwups(th) && th->openupval != NULL) { th->twups = g->twups; /* link it back to the list */ g->twups = th; } } else if (!g->gcemergency) luaD_shrinkstack(th); /* do not change stack in emergency cycle */ return 1 + th->stacksize; } /* ** traverse one gray object, turning it to black (except for threads, ** which are always gray). */ static lu_mem propagatemark (global_State *g) { GCObject *o = g->gray; gray2black(o); g->gray = *getgclist(o); /* remove from 'gray' list */ switch (o->tt) { case LUA_VTABLE: return traversetable(g, gco2t(o)); case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); case LUA_VPROTO: return traverseproto(g, gco2p(o)); case LUA_VTHREAD: { lua_State *th = gco2th(o); linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ black2gray(o); return traversethread(g, th); } default: lua_assert(0); return 0; } } static lu_mem propagateall (global_State *g) { lu_mem tot = 0; while (g->gray) tot += propagatemark(g); return tot; } /* ** Traverse all ephemeron tables propagating marks from keys to values. ** Repeat until it converges, that is, nothing new is marked. 'dir' ** inverts the direction of the traversals, trying to speed up ** convergence on chains in the same table. ** */ static void convergeephemerons (global_State *g) { int changed; int dir = 0; do { GCObject *w; GCObject *next = g->ephemeron; /* get ephemeron list */ g->ephemeron = NULL; /* tables may return to this list when traversed */ changed = 0; while ((w = next) != NULL) { /* for each ephemeron table */ next = gco2t(w)->gclist; /* list is rebuilt during loop */ if (traverseephemeron(g, gco2t(w), dir)) { /* marked some value? */ propagateall(g); /* propagate changes */ changed = 1; /* will have to revisit all ephemeron tables */ } } dir = !dir; /* invert direction next time */ } while (changed); /* repeat until no more changes */ } /* }====================================================== */ /* ** {====================================================== ** Sweep Functions ** ======================================================= */ /* ** clear entries with unmarked keys from all weaktables in list 'l' */ static void clearbykeys (global_State *g, GCObject *l) { for (; l; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *limit = gnodelast(h); Node *n; for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gckeyN(n))) /* unmarked key? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } /* ** clear entries with unmarked values from all weaktables in list 'l' up ** to element 'f' */ static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { for (; l != f; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) { TValue *o = &h->array[i]; if (iscleared(g, gcvalueN(o))) /* value was collected? */ setempty(o); /* remove entry */ } for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } static void freeupval (lua_State *L, UpVal *uv) { if (upisopen(uv)) luaF_unlinkupval(uv); luaM_free(L, uv); } static void freeobj (lua_State *L, GCObject *o) { switch (o->tt) { case LUA_VPROTO: luaF_freeproto(L, gco2p(o)); break; case LUA_VUPVAL: freeupval(L, gco2upv(o)); break; case LUA_VLCL: luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); break; case LUA_VCCL: luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); break; case LUA_VTABLE: luaH_free(L, gco2t(o)); break; case LUA_VTHREAD: luaE_freethread(L, gco2th(o)); break; case LUA_VUSERDATA: { Udata *u = gco2u(o); luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); break; } case LUA_VSHRSTR: luaS_remove(L, gco2ts(o)); /* remove it from hash table */ luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen)); break; case LUA_VLNGSTR: luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen)); break; default: lua_assert(0); } } /* ** sweep at most 'countin' elements from a list of GCObjects erasing dead ** objects, where a dead object is one marked with the old (non current) ** white; change all non-dead objects back to white, preparing for next ** collection cycle. Return where to continue the traversal or NULL if ** list is finished. ('*countout' gets the number of elements traversed.) */ static GCObject **sweeplist (lua_State *L, GCObject **p, int countin, int *countout) { global_State *g = G(L); int ow = otherwhite(g); int i; int white = luaC_white(g); /* current white */ for (i = 0; *p != NULL && i < countin; i++) { GCObject *curr = *p; int marked = curr->marked; if (isdeadm(ow, marked)) { /* is 'curr' dead? */ *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* change mark to 'white' */ curr->marked = cast_byte((marked & maskcolors) | white); p = &curr->next; /* go to next element */ } } if (countout) *countout = i; /* number of elements traversed */ return (*p == NULL) ? NULL : p; } /* ** sweep a list until a live object (or end of list) */ static GCObject **sweeptolive (lua_State *L, GCObject **p) { GCObject **old = p; do { p = sweeplist(L, p, 1, NULL); } while (p == old); return p; } /* }====================================================== */ /* ** {====================================================== ** Finalization ** ======================================================= */ /* ** If possible, shrink string table. */ static void checkSizes (lua_State *L, global_State *g) { if (!g->gcemergency) { if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */ l_mem olddebt = g->GCdebt; luaS_resize(L, g->strt.size / 2); g->GCestimate += g->GCdebt - olddebt; /* correct estimate */ } } } /* ** Get the next udata to be finalized from the 'tobefnz' list, and ** link it back into the 'allgc' list. */ static GCObject *udata2finalize (global_State *g) { GCObject *o = g->tobefnz; /* get first element */ lua_assert(tofinalize(o)); g->tobefnz = o->next; /* remove it from 'tobefnz' list */ o->next = g->allgc; /* return it to 'allgc' list */ g->allgc = o; resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ if (issweepphase(g)) makewhite(g, o); /* "sweep" object */ return o; } static void dothecall (lua_State *L, void *ud) { UNUSED(ud); luaD_callnoyield(L, L->top - 2, 0); } static void GCTM (lua_State *L) { global_State *g = G(L); const TValue *tm; TValue v; lua_assert(!g->gcemergency); setgcovalue(L, &v, udata2finalize(g)); tm = luaT_gettmbyobj(L, &v, TM_GC); if (!notm(tm)) { /* is there a finalizer? */ int status; lu_byte oldah = L->allowhook; int running = g->gcrunning; L->allowhook = 0; /* stop debug hooks during GC metamethod */ g->gcrunning = 0; /* avoid GC steps */ setobj2s(L, L->top++, tm); /* push finalizer... */ setobj2s(L, L->top++, &v); /* ... and its argument */ L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ L->allowhook = oldah; /* restore hooks */ g->gcrunning = running; /* restore state */ if (unlikely(status != LUA_OK)) { /* error while running __gc? */ luaE_warnerror(L, "__gc metamethod"); L->top--; /* pops error object */ } } } /* ** Call a few finalizers */ static int runafewfinalizers (lua_State *L, int n) { global_State *g = G(L); int i; for (i = 0; i < n && g->tobefnz; i++) GCTM(L); /* call one finalizer */ return i; } /* ** call all pending finalizers */ static void callallpendingfinalizers (lua_State *L) { global_State *g = G(L); while (g->tobefnz) GCTM(L); } /* ** find last 'next' field in list 'p' list (to add elements in its end) */ static GCObject **findlast (GCObject **p) { while (*p != NULL) p = &(*p)->next; return p; } /* ** Move all unreachable objects (or 'all' objects) that need ** finalization from list 'finobj' to list 'tobefnz' (to be finalized). ** (Note that objects after 'finobjold' cannot be white, so they ** don't need to be traversed. In incremental mode, 'finobjold' is NULL, ** so the whole list is traversed.) */ static void separatetobefnz (global_State *g, int all) { GCObject *curr; GCObject **p = &g->finobj; GCObject **lastnext = findlast(&g->tobefnz); while ((curr = *p) != g->finobjold) { /* traverse all finalizable objects */ lua_assert(tofinalize(curr)); if (!(iswhite(curr) || all)) /* not being collected? */ p = &curr->next; /* don't bother with it */ else { if (curr == g->finobjsur) /* removing 'finobjsur'? */ g->finobjsur = curr->next; /* correct it */ *p = curr->next; /* remove 'curr' from 'finobj' list */ curr->next = *lastnext; /* link at the end of 'tobefnz' list */ *lastnext = curr; lastnext = &curr->next; } } } /* ** if object 'o' has a finalizer, remove it from 'allgc' list (must ** search the list to find it) and link it in 'finobj' list. */ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { global_State *g = G(L); if (tofinalize(o) || /* obj. is already marked... */ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ return; /* nothing to be done */ else { /* move 'o' to 'finobj' list */ GCObject **p; if (issweepphase(g)) { makewhite(g, o); /* "sweep" object 'o' */ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ } else { /* correct pointers into 'allgc' list, if needed */ if (o == g->survival) g->survival = o->next; if (o == g->old) g->old = o->next; if (o == g->reallyold) g->reallyold = o->next; } /* search for pointer pointing to 'o' */ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } *p = o->next; /* remove 'o' from 'allgc' list */ o->next = g->finobj; /* link it in 'finobj' list */ g->finobj = o; l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ } } /* }====================================================== */ /* ** {====================================================== ** Generational Collector ** ======================================================= */ static void setpause (global_State *g); /* mask to erase all color bits, not changing gen-related stuff */ #define maskgencolors (~(bitmask(BLACKBIT) | WHITEBITS)) /* ** Sweep a list of objects, deleting dead ones and turning ** the non dead to old (without changing their colors). */ static void sweep2old (lua_State *L, GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(isdead(G(L), curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* all surviving objects become old */ setage(curr, G_OLD); p = &curr->next; /* go to next element */ } } } /* ** Sweep for generational mode. Delete dead objects. (Because the ** collection is not incremental, there are no "new white" objects ** during the sweep. So, any white object must be dead.) For ** non-dead objects, advance their ages and clear the color of ** new objects. (Old objects keep their colors.) */ static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, GCObject *limit) { static const lu_byte nextage[] = { G_SURVIVAL, /* from G_NEW */ G_OLD1, /* from G_SURVIVAL */ G_OLD1, /* from G_OLD0 */ G_OLD, /* from G_OLD1 */ G_OLD, /* from G_OLD (do not change) */ G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ }; int white = luaC_white(g); GCObject *curr; while ((curr = *p) != limit) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(!isold(curr) && isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* correct mark and age */ if (getage(curr) == G_NEW) curr->marked = cast_byte((curr->marked & maskgencolors) | white); setage(curr, nextage[getage(curr)]); p = &curr->next; /* go to next element */ } } return p; } /* ** Traverse a list making all its elements white and clearing their ** age. */ static void whitelist (global_State *g, GCObject *p) { int white = luaC_white(g); for (; p != NULL; p = p->next) p->marked = cast_byte((p->marked & maskcolors) | white); } /* ** Correct a list of gray objects. ** Because this correction is done after sweeping, young objects might ** be turned white and still be in the list. They are only removed. ** For tables and userdata, advance 'touched1' to 'touched2'; 'touched2' ** objects become regular old and are removed from the list. ** For threads, just remove white ones from the list. */ static GCObject **correctgraylist (GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { switch (curr->tt) { case LUA_VTABLE: case LUA_VUSERDATA: { GCObject **next = getgclist(curr); if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ lua_assert(isgray(curr)); gray2black(curr); /* make it black, for next barrier */ changeage(curr, G_TOUCHED1, G_TOUCHED2); p = next; /* go to next element */ } else { /* not touched in this cycle */ if (!iswhite(curr)) { /* not white? */ lua_assert(isold(curr)); if (getage(curr) == G_TOUCHED2) /* advance from G_TOUCHED2... */ changeage(curr, G_TOUCHED2, G_OLD); /* ... to G_OLD */ gray2black(curr); /* make it black */ } /* else, object is white: just remove it from this list */ *p = *next; /* remove 'curr' from gray list */ } break; } case LUA_VTHREAD: { lua_State *th = gco2th(curr); lua_assert(!isblack(th)); if (iswhite(th)) /* new object? */ *p = th->gclist; /* remove from gray list */ else /* old threads remain gray */ p = &th->gclist; /* go to next element */ break; } default: lua_assert(0); /* nothing more could be gray here */ } } return p; } /* ** Correct all gray lists, coalescing them into 'grayagain'. */ static void correctgraylists (global_State *g) { GCObject **list = correctgraylist(&g->grayagain); *list = g->weak; g->weak = NULL; list = correctgraylist(list); *list = g->allweak; g->allweak = NULL; list = correctgraylist(list); *list = g->ephemeron; g->ephemeron = NULL; correctgraylist(list); } /* ** Mark 'OLD1' objects when starting a new young collection. ** Gray objects are already in some gray list, and so will be visited ** in the atomic step. */ static void markold (global_State *g, GCObject *from, GCObject *to) { GCObject *p; for (p = from; p != to; p = p->next) { if (getage(p) == G_OLD1) { lua_assert(!iswhite(p)); if (isblack(p)) { black2gray(p); /* should be '2white', but gray works too */ reallymarkobject(g, p); } } } } /* ** Finish a young-generation collection. */ static void finishgencycle (lua_State *L, global_State *g) { correctgraylists(g); checkSizes(L, g); g->gcstate = GCSpropagate; /* skip restart */ if (!g->gcemergency) callallpendingfinalizers(L); } /* ** Does a young collection. First, mark 'OLD1' objects. Then does the ** atomic step. Then, sweep all lists and advance pointers. Finally, ** finish the collection. */ static void youngcollection (lua_State *L, global_State *g) { GCObject **psurvival; /* to point to first non-dead survival object */ lua_assert(g->gcstate == GCSpropagate); markold(g, g->allgc, g->reallyold); markold(g, g->finobj, g->finobjrold); atomic(L); /* sweep nursery and get a pointer to its last live element */ psurvival = sweepgen(L, g, &g->allgc, g->survival); /* sweep 'survival' and 'old' */ sweepgen(L, g, psurvival, g->reallyold); g->reallyold = g->old; g->old = *psurvival; /* 'survival' survivals are old now */ g->survival = g->allgc; /* all news are survivals */ /* repeat for 'finobj' lists */ psurvival = sweepgen(L, g, &g->finobj, g->finobjsur); /* sweep 'survival' and 'old' */ sweepgen(L, g, psurvival, g->finobjrold); g->finobjrold = g->finobjold; g->finobjold = *psurvival; /* 'survival' survivals are old now */ g->finobjsur = g->finobj; /* all news are survivals */ sweepgen(L, g, &g->tobefnz, NULL); finishgencycle(L, g); } static void atomic2gen (lua_State *L, global_State *g) { /* sweep all elements making them old */ sweep2old(L, &g->allgc); /* everything alive now is old */ g->reallyold = g->old = g->survival = g->allgc; /* repeat for 'finobj' lists */ sweep2old(L, &g->finobj); g->finobjrold = g->finobjold = g->finobjsur = g->finobj; sweep2old(L, &g->tobefnz); g->gckind = KGC_GEN; g->lastatomic = 0; g->GCestimate = gettotalbytes(g); /* base for memory control */ finishgencycle(L, g); } /* ** Enter generational mode. Must go until the end of an atomic cycle ** to ensure that all threads and weak tables are in the gray lists. ** Then, turn all objects into old and finishes the collection. */ static lu_mem entergen (lua_State *L, global_State *g) { lu_mem numobjs; luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ numobjs = atomic(L); /* propagates all and then do the atomic stuff */ atomic2gen(L, g); return numobjs; } /* ** Enter incremental mode. Turn all objects white, make all ** intermediate lists point to NULL (to avoid invalid pointers), ** and go to the pause state. */ static void enterinc (global_State *g) { whitelist(g, g->allgc); g->reallyold = g->old = g->survival = NULL; whitelist(g, g->finobj); whitelist(g, g->tobefnz); g->finobjrold = g->finobjold = g->finobjsur = NULL; g->gcstate = GCSpause; g->gckind = KGC_INC; g->lastatomic = 0; } /* ** Change collector mode to 'newmode'. */ void luaC_changemode (lua_State *L, int newmode) { global_State *g = G(L); if (newmode != g->gckind) { if (newmode == KGC_GEN) /* entering generational mode? */ entergen(L, g); else enterinc(g); /* entering incremental mode */ } g->lastatomic = 0; } /* ** Does a full collection in generational mode. */ static lu_mem fullgen (lua_State *L, global_State *g) { enterinc(g); return entergen(L, g); } /* ** Set debt for the next minor collection, which will happen when ** memory grows 'genminormul'%. */ static void setminordebt (global_State *g) { luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul)); } /* ** Does a major collection after last collection was a "bad collection". ** ** When the program is building a big structure, it allocates lots of ** memory but generates very little garbage. In those scenarios, ** the generational mode just wastes time doing small collections, and ** major collections are frequently what we call a "bad collection", a ** collection that frees too few objects. To avoid the cost of switching ** between generational mode and the incremental mode needed for full ** (major) collections, the collector tries to stay in incremental mode ** after a bad collection, and to switch back to generational mode only ** after a "good" collection (one that traverses less than 9/8 objects ** of the previous one). ** The collector must choose whether to stay in incremental mode or to ** switch back to generational mode before sweeping. At this point, it ** does not know the real memory in use, so it cannot use memory to ** decide whether to return to generational mode. Instead, it uses the ** number of objects traversed (returned by 'atomic') as a proxy. The ** field 'g->lastatomic' keeps this count from the last collection. ** ('g->lastatomic != 0' also means that the last collection was bad.) */ static void stepgenfull (lua_State *L, global_State *g) { lu_mem newatomic; /* count of traversed objects */ lu_mem lastatomic = g->lastatomic; /* count from last collection */ if (g->gckind == KGC_GEN) /* still in generational mode? */ enterinc(g); /* enter incremental mode */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ newatomic = atomic(L); /* mark everybody */ if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */ atomic2gen(L, g); /* return to generational mode */ setminordebt(g); } else { /* another bad collection; stay in incremental mode */ g->GCestimate = gettotalbytes(g); /* first estimate */; entersweep(L); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); g->lastatomic = newatomic; } } /* ** Does a generational "step". ** Usually, this means doing a minor collection and setting the debt to ** make another collection when memory grows 'genminormul'% larger. ** ** However, there are exceptions. If memory grows 'genmajormul'% ** larger than it was at the end of the last major collection (kept ** in 'g->GCestimate'), the function does a major collection. At the ** end, it checks whether the major collection was able to free a ** decent amount of memory (at least half the growth in memory since ** previous major collection). If so, the collector keeps its state, ** and the next collection will probably be minor again. Otherwise, ** we have what we call a "bad collection". In that case, set the field ** 'g->lastatomic' to signal that fact, so that the next collection will ** go to 'stepgenfull'. ** ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero; ** in that case, do a minor collection. */ static void genstep (lua_State *L, global_State *g) { if (g->lastatomic != 0) /* last collection was a bad one? */ stepgenfull(L, g); /* do a full step */ else { lu_mem majorbase = g->GCestimate; /* memory after last major collection */ lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul); if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) { lu_mem numobjs = fullgen(L, g); /* do a major collection */ if (gettotalbytes(g) < majorbase + (majorinc / 2)) { /* collected at least half of memory growth since last major collection; keep doing minor collections */ setminordebt(g); } else { /* bad collection */ g->lastatomic = numobjs; /* signal that last collection was bad */ setpause(g); /* do a long wait for next (major) collection */ } } else { /* regular case; do a minor collection */ youngcollection(L, g); setminordebt(g); g->GCestimate = majorbase; /* preserve base value */ } } lua_assert(isdecGCmodegen(g)); } /* }====================================================== */ /* ** {====================================================== ** GC control ** ======================================================= */ /* ** Set the "time" to wait before starting a new GC cycle; cycle will ** start when memory use hits the threshold of ('estimate' * pause / ** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero, ** because Lua cannot even start with less than PAUSEADJ bytes). */ static void setpause (global_State *g) { l_mem threshold, debt; int pause = getgcparam(g->gcpause); l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ lua_assert(estimate > 0); threshold = (pause < MAX_LMEM / estimate) /* overflow? */ ? estimate * pause /* no overflow */ : MAX_LMEM; /* overflow; truncate to maximum */ debt = gettotalbytes(g) - threshold; if (debt > 0) debt = 0; luaE_setdebt(g, debt); } /* ** Enter first sweep phase. ** The call to 'sweeptolive' makes the pointer point to an object ** inside the list (instead of to the header), so that the real sweep do ** not need to skip objects created between "now" and the start of the ** real sweep. */ static void entersweep (lua_State *L) { global_State *g = G(L); g->gcstate = GCSswpallgc; lua_assert(g->sweepgc == NULL); g->sweepgc = sweeptolive(L, &g->allgc); } /* ** Delete all objects in list 'p' until (but not including) object ** 'limit'. */ static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { while (p != limit) { GCObject *next = p->next; freeobj(L, p); p = next; } } /* ** Call all finalizers of the objects in the given Lua state, and ** then free all objects, except for the main thread. */ void luaC_freeallobjects (lua_State *L) { global_State *g = G(L); luaC_changemode(L, KGC_INC); separatetobefnz(g, 1); /* separate all objects with finalizers */ lua_assert(g->finobj == NULL); callallpendingfinalizers(L); deletelist(L, g->allgc, obj2gco(g->mainthread)); deletelist(L, g->finobj, NULL); deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ lua_assert(g->strt.nuse == 0); } static lu_mem atomic (lua_State *L) { global_State *g = G(L); lu_mem work = 0; GCObject *origweak, *origall; GCObject *grayagain = g->grayagain; /* save original list */ g->grayagain = NULL; lua_assert(g->ephemeron == NULL && g->weak == NULL); lua_assert(!iswhite(g->mainthread)); g->gcstate = GCSatomic; markobject(g, L); /* mark running thread */ /* registry and global metatables may be changed by API */ markvalue(g, &g->l_registry); markmt(g); /* mark global metatables */ work += propagateall(g); /* empties 'gray' list */ /* remark occasional upvalues of (maybe) dead threads */ work += remarkupvals(g); work += propagateall(g); /* propagate changes */ g->gray = grayagain; work += propagateall(g); /* traverse 'grayagain' list */ convergeephemerons(g); /* at this point, all strongly accessible objects are marked. */ /* Clear values from weak tables, before checking finalizers */ clearbyvalues(g, g->weak, NULL); clearbyvalues(g, g->allweak, NULL); origweak = g->weak; origall = g->allweak; separatetobefnz(g, 0); /* separate objects to be finalized */ work += markbeingfnz(g); /* mark objects that will be finalized */ work += propagateall(g); /* remark, to propagate 'resurrection' */ convergeephemerons(g); /* at this point, all resurrected objects are marked. */ /* remove dead objects from weak tables */ clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */ clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */ /* clear values from resurrected weak tables */ clearbyvalues(g, g->weak, origweak); clearbyvalues(g, g->allweak, origall); luaS_clearcache(g); g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ lua_assert(g->gray == NULL); return work; /* estimate of slots marked by 'atomic' */ } static int sweepstep (lua_State *L, global_State *g, int nextstate, GCObject **nextlist) { if (g->sweepgc) { l_mem olddebt = g->GCdebt; int count; g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count); g->GCestimate += g->GCdebt - olddebt; /* update estimate */ return count; } else { /* enter next state */ g->gcstate = nextstate; g->sweepgc = nextlist; return 0; /* no work done */ } } static lu_mem singlestep (lua_State *L) { global_State *g = G(L); switch (g->gcstate) { case GCSpause: { restartcollection(g); g->gcstate = GCSpropagate; return 1; } case GCSpropagate: { if (g->gray == NULL) { /* no more gray objects? */ g->gcstate = GCSenteratomic; /* finish propagate phase */ return 0; } else return propagatemark(g); /* traverse one gray object */ } case GCSenteratomic: { lu_mem work = atomic(L); /* work is what was traversed by 'atomic' */ entersweep(L); g->GCestimate = gettotalbytes(g); /* first estimate */; return work; } case GCSswpallgc: { /* sweep "regular" objects */ return sweepstep(L, g, GCSswpfinobj, &g->finobj); } case GCSswpfinobj: { /* sweep objects with finalizers */ return sweepstep(L, g, GCSswptobefnz, &g->tobefnz); } case GCSswptobefnz: { /* sweep objects to be finalized */ return sweepstep(L, g, GCSswpend, NULL); } case GCSswpend: { /* finish sweeps */ checkSizes(L, g); g->gcstate = GCScallfin; return 0; } case GCScallfin: { /* call remaining finalizers */ if (g->tobefnz && !g->gcemergency) { int n = runafewfinalizers(L, GCFINMAX); return n * GCFINALIZECOST; } else { /* emergency mode or no more finalizers */ g->gcstate = GCSpause; /* finish collection */ return 0; } } default: lua_assert(0); return 0; } } /* ** advances the garbage collector until it reaches a state allowed ** by 'statemask' */ void luaC_runtilstate (lua_State *L, int statesmask) { global_State *g = G(L); while (!testbit(statesmask, g->gcstate)) singlestep(L); } /* ** Performs a basic incremental step. The debt and step size are ** converted from bytes to "units of work"; then the function loops ** running single steps until adding that many units of work or ** finishing a cycle (pause state). Finally, it sets the debt that ** controls when next step will be performed. */ static void incstep (lua_State *L, global_State *g) { int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */ l_mem debt = (g->GCdebt / WORK2MEM) * stepmul; l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem)) ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul : MAX_LMEM; /* overflow; keep maximum value */ do { /* repeat until pause or enough "credit" (negative debt) */ lu_mem work = singlestep(L); /* perform one single step */ debt -= work; } while (debt > -stepsize && g->gcstate != GCSpause); if (g->gcstate == GCSpause) setpause(g); /* pause until next cycle */ else { debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */ luaE_setdebt(g, debt); } } /* ** performs a basic GC step if collector is running */ void luaC_step (lua_State *L) { global_State *g = G(L); lua_assert(!g->gcemergency); if (g->gcrunning) { /* running? */ if(isdecGCmodegen(g)) genstep(L, g); else incstep(L, g); } } /* ** Perform a full collection in incremental mode. ** Before running the collection, check 'keepinvariant'; if it is true, ** there may be some objects marked as black, so the collector has ** to sweep all objects to turn them back to white (as white has not ** changed, nothing will be collected). */ static void fullinc (lua_State *L, global_State *g) { if (keepinvariant(g)) /* black objects? */ entersweep(L); /* sweep everything to turn them back to white */ /* finish any pending sweep phase to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpause)); luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ /* estimate must be correct after a full GC cycle */ lua_assert(g->GCestimate == gettotalbytes(g)); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); } /* ** Performs a full GC cycle; if 'isemergency', set a flag to avoid ** some operations which could change the interpreter state in some ** unexpected ways (running finalizers and shrinking some structures). */ void luaC_fullgc (lua_State *L, int isemergency) { global_State *g = G(L); lua_assert(!g->gcemergency); g->gcemergency = isemergency; /* set flag */ if (g->gckind == KGC_INC) fullinc(L, g); else fullgen(L, g); g->gcemergency = 0; } /* }====================================================== */
./CrossVul/dataset_final_sorted/CWE-125/c/good_4232_0
crossvul-cpp_data_good_2657_1
/* * Copyright (C) 2002 WIDE Project. * 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ /* \summary: IPv6 mobility printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "ip6.h" #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static const char tstr[] = "[|MOBILITY]"; /* Mobility header */ struct ip6_mobility { uint8_t ip6m_pproto; /* following payload protocol (for PG) */ uint8_t ip6m_len; /* length in units of 8 octets */ uint8_t ip6m_type; /* message type */ uint8_t reserved; /* reserved */ uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */ union { uint16_t ip6m_un_data16[1]; /* type-specific field */ uint8_t ip6m_un_data8[2]; /* type-specific field */ } ip6m_dataun; }; #define ip6m_data16 ip6m_dataun.ip6m_un_data16 #define ip6m_data8 ip6m_dataun.ip6m_un_data8 #define IP6M_MINLEN 8 /* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */ /* message type */ #define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */ #define IP6M_HOME_TEST_INIT 1 /* Home Test Init */ #define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */ #define IP6M_HOME_TEST 3 /* Home Test */ #define IP6M_CAREOF_TEST 4 /* Care-of Test */ #define IP6M_BINDING_UPDATE 5 /* Binding Update */ #define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */ #define IP6M_BINDING_ERROR 7 /* Binding Error */ #define IP6M_MAX 7 static const struct tok ip6m_str[] = { { IP6M_BINDING_REQUEST, "BRR" }, { IP6M_HOME_TEST_INIT, "HoTI" }, { IP6M_CAREOF_TEST_INIT, "CoTI" }, { IP6M_HOME_TEST, "HoT" }, { IP6M_CAREOF_TEST, "CoT" }, { IP6M_BINDING_UPDATE, "BU" }, { IP6M_BINDING_ACK, "BA" }, { IP6M_BINDING_ERROR, "BE" }, { 0, NULL } }; static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = { IP6M_MINLEN, /* IP6M_BINDING_REQUEST */ IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */ IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */ IP6M_MINLEN + 16, /* IP6M_HOME_TEST */ IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */ IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */ IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */ IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */ }; /* Mobility Header Options */ #define IP6MOPT_MINLEN 2 #define IP6MOPT_PAD1 0x0 /* Pad1 */ #define IP6MOPT_PADN 0x1 /* PadN */ #define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */ #define IP6MOPT_REFRESH_MINLEN 4 #define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */ #define IP6MOPT_ALTCOA_MINLEN 18 #define IP6MOPT_NONCEID 0x4 /* Nonce Indices */ #define IP6MOPT_NONCEID_MINLEN 6 #define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */ #define IP6MOPT_AUTH_MINLEN 12 static int mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } /* * Mobility Header */ int mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2657_1
crossvul-cpp_data_good_147_0
/* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */ #if 0 http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set #endif #include <string.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> static RDESContext desctx; typedef struct _cpu_const_tag { const char *const key; ut8 type; ut32 value; ut8 size; } CPU_CONST; #define CPU_CONST_NONE 0 #define CPU_CONST_PARAM 1 #define CPU_CONST_REG 2 typedef struct _cpu_model_tag { const char *const model; int pc; char *inherit; struct _cpu_model_tag *inherit_cpu_p; CPU_CONST *consts[10]; } CPU_MODEL; typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu); typedef struct _opcodes_tag_ { const char *const name; int mask; int selector; inst_handler_t handler; int cycles; int size; ut64 type; } OPCODE_DESC; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu); #define CPU_MODEL_DECL(model, pc, consts) \ { \ model, \ pc, \ consts \ } #define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits)))) #define CPU_PC_MASK(cpu) MASK((cpu)->pc) #define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0)) #define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu) #define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T } #define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK } #define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu) #define INST_INVALID { *fail = 1; return; } #define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } } #define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__) #define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s)) // Following IO definitions are valid for: // ATmega8 // ATmega88 CPU_CONST cpu_reg_common[] = { { "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) }, { "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) }, { "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) }, { "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_common[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_xmega128a4u[] = { { "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_5_bits[] = { { "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_7_bits[] = { { "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_MODEL cpu_models[] = { { .model = "ATmega640", .pc = 15, .consts = { cpu_reg_common, cpu_memsize_m640_m1280m_m1281_m2560_m2561, cpu_pagesize_7_bits, NULL }, }, { .model = "ATxmega128a4u", .pc = 17, .consts = { cpu_reg_common, cpu_memsize_xmega128a4u, cpu_pagesize_7_bits, NULL } }, { .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega88", .pc = 8, .inherit = "ATmega8" }, // CPU_MODEL_DECL ("ATmega168", 13, 512, 512), // last model is the default AVR - ATmega8 forever! { .model = "ATmega8", .pc = 13, .consts = { cpu_reg_common, cpu_memsize_common, cpu_pagesize_5_bits, NULL } }, }; static CPU_MODEL *get_cpu_model(char *model); static CPU_MODEL *__get_cpu_model_recursive(char *model) { CPU_MODEL *cpu = NULL; for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) { if (!strcasecmp (model, cpu->model)) { break; } } // fix inheritance tree if (cpu->inherit && !cpu->inherit_cpu_p) { cpu->inherit_cpu_p = get_cpu_model (cpu->inherit); if (!cpu->inherit_cpu_p) { eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit); } } return cpu; } static CPU_MODEL *get_cpu_model(char *model) { static CPU_MODEL *cpu = NULL; // cached value? if (cpu && !strcasecmp (model, cpu->model)) return cpu; // do the real search cpu = __get_cpu_model_recursive (model); return cpu; } static ut32 const_get_value(CPU_CONST *c) { return c ? MASK (c->size * 8) & c->value : 0; } static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem->key; citem++) { if (!strcmp (c, citem->key) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_name (cpu->inherit_cpu_p, type, c); eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c); return NULL; } static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) { char *t = r_anal_esil_pop (esil); if (!t || !r_anal_esil_get_parm (esil, t, v)) { free (t); return false; } free (t); return true; } static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem && citem->key; citem++) { if (citem->value == (MASK (citem->size * 8) & v) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_value (cpu->inherit_cpu_p, type, v); return NULL; } static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) { RStrBuf *r = r_strbuf_new (""); CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port); if (c != NULL) { r_strbuf_set (r, c->key); if (write) { r_strbuf_append (r, ",="); } } else { r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : ""); } return r; } static void __generic_bitop_flags(RAnalOp *op) { ESIL_A ("0,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S } static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) { if (ireg) { // preincrement index register if (prepostdec < 0) { ESIL_A ("1,%c,-,%c,=,", ireg, ireg); } // set register index address ESIL_A ("%c,", ireg); // add offset if (offset != 0) { ESIL_A ("%d,+,", offset); } } else { ESIL_A ("%d,", offset); } if (use_ramp) { ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd'); } // set SRAM base address ESIL_A ("_%s,+,", mem); // read/write from SRAM ESIL_A ("%s[1],", st ? "=" : ""); // postincrement index register if (ireg && prepostdec > 0) { ESIL_A ("1,%c,+,%c,=,", ireg, ireg); } } static void __generic_pop(RAnalOp *op, int sz) { if (sz > 1) { ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1) ESIL_A ("[%d],", sz); // read value ESIL_A ("%d,sp,+=,", sz); // sp += item_size } else { ESIL_A ("1,sp,+=," // increment stack pointer "sp,_ram,+,[1],"); // load SRAM[sp] } } static void __generic_push(RAnalOp *op, int sz) { ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp) if (sz > 1) { ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz' } ESIL_A ("=[%d],", sz); // store value in stack ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer } static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) { __generic_add_update_flags(op, 'r', d, 'r', r); } static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&," "%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N if (carry) ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z else ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&," "%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) { __generic_sub_update_flags(op, 'r', d, 'r', r, carry); } static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) { __generic_sub_update_flags(op, 'r', d, 'k', k, carry); } INST_HANDLER (adc) { // ADC Rd, Rr // ROL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (add) { // ADD Rd, Rr // LSL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr // FLAGS: ESIL_A ("r%d,0x80,&,!," // V "0,RPICK,0x8000,&,!,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!,!," // C "0,RPICK,0x8000,&,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (and) { // AND Rd, Rr // TST Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (andi) { // ANDI Rd, K // CBR Rd, K (= ANDI Rd, 1-K) if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f); op->val = k; ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (asr) { // ASR Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7 ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (bclr) { // BCLR s // CLC // CLH // CLI // CLN // CLR // CLS // CLT // CLV // CLZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s); } INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } INST_HANDLER (brbx) { // BRBC s, k // BRBS s, k // BRBC/S 0: BRCC BRCS // BRSH BRLO // BRBC/S 1: BREQ BRNE // BRBC/S 2: BRPL BRMI // BRBC/S 3: BRVC BRVS // BRBC/S 4: BRGE BRLT // BRBC/S 5: BRHC BRHS // BRBC/S 6: BRTC BRTS // BRBC/S 7: BRID BRIE int s = buf[0] & 0x7; op->jump = op->addr + ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2)) | (buf[1] & 0x2 ? ~((int) 0x7f) : 0)) + 2; op->fail = op->addr + op->size; op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s) ESIL_A (buf[1] & 0x4 ? "!," // BRBC => branch if cleared : "!,!,"); // BRBS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (break) { // BREAK ESIL_A ("BREAK"); } INST_HANDLER (bset) { // BSET s // SEC // SEH // SEI // SEN // SER // SES // SET // SEV // SEZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("%d,1,<<,sreg,|=,", s); } INST_HANDLER (bst) { // BST Rd, b if (len < 2) { return; } ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r buf[0] & 0x7); // b } INST_HANDLER (call) { // CALL k if (len < 4) { return; } op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->fail = op->addr + op->size; op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // AT*mega optimizes one cycle } ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (cbi) { // CBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->family = R_ANAL_OP_FAMILY_IO; op->type2 = 1; op->val = a; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (com) { // COM Rd int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd // FLAGS: ESIL_A ("0,cf,=,"); // C __generic_bitop_flags (op); // ...rest... } INST_HANDLER (cp) { // CP Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) } INST_HANDLER (cpc) { // CPC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) } INST_HANDLER (cpi) { // CPI Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); ESIL_A ("%d,r%d,-,", k, d); // Rd - k __generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry) } INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op = {0}; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (dec) { // DEC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("-1,r%d,+,", d); // --Rd // FLAGS: ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (des) { // DES k if (desctx.round < 16) { //DES op->type = R_ANAL_OP_TYPE_CRYPTO; op->cycles = 1; //redo this r_strbuf_setf (&op->esil, "%d,des", desctx.round); } } INST_HANDLER (eijmp) { // EIJMP ut64 z, eind; // read z and eind for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = ((eind << 16) + z) << 1; // jump ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,"); // cycles op->cycles = 2; } INST_HANDLER (eicall) { // EICALL // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard EIJMP INST_CALL (eijmp); // fix cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4; } INST_HANDLER (elpm) { // ELPM // ELPM Rd // ELPM Rd, Z+ int d = ((buf[1] & 0xfe) == 0x90) ? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd : 0; // R0 ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z ESIL_A ("r%d,=,", d); // Rd = [1] if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) { ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z) } } INST_HANDLER (eor) { // EOR Rd, Rr // CLR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (fmul) { // FMUL Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmuls) { // FMULS Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmulsu) { // FMULSU Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d", r); // unsigned Rr ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (ijmp) { // IJMP k ut64 z; // read z for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = z << 1; op->cycles = 2; ESIL_A ("1,z,<<,pc,=,"); // jump! } INST_HANDLER (icall) { // ICALL k // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard IJMP INST_CALL (ijmp); // fix cycles if (!STR_BEGINS (cpu->model, "ATxmega")) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } INST_HANDLER (inc) { // INC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("1,r%d,+,", d); // ++Rd // FLAGS: ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (jmp) { // JMP k op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->cycles = 3; ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (lac) { // LAC Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (las) { // LAS Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,|,", d); // 0: (Z) | Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (lat) { // LAT Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (ld) { // LD Rd, X // LD Rd, X+ // LD Rd, -X // read memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post incremented : 0, // no increment 0, // offset always 0 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[0] & 0x3) == 0 ? 2 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z // LD Rd, Y+ LD Rd, Z+ // LD Rd, -Y LD Rd, -Z // LD Rd, Y+q LD Rd, Z+q // calculate offset (this value only has sense in some opcodes, // but we are optimistic and we calculate it always) int offset = (buf[1] & 0x20) | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7); // read memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? offset : 0, // offset or not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[1] & 0x10) == 0 ? (!offset ? 1 : 3) // LDD : (buf[0] & 0x3) == 0 ? 1 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldi) { // LDI Rd, K int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4); int d = ((buf[0] >> 4) & 0xf) + 16; op->val = k; ESIL_A ("0x%x,r%d,=,", k, d); } INST_HANDLER (lds) { // LDS Rd, k if (len < 4) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; // load value from RAMPD:k __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } INST_HANDLER (sts) { // STS k, Rr if (len < 4) { return; } int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } #if 0 INST_HANDLER (lds16) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x30) | ((buf[1] << 4) & 0x40) | (~(buf[1] << 4) & 0x80); op->ptr = k; // load value from @k __generic_ld_st (op, "ram", 0, 0, 0, k, 0); ESIL_A ("r%d,=,", d); } #endif INST_HANDLER (lpm) { // LPM // LPM Rd, Z // LPM Rd, Z+ ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]); // read program memory __generic_ld_st ( op, "prog", 'z', // index register Y/Z 1, // use RAMP* registers (ins & 0xfe0f) == 0x9005 ? 1 // post incremented : 0, // no increment 0, // not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", (ins == 0x95c8) ? 0 // LPM (r0) : ((buf[0] >> 4) & 0xf) // LPM Rd | ((buf[1] & 0x1) << 4)); } INST_HANDLER (lsr) { // LSR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1) ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (mov) { // MOV Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,=,", r, d); } INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr int d = (buf[0] & 0xf0) >> 3; int r = (buf[0] & 0x0f) << 1; ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1); } INST_HANDLER (mul) { // MUL Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (muls) { // MULS Rd, Rr int d = (buf[0] >> 4 & 0x0f) + 16; int r = (buf[0] & 0x0f) + 16; ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (mulsu) { // MULSU Rd, Rr int d = (buf[0] >> 4 & 0x07) + 16; int r = (buf[0] & 0x07) + 16; ESIL_A ("r%d,", r); // unsigned Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (neg) { // NEG Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd) ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N ESIL_A ("DUP,!,zf,=,"); // Z ESIL_A ("DUP,!,!,cf,=,"); // C ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (nop) { // NOP ESIL_A (",,"); } INST_HANDLER (or) { // OR Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (ori) { // ORI Rd, K // SBR Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); op->val = k; ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (out) { // OUT A, Rr int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_dst = __generic_io_dest (a, 1, cpu); op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst)); r_strbuf_free (io_dst); } INST_HANDLER (pop) { // POP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); __generic_pop (op, 1); ESIL_A ("r%d,=,", d); // store in Rd } INST_HANDLER (push) { // PUSH Rr int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("r%d,", r); // load Rr __generic_push (op, 1); // push it into stack // cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 1 // AT*mega optimizes one cycle : 2; } INST_HANDLER (rcall) { // RCALL k // target address op->jump = (op->addr + (((((buf[1] & 0xf) << 8) | buf[0]) << 1) | (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0))) + 2) & CPU_PC_MASK (cpu); op->fail = op->addr + op->size; // esil ESIL_A ("pc,"); // esil already points to next // instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! // cycles if (!strncasecmp (cpu->model, "ATtiny", 6)) { op->cycles = 4; // ATtiny is always slow } else { // PC size decides required runtime! op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // ATxmega optimizes one cycle } } } INST_HANDLER (ret) { // RET op->eob = true; // esil __generic_pop (op, CPU_PC_SIZE (cpu)); ESIL_A ("pc,=,"); // jump! // cycles if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit op->cycles++; // (i.e. a 22-bit bus), add one extra cycle } } INST_HANDLER (reti) { // RETI //XXX: There are not privileged instructions in ATMEL/AVR op->family = R_ANAL_OP_FAMILY_PRIV; // first perform a standard 'ret' INST_CALL (ret); // RETI: The I-bit is cleared by hardware after an interrupt // has occurred, and is set by the RETI instruction to enable // subsequent interrupts ESIL_A ("1,if,=,"); } INST_HANDLER (rjmp) { // RJMP k op->jump = (op->addr #ifdef _MSC_VER #pragma message ("anal_avr.c: WARNING: Probably broken on windows") + ((((( buf[1] & 0xf) << 9) | (buf[0] << 1))) | (buf[1] & 0x8 ? ~(0x1fff) : 0)) #else + ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1))) | (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0)) #endif + 2) & CPU_PC_MASK (cpu); ESIL_A ("%"PFMT64d",pc,=,", op->jump); } INST_HANDLER (ror) { // ROR Rd int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7) ESIL_A ("r%d,1,&,cf,=,", d); // C ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (sbc) { // SBC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C) __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbci) { // SBCI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sub) { // SUB Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k) __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (subi) { // SUBI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbi) { // SBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (sbix) { // SBIC A, b // SBIS A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RAnalOp next_op; RStrBuf *io_port; op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBIC => branch if 0 : "!,!,"); // SBIS => branch if 1 ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp r_strbuf_free (io_port); } INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr) ESIL_A ("r%d,0x80,&,!,!," // V "0,RPICK,0x8000,&,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!," // C "0,RPICK,0x8000,&,!,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (sbrx) { // SBRC Rr, b // SBRS Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op = {0}; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (sleep) { // SLEEP ESIL_A ("BREAK"); } INST_HANDLER (spm) { // SPM Z+ ut64 spmcsr; // read SPM Control Register (SPMCR) r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL); // clear SPMCSR ESIL_A ("0x7c,spmcsr,&=,"); // decide action depending on the old value of SPMCSR switch (spmcsr & 0x7f) { case 0x03: // PAGE ERASE // invoke SPM_CLEAR_PAGE (erases target page writing // the 0xff value ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_ERASE,"); // do magic break; case 0x01: // FILL TEMPORARY BUFFER ESIL_A ("r1,r0,"); // push data ESIL_A ("z,"); // push target address ESIL_A ("SPM_PAGE_FILL,"); // do magic break; case 0x05: // WRITE PAGE ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_WRITE,"); // do magic break; default: eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n", (unsigned int) spmcsr); } op->cycles = 1; // This is truly false. Datasheets do not publish how // many cycles this instruction uses in all its // operation modes and I am pretty sure that this value // can vary substantially from one MCU type to another. // So... one cycle is fine. } INST_HANDLER (st) { // ST X, Rr // ST X+, Rr // ST -X, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post increment : 0, // no increment 0, // offset always 0 1); // store operation (st) // // cycles // op->cycles = buf[0] & 0x3 == 0 // ? 2 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (std) { // ST Y, Rr ST Z, Rr // ST Y+, Rr ST Z+, Rr // ST -Y, Rr ST -Z, Rr // ST Y+q, Rr ST Z+q, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? (buf[1] & 0x20) // offset | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7) : 0, // no offset 1); // load operation (!st) // // cycles // op->cycles = // buf[1] & 0x1 == 0 // ? !(offset ? 1 : 3) // LDD // : buf[0] & 0x3 == 0 // ? 1 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (swap) { // SWAP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf ESIL_A ("|,", d); // S[0] | S[1] ESIL_A ("r%d,=,", d); // Rd = result } OPCODE_DESC opcodes[] = { // op mask select cycles size type INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ... INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+ INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+ INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+ INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+ INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A //INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr INST_LAST }; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) { CPU_MODEL *cpu; ut64 offset; // init op if (!op) { return 2; } // select cpu info cpu = get_cpu_model (anal->cpu); // set memory layout registers if (anal->esil) { offset = 0; r_anal_esil_reg_write (anal->esil, "_prog", offset); offset += (1 << cpu->pc); r_anal_esil_reg_write (anal->esil, "_io", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start")); r_anal_esil_reg_write (anal->esil, "_sram", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size")); r_anal_esil_reg_write (anal->esil, "_eeprom", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size")); r_anal_esil_reg_write (anal->esil, "_page", offset); } // process opcode avr_op_analyze (anal, op, addr, buf, len, cpu); return op->size; } static int avr_custom_des (RAnalEsil *esil) { ut64 key, encrypt, text,des_round; ut32 key_lo, key_hi, buf_lo, buf_hi; if (!esil || !esil->anal || !esil->anal->reg) { return false; } if (!__esil_pop_argument (esil, &des_round)) { return false; } r_anal_esil_reg_read (esil, "hf", &encrypt, NULL); r_anal_esil_reg_read (esil, "deskey", &key, NULL); r_anal_esil_reg_read (esil, "text", &text, NULL); key_lo = key & UT32_MAX; key_hi = key >> 32; buf_lo = text & UT32_MAX; buf_hi = text >> 32; if (des_round != desctx.round) { desctx.round = des_round; } if (!desctx.round) { int i; //generating all round keys r_des_permute_key (&key_lo, &key_hi); for (i = 0; i < 16; i++) { r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi); } r_des_permute_block0 (&buf_lo, &buf_hi); } if (encrypt) { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]); } else { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]); } if (desctx.round == 15) { r_des_permute_block1 (&buf_hi, &buf_lo); desctx.round = 0; } else { desctx.round++; } r_anal_esil_reg_write (esil, "text", text); return true; } // ESIL operation SPM_PAGE_ERASE static int avr_custom_spm_page_erase(RAnalEsil *esil) { CPU_MODEL *cpu; ut8 c; ut64 addr, page_size_bits, i; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument(esil, &addr)) { return false; } // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align base address to page_size_bits addr &= ~(MASK (page_size_bits)); // perform erase //eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); c = 0xff; for (i = 0; i < (1ULL << page_size_bits); i++) { r_anal_esil_mem_write ( esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1); } return true; } // ESIL operation SPM_PAGE_FILL static int avr_custom_spm_page_fill(RAnalEsil *esil) { CPU_MODEL *cpu; ut64 addr, page_size_bits, i; ut8 r0, r1; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address, r0, r1 if (!__esil_pop_argument(esil, &addr)) { return false; } if (!__esil_pop_argument (esil, &i)) { return false; } r0 = i; if (!__esil_pop_argument (esil, &i)) { return false; } r1 = i; // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align and crop base address addr &= (MASK (page_size_bits) ^ 1); // perform write to temporary page //eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr); r_anal_esil_mem_write (esil, addr++, &r0, 1); r_anal_esil_mem_write (esil, addr++, &r1, 1); return true; } // ESIL operation SPM_PAGE_WRITE static int avr_custom_spm_page_write(RAnalEsil *esil) { CPU_MODEL *cpu; char *t = NULL; ut64 addr, page_size_bits, tmp_page; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument (esil, &addr)) { return false; } // get details about current MCU and fix input address and base address // of the internal temporary page cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL); // align base address to page_size_bits addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu)); // perform writing //eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); if (!(t = malloc (1 << page_size_bits))) { eprintf ("Cannot alloc a buffer for copying the temporary page.\n"); return false; } r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits); r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits); return true; } static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) { CPU_MODEL *cpu; if (!esil || !esil->anal) { return 0; } // select cpu info cpu = get_cpu_model (esil->anal->cpu); // crop registers and force certain values if (!strcmp (name, "pc")) { *val &= CPU_PC_MASK (cpu); } else if (!strcmp (name, "pcl")) { if (cpu->pc < 8) { *val &= MASK (8); } } else if (!strcmp (name, "pch")) { *val = cpu->pc > 8 ? *val & MASK (cpu->pc - 8) : 0; } return 0; } static int esil_avr_init(RAnalEsil *esil) { if (!esil) { return false; } desctx.round = 0; r_anal_esil_set_op (esil, "des", avr_custom_des); r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase); r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill); r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write); esil->cb.hook_reg_write = esil_avr_hook_reg_write; return true; } static int esil_avr_fini(RAnalEsil *esil) { return true; } static int set_reg_profile(RAnal *anal) { const char *p = "=PC pcl\n" "=SP sp\n" // explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html // and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file "=A0 r25\n" "=A1 r24\n" "=A2 r23\n" "=A3 r22\n" "=R0 r24\n" #if 0 PC: 16- or 22-bit program counter SP: 8- or 16-bit stack pointer SREG: 8-bit status register RAMPX, RAMPY, RAMPZ, RAMPD and EIND: #endif // 8bit registers x 32 "gpr r0 .8 0 0\n" "gpr r1 .8 1 0\n" "gpr r2 .8 2 0\n" "gpr r3 .8 3 0\n" "gpr r4 .8 4 0\n" "gpr r5 .8 5 0\n" "gpr r6 .8 6 0\n" "gpr r7 .8 7 0\n" "gpr text .64 0 0\n" "gpr r8 .8 8 0\n" "gpr r9 .8 9 0\n" "gpr r10 .8 10 0\n" "gpr r11 .8 11 0\n" "gpr r12 .8 12 0\n" "gpr r13 .8 13 0\n" "gpr r14 .8 14 0\n" "gpr r15 .8 15 0\n" "gpr deskey .64 8 0\n" "gpr r16 .8 16 0\n" "gpr r17 .8 17 0\n" "gpr r18 .8 18 0\n" "gpr r19 .8 19 0\n" "gpr r20 .8 20 0\n" "gpr r21 .8 21 0\n" "gpr r22 .8 22 0\n" "gpr r23 .8 23 0\n" "gpr r24 .8 24 0\n" "gpr r25 .8 25 0\n" "gpr r26 .8 26 0\n" "gpr r27 .8 27 0\n" "gpr r28 .8 28 0\n" "gpr r29 .8 29 0\n" "gpr r30 .8 30 0\n" "gpr r31 .8 31 0\n" // 16 bit overlapped registers for 16 bit math "gpr r17:r16 .16 16 0\n" "gpr r19:r18 .16 18 0\n" "gpr r21:r20 .16 20 0\n" "gpr r23:r22 .16 22 0\n" "gpr r25:r24 .16 24 0\n" "gpr r27:r26 .16 26 0\n" "gpr r29:r28 .16 28 0\n" "gpr r31:r30 .16 30 0\n" // 16 bit overlapped registers for memory addressing "gpr x .16 26 0\n" "gpr y .16 28 0\n" "gpr z .16 30 0\n" // program counter // NOTE: program counter size in AVR depends on the CPU model. It seems that // the PC may range from 16 bits to 22 bits. "gpr pc .32 32 0\n" "gpr pcl .16 32 0\n" "gpr pch .16 34 0\n" // special purpose registers "gpr sp .16 36 0\n" "gpr spl .8 36 0\n" "gpr sph .8 37 0\n" // status bit register (SREG) "gpr sreg .8 38 0\n" "gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts. "gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero. "gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result. "gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow. "gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison. "gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic. "gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit. "gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled. // 8bit segment registers to be added to X, Y, Z to get 24bit offsets "gpr rampx .8 39 0\n" "gpr rampy .8 40 0\n" "gpr rampz .8 41 0\n" "gpr rampd .8 42 0\n" "gpr eind .8 43 0\n" // memory mapping emulator registers // _prog // the program flash. It has its own address space. // _ram // _io // start of the data addres space. It is the same address of IO, // because IO is the first memory space addressable in the AVR. // _sram // start of the SRAM (this offset depends on IO size, and it is // inside the _ram address space) // _eeprom // this is another address space, outside ram and flash // _page // this is the temporary page used by the SPM instruction. This // memory is not directly addressable and it is used internally by // the CPU when autoflashing. "gpr _prog .32 44 0\n" "gpr _page .32 48 0\n" "gpr _eeprom .32 52 0\n" "gpr _ram .32 56 0\n" "gpr _io .32 56 0\n" "gpr _sram .32 60 0\n" // other important MCU registers // spmcsr/spmcr // Store Program Memory Control and Status Register (SPMCSR) "gpr spmcsr .8 64 0\n" ; return r_reg_set_profile_string (anal->reg, p); } static int archinfo(RAnal *anal, int q) { if (q == R_ANAL_ARCHINFO_ALIGN) return 2; if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE) return 4; if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE) return 2; return 2; // XXX } static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) { RAnalOp *op = NULL; ut8 *ret = NULL; int idx; if (!(op = r_anal_op_new ())) { return NULL; } if (!(ret = malloc (size))) { r_anal_op_free (op); return NULL; } memset (ret, 0xff, size); CPU_MODEL *cpu = get_cpu_model (anal->cpu); for (idx = 0; idx + 1 < size; idx += op->size) { OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu); if (op->size < 1) { break; } if (!opcode_desc) { // invalid instruction continue; } // the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching // (things like memory offsets or jump addresses) if (op->size == 4) { ret[idx + 2] = 0; ret[idx + 3] = 0; } if (op->ptr != UT64_MAX || op->jump != UT64_MAX) { ret[idx] = opcode_desc->mask; ret[idx + 1] = opcode_desc->mask >> 8; } } r_anal_op_free (op); return ret; } RAnalPlugin r_anal_plugin_avr = { .name = "avr", .desc = "AVR code analysis plugin", .license = "LGPL3", .arch = "avr", .esil = true, .archinfo = archinfo, .bits = 8 | 16, // 24 big regs conflicts .op = &avr_op, .set_reg_profile = &set_reg_profile, .esil_init = esil_avr_init, .esil_fini = esil_avr_fini, .anal_mask = anal_mask_avr, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_avr, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_147_0
crossvul-cpp_data_good_4831_1
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2013 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // read_words.c // This module provides entropy word decoding functions using // a variation on the Rice method. This was introduced in version 3.93 // because it allows splitting the data into a "lossy" stream and a // "correction" stream in a very efficient manner and is therefore ideal // for the "hybrid" mode. For 4.0, the efficiency of this method was // significantly improved by moving away from the normal Rice restriction of // using powers of two for the modulus divisions and now the method can be // used for both hybrid and pure lossless encoding. // Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%), // and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the // previous. Using standard Rice coding on this data would result in 1.4 // bits per sample average (not counting sign bit). However, there is a // very simple encoding that is over 99% efficient with this data and // results in about 1.22 bits per sample. #include <stdlib.h> #include <string.h> #include "wavpack_local.h" #if defined (HAVE___BUILTIN_CTZ) || defined (_WIN64) #define USE_CTZ_OPTIMIZATION // use ctz intrinsic (or Windows equivalent) to count trailing ones #else #define USE_NEXT8_OPTIMIZATION // optimization using a table to count trailing ones #endif #define USE_BITMASK_TABLES // use tables instead of shifting for certain masking operations ///////////////////////////// local table storage //////////////////////////// #ifdef USE_NEXT8_OPTIMIZATION static const char ones_count_table [] = { 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8 }; #endif ///////////////////////////// executable code //////////////////////////////// static uint32_t __inline read_code (Bitstream *bs, uint32_t maxcode); // Read the next word from the bitstream "wvbits" and return the value. This // function can be used for hybrid or lossless streams, but since an // optimized version is available for lossless this function would normally // be used for hybrid only. If a hybrid lossless stream is being read then // the "correction" offset is written at the specified pointer. A return value // of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or // some other error occurred. int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction) { register struct entropy_data *c = wps->w.c + chan; uint32_t ones_count, low, mid, high; int32_t value; int sign; if (!wps->wvbits.ptr) return WORD_EOF; if (correction) *correction = 0; if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) { uint32_t mask; int cbits; if (wps->w.zeros_acc) { if (--wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; return 0; } } else { for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) wps->w.zeros_acc = cbits; else { for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) wps->w.zeros_acc |= mask; wps->w.zeros_acc |= mask; } if (wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; CLEAR (wps->w.c [0].median); CLEAR (wps->w.c [1].median); return 0; } } } if (wps->w.holding_zero) ones_count = wps->w.holding_zero = 0; else { #ifdef USE_CTZ_OPTIMIZATION while (wps->wvbits.bc < LIMIT_ONES) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } #ifdef _WIN32 _BitScanForward (&ones_count, ~wps->wvbits.sr); #else ones_count = __builtin_ctz (~wps->wvbits.sr); #endif if (ones_count >= LIMIT_ONES) { wps->wvbits.bc -= ones_count; wps->wvbits.sr >>= ones_count; for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= ones_count + 1; wps->wvbits.sr >>= ones_count + 1; } #elif defined (USE_NEXT8_OPTIMIZATION) int next8; if (wps->wvbits.bc < 8) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } else next8 = wps->wvbits.sr & 0xff; if (next8 == 0xff) { wps->wvbits.bc -= 8; wps->wvbits.sr >>= 8; for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1; wps->wvbits.sr >>= ones_count + 1; } #else for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count >= LIMIT_ONES) { uint32_t mask; int cbits; if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } #endif if (wps->w.holding_one) { wps->w.holding_one = ones_count & 1; ones_count = (ones_count >> 1) + 1; } else { wps->w.holding_one = ones_count & 1; ones_count >>= 1; } wps->w.holding_zero = ~wps->w.holding_one & 1; } if ((wps->wphdr.flags & HYBRID_FLAG) && !chan) update_error_limit (wps); if (ones_count == 0) { low = 0; high = GET_MED (0) - 1; DEC_MED0 (); } else { low = GET_MED (0); INC_MED0 (); if (ones_count == 1) { high = low + GET_MED (1) - 1; DEC_MED1 (); } else { low += GET_MED (1); INC_MED1 (); if (ones_count == 2) { high = low + GET_MED (2) - 1; DEC_MED2 (); } else { low += (ones_count - 2) * GET_MED (2); high = low + GET_MED (2) - 1; INC_MED2 (); } } } low &= 0x7fffffff; high &= 0x7fffffff; if (low > high) // make sure high and low make sense high = low; mid = (high + low + 1) >> 1; if (!c->error_limit) mid = read_code (&wps->wvbits, high - low) + low; else while (high - low > c->error_limit) { if (getbit (&wps->wvbits)) mid = (high + (low = mid) + 1) >> 1; else mid = ((high = mid - 1) + low + 1) >> 1; } sign = getbit (&wps->wvbits); if (bs_is_open (&wps->wvcbits) && c->error_limit) { value = read_code (&wps->wvcbits, high - low) + low; if (correction) *correction = sign ? (mid - value) : (value - mid); } if (wps->wphdr.flags & HYBRID_BITRATE) { c->slow_level -= (c->slow_level + SLO) >> SLS; c->slow_level += wp_log2 (mid); } return sign ? ~mid : mid; } // This is an optimized version of get_word() that is used for lossless only // (error_limit == 0). Also, rather than obtaining a single sample, it can be // used to obtain an entire buffer of either mono or stereo samples. int32_t get_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples) { struct entropy_data *c = wps->w.c; uint32_t ones_count, low, high; Bitstream *bs = &wps->wvbits; int32_t csamples; #ifdef USE_NEXT8_OPTIMIZATION int32_t next8; #endif if (nsamples && !bs->ptr) { memset (buffer, 0, (wps->wphdr.flags & MONO_DATA) ? nsamples * 4 : nsamples * 8); return nsamples; } if (!(wps->wphdr.flags & MONO_DATA)) nsamples *= 2; for (csamples = 0; csamples < nsamples; ++csamples) { if (!(wps->wphdr.flags & MONO_DATA)) c = wps->w.c + (csamples & 1); if (wps->w.holding_zero) { wps->w.holding_zero = 0; low = read_code (bs, GET_MED (0) - 1); DEC_MED0 (); buffer [csamples] = (getbit (bs)) ? ~low : low; if (++csamples == nsamples) break; if (!(wps->wphdr.flags & MONO_DATA)) c = wps->w.c + (csamples & 1); } if (wps->w.c [0].median [0] < 2 && !wps->w.holding_one && wps->w.c [1].median [0] < 2) { uint32_t mask; int cbits; if (wps->w.zeros_acc) { if (--wps->w.zeros_acc) { buffer [csamples] = 0; continue; } } else { for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) wps->w.zeros_acc = cbits; else { for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1) if (getbit (bs)) wps->w.zeros_acc |= mask; wps->w.zeros_acc |= mask; } if (wps->w.zeros_acc) { CLEAR (wps->w.c [0].median); CLEAR (wps->w.c [1].median); buffer [csamples] = 0; continue; } } } #ifdef USE_CTZ_OPTIMIZATION while (bs->bc < LIMIT_ONES) { if (++(bs->ptr) == bs->end) bs->wrap (bs); bs->sr |= *(bs->ptr) << bs->bc; bs->bc += sizeof (*(bs->ptr)) * 8; } #ifdef _WIN32 _BitScanForward (&ones_count, ~wps->wvbits.sr); #else ones_count = __builtin_ctz (~wps->wvbits.sr); #endif if (ones_count >= LIMIT_ONES) { bs->bc -= ones_count; bs->sr >>= ones_count; for (; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) break; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (bs)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { bs->bc -= ones_count + 1; bs->sr >>= ones_count + 1; } #elif defined (USE_NEXT8_OPTIMIZATION) if (bs->bc < 8) { if (++(bs->ptr) == bs->end) bs->wrap (bs); next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff; bs->bc += sizeof (*(bs->ptr)) * 8; } else next8 = bs->sr & 0xff; if (next8 == 0xff) { bs->bc -= 8; bs->sr >>= 8; for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) break; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (bs)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { bs->bc -= (ones_count = ones_count_table [next8]) + 1; bs->sr >>= ones_count + 1; } #else for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count); if (ones_count >= LIMIT_ONES) { uint32_t mask; int cbits; if (ones_count == (LIMIT_ONES + 1)) break; for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (bs)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } #endif low = wps->w.holding_one; wps->w.holding_one = ones_count & 1; wps->w.holding_zero = ~ones_count & 1; ones_count = (ones_count >> 1) + low; if (ones_count == 0) { low = 0; high = GET_MED (0) - 1; DEC_MED0 (); } else { low = GET_MED (0); INC_MED0 (); if (ones_count == 1) { high = low + GET_MED (1) - 1; DEC_MED1 (); } else { low += GET_MED (1); INC_MED1 (); if (ones_count == 2) { high = low + GET_MED (2) - 1; DEC_MED2 (); } else { low += (ones_count - 2) * GET_MED (2); high = low + GET_MED (2) - 1; INC_MED2 (); } } } low += read_code (bs, high - low); buffer [csamples] = (getbit (bs)) ? ~low : low; } return (wps->wphdr.flags & MONO_DATA) ? csamples : (csamples / 2); } // Read a single unsigned value from the specified bitstream with a value // from 0 to maxcode. If there are exactly a power of two number of possible // codes then this will read a fixed number of bits; otherwise it reads the // minimum number of bits and then determines whether another bit is needed // to define the code. static uint32_t __inline read_code (Bitstream *bs, uint32_t maxcode) { unsigned long local_sr; uint32_t extras, code; int bitcount; if (maxcode < 2) return maxcode ? getbit (bs) : 0; bitcount = count_bits (maxcode); #ifdef USE_BITMASK_TABLES extras = bitset [bitcount] - maxcode - 1; #else extras = (1 << bitcount) - maxcode - 1; #endif local_sr = bs->sr; while (bs->bc < bitcount) { if (++(bs->ptr) == bs->end) bs->wrap (bs); local_sr |= (long)*(bs->ptr) << bs->bc; bs->bc += sizeof (*(bs->ptr)) * 8; } #ifdef USE_BITMASK_TABLES if ((code = local_sr & bitmask [bitcount - 1]) >= extras) #else if ((code = local_sr & ((1 << (bitcount - 1)) - 1)) >= extras) #endif code = (code << 1) - extras + ((local_sr >> (bitcount - 1)) & 1); else bitcount--; if (sizeof (local_sr) < 8 && bs->bc > sizeof (local_sr) * 8) { bs->bc -= bitcount; bs->sr = *(bs->ptr) >> (sizeof (*(bs->ptr)) * 8 - bs->bc); } else { bs->bc -= bitcount; bs->sr = local_sr >> bitcount; } return code; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_4831_1
crossvul-cpp_data_good_3943_0
/** * WinPR: Windows Portable Runtime * NTLM Security Package (Compute) * * Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <assert.h> #include "ntlm.h" #include "../sspi.h" #include <winpr/crt.h> #include <winpr/sam.h> #include <winpr/ntlm.h> #include <winpr/print.h> #include <winpr/crypto.h> #include <winpr/sysinfo.h> #include "ntlm_compute.h" #include "../../log.h" #define TAG WINPR_TAG("sspi.NTLM") const char LM_MAGIC[] = "KGS!@#$%"; static const char NTLM_CLIENT_SIGN_MAGIC[] = "session key to client-to-server signing key magic constant"; static const char NTLM_SERVER_SIGN_MAGIC[] = "session key to server-to-client signing key magic constant"; static const char NTLM_CLIENT_SEAL_MAGIC[] = "session key to client-to-server sealing key magic constant"; static const char NTLM_SERVER_SEAL_MAGIC[] = "session key to server-to-client sealing key magic constant"; static const BYTE NTLM_NULL_BUFFER[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /** * Populate VERSION structure. * VERSION @msdn{cc236654} * @param s */ void ntlm_get_version_info(NTLM_VERSION_INFO* versionInfo) { OSVERSIONINFOA osVersionInfo; osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); GetVersionExA(&osVersionInfo); versionInfo->ProductMajorVersion = (UINT8)osVersionInfo.dwMajorVersion; versionInfo->ProductMinorVersion = (UINT8)osVersionInfo.dwMinorVersion; versionInfo->ProductBuild = (UINT16)osVersionInfo.dwBuildNumber; ZeroMemory(versionInfo->Reserved, sizeof(versionInfo->Reserved)); versionInfo->NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3; } /** * Read VERSION structure. * VERSION @msdn{cc236654} * @param s */ int ntlm_read_version_info(wStream* s, NTLM_VERSION_INFO* versionInfo) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */ Stream_Read_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */ Stream_Read_UINT16(s, versionInfo->ProductBuild); /* ProductBuild (2 bytes) */ Stream_Read(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */ Stream_Read_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */ return 1; } /** * Write VERSION structure. * VERSION @msdn{cc236654} * @param s */ void ntlm_write_version_info(wStream* s, NTLM_VERSION_INFO* versionInfo) { Stream_Write_UINT8(s, versionInfo->ProductMajorVersion); /* ProductMajorVersion (1 byte) */ Stream_Write_UINT8(s, versionInfo->ProductMinorVersion); /* ProductMinorVersion (1 byte) */ Stream_Write_UINT16(s, versionInfo->ProductBuild); /* ProductBuild (2 bytes) */ Stream_Write(s, versionInfo->Reserved, sizeof(versionInfo->Reserved)); /* Reserved (3 bytes) */ Stream_Write_UINT8(s, versionInfo->NTLMRevisionCurrent); /* NTLMRevisionCurrent (1 byte) */ } /** * Print VERSION structure. * VERSION @msdn{cc236654} * @param s */ void ntlm_print_version_info(NTLM_VERSION_INFO* versionInfo) { WLog_INFO(TAG, "VERSION ={"); WLog_INFO(TAG, "\tProductMajorVersion: %" PRIu8 "", versionInfo->ProductMajorVersion); WLog_INFO(TAG, "\tProductMinorVersion: %" PRIu8 "", versionInfo->ProductMinorVersion); WLog_INFO(TAG, "\tProductBuild: %" PRIu16 "", versionInfo->ProductBuild); WLog_INFO(TAG, "\tReserved: 0x%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "", versionInfo->Reserved[0], versionInfo->Reserved[1], versionInfo->Reserved[2]); WLog_INFO(TAG, "\tNTLMRevisionCurrent: 0x%02" PRIX8 "", versionInfo->NTLMRevisionCurrent); } static int ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge) { size_t size; if (Stream_GetRemainingLength(s) < 28) return -1; Stream_Read_UINT8(s, challenge->RespType); Stream_Read_UINT8(s, challenge->HiRespType); Stream_Read_UINT16(s, challenge->Reserved1); Stream_Read_UINT32(s, challenge->Reserved2); Stream_Read(s, challenge->Timestamp, 8); Stream_Read(s, challenge->ClientChallenge, 8); Stream_Read_UINT32(s, challenge->Reserved3); size = Stream_Length(s) - Stream_GetPosition(s); if (size > UINT32_MAX) return -1; challenge->cbAvPairs = size; challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs); if (!challenge->AvPairs) return -1; Stream_Read(s, challenge->AvPairs, size); return 1; } static int ntlm_write_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge) { ULONG length; Stream_Write_UINT8(s, challenge->RespType); Stream_Write_UINT8(s, challenge->HiRespType); Stream_Write_UINT16(s, challenge->Reserved1); Stream_Write_UINT32(s, challenge->Reserved2); Stream_Write(s, challenge->Timestamp, 8); Stream_Write(s, challenge->ClientChallenge, 8); Stream_Write_UINT32(s, challenge->Reserved3); length = ntlm_av_pair_list_length(challenge->AvPairs, challenge->cbAvPairs); Stream_Write(s, challenge->AvPairs, length); return 1; } int ntlm_read_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response) { if (Stream_GetRemainingLength(s) < 16) return -1; Stream_Read(s, response->Response, 16); return ntlm_read_ntlm_v2_client_challenge(s, &(response->Challenge)); } int ntlm_write_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response) { Stream_Write(s, response->Response, 16); return ntlm_write_ntlm_v2_client_challenge(s, &(response->Challenge)); } /** * Get current time, in tenths of microseconds since midnight of January 1, 1601. * @param[out] timestamp 64-bit little-endian timestamp */ void ntlm_current_time(BYTE* timestamp) { FILETIME filetime; ULARGE_INTEGER time64; GetSystemTimeAsFileTime(&filetime); time64.u.LowPart = filetime.dwLowDateTime; time64.u.HighPart = filetime.dwHighDateTime; CopyMemory(timestamp, &(time64.QuadPart), 8); } /** * Generate timestamp for AUTHENTICATE_MESSAGE. * @param NTLM context */ void ntlm_generate_timestamp(NTLM_CONTEXT* context) { if (memcmp(context->ChallengeTimestamp, NTLM_NULL_BUFFER, 8) != 0) CopyMemory(context->Timestamp, context->ChallengeTimestamp, 8); else ntlm_current_time(context->Timestamp); } static int ntlm_fetch_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash) { WINPR_SAM* sam; WINPR_SAM_ENTRY* entry; SSPI_CREDENTIALS* credentials = context->credentials; sam = SamOpen(context->SamFile, TRUE); if (!sam) return -1; entry = SamLookupUserW( sam, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2); if (entry) { #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NTLM Hash:"); winpr_HexDump(TAG, WLOG_DEBUG, entry->NtHash, 16); #endif NTOWFv2FromHashW(entry->NtHash, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, (BYTE*)hash); SamFreeEntry(sam, entry); SamClose(sam); return 1; } entry = SamLookupUserW(sam, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, NULL, 0); if (entry) { #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NTLM Hash:"); winpr_HexDump(TAG, WLOG_DEBUG, entry->NtHash, 16); #endif NTOWFv2FromHashW(entry->NtHash, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, (BYTE*)hash); SamFreeEntry(sam, entry); SamClose(sam); return 1; } else { SamClose(sam); WLog_ERR(TAG, "Error: Could not find user in SAM database"); return 0; } SamClose(sam); return 1; } static int ntlm_convert_password_hash(NTLM_CONTEXT* context, BYTE* hash) { int status; int i, hn, ln; char* PasswordHash = NULL; UINT32 PasswordHashLength = 0; SSPI_CREDENTIALS* credentials = context->credentials; /* Password contains a password hash of length (PasswordLength - * SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) */ PasswordHashLength = credentials->identity.PasswordLength - SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; status = ConvertFromUnicode(CP_UTF8, 0, (LPCWSTR)credentials->identity.Password, PasswordHashLength, &PasswordHash, 0, NULL, NULL); if (status <= 0) return -1; CharUpperBuffA(PasswordHash, PasswordHashLength); for (i = 0; i < 32; i += 2) { hn = PasswordHash[i] > '9' ? PasswordHash[i] - 'A' + 10 : PasswordHash[i] - '0'; ln = PasswordHash[i + 1] > '9' ? PasswordHash[i + 1] - 'A' + 10 : PasswordHash[i + 1] - '0'; hash[i / 2] = (hn << 4) | ln; } free(PasswordHash); return 1; } static int ntlm_compute_ntlm_v2_hash(NTLM_CONTEXT* context, BYTE* hash) { SSPI_CREDENTIALS* credentials = context->credentials; #ifdef WITH_DEBUG_NTLM if (credentials) { WLog_DBG(TAG, "Password (length = %" PRIu32 ")", credentials->identity.PasswordLength * 2); winpr_HexDump(TAG, WLOG_DEBUG, (BYTE*)credentials->identity.Password, credentials->identity.PasswordLength * 2); WLog_DBG(TAG, "Username (length = %" PRIu32 ")", credentials->identity.UserLength * 2); winpr_HexDump(TAG, WLOG_DEBUG, (BYTE*)credentials->identity.User, credentials->identity.UserLength * 2); WLog_DBG(TAG, "Domain (length = %" PRIu32 ")", credentials->identity.DomainLength * 2); winpr_HexDump(TAG, WLOG_DEBUG, (BYTE*)credentials->identity.Domain, credentials->identity.DomainLength * 2); } else WLog_DBG(TAG, "Strange, NTLM_CONTEXT is missing valid credentials..."); WLog_DBG(TAG, "Workstation (length = %" PRIu16 ")", context->Workstation.Length); winpr_HexDump(TAG, WLOG_DEBUG, (BYTE*)context->Workstation.Buffer, context->Workstation.Length); WLog_DBG(TAG, "NTOWFv2, NTLMv2 Hash"); winpr_HexDump(TAG, WLOG_DEBUG, context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH); #endif if (memcmp(context->NtlmV2Hash, NTLM_NULL_BUFFER, 16) != 0) return 1; if (!credentials) return -1; else if (memcmp(context->NtlmHash, NTLM_NULL_BUFFER, 16) != 0) { NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, (BYTE*)hash); } else if (credentials->identity.PasswordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) { /* Special case for WinPR: password hash */ if (ntlm_convert_password_hash(context, context->NtlmHash) < 0) return -1; NTOWFv2FromHashW(context->NtlmHash, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, (BYTE*)hash); } else if (credentials->identity.Password) { NTOWFv2W((LPWSTR)credentials->identity.Password, credentials->identity.PasswordLength * 2, (LPWSTR)credentials->identity.User, credentials->identity.UserLength * 2, (LPWSTR)credentials->identity.Domain, credentials->identity.DomainLength * 2, (BYTE*)hash); } else if (context->HashCallback) { int ret; SecBuffer proofValue, micValue; if (ntlm_computeProofValue(context, &proofValue) != SEC_E_OK) return -1; if (ntlm_computeMicValue(context, &micValue) != SEC_E_OK) { sspi_SecBufferFree(&proofValue); return -1; } ret = context->HashCallback(context->HashCallbackArg, &credentials->identity, &proofValue, context->EncryptedRandomSessionKey, (&context->AUTHENTICATE_MESSAGE)->MessageIntegrityCheck, &micValue, hash); sspi_SecBufferFree(&proofValue); sspi_SecBufferFree(&micValue); return ret ? 1 : -1; } else if (context->UseSamFileDatabase) { return ntlm_fetch_ntlm_v2_hash(context, hash); } return 1; } int ntlm_compute_lm_v2_response(NTLM_CONTEXT* context) { BYTE* response; BYTE value[WINPR_MD5_DIGEST_LENGTH]; if (context->LmCompatibilityLevel < 2) { if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24)) return -1; ZeroMemory(context->LmChallengeResponse.pvBuffer, 24); return 1; } /* Compute the NTLMv2 hash */ if (ntlm_compute_ntlm_v2_hash(context, context->NtlmV2Hash) < 0) return -1; /* Concatenate the server and client challenges */ CopyMemory(value, context->ServerChallenge, 8); CopyMemory(&value[8], context->ClientChallenge, 8); if (!sspi_SecBufferAlloc(&context->LmChallengeResponse, 24)) return -1; response = (BYTE*)context->LmChallengeResponse.pvBuffer; /* Compute the HMAC-MD5 hash of the resulting value using the NTLMv2 hash as the key */ winpr_HMAC(WINPR_MD_MD5, (void*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, (BYTE*)value, WINPR_MD5_DIGEST_LENGTH, (BYTE*)response, WINPR_MD5_DIGEST_LENGTH); /* Concatenate the resulting HMAC-MD5 hash and the client challenge, giving us the LMv2 response * (24 bytes) */ CopyMemory(&response[16], context->ClientChallenge, 8); return 1; } /** * Compute NTLMv2 Response. * NTLMv2_RESPONSE @msdn{cc236653} * NTLMv2 Authentication @msdn{cc236700} * @param NTLM context */ int ntlm_compute_ntlm_v2_response(NTLM_CONTEXT* context) { BYTE* blob; SecBuffer ntlm_v2_temp = { 0 }; SecBuffer ntlm_v2_temp_chal = { 0 }; PSecBuffer TargetInfo = &context->ChallengeTargetInfo; int ret = -1; if (!sspi_SecBufferAlloc(&ntlm_v2_temp, TargetInfo->cbBuffer + 28)) goto exit; ZeroMemory(ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); blob = (BYTE*)ntlm_v2_temp.pvBuffer; /* Compute the NTLMv2 hash */ if (ntlm_compute_ntlm_v2_hash(context, (BYTE*)context->NtlmV2Hash) < 0) goto exit; /* Construct temp */ blob[0] = 1; /* RespType (1 byte) */ blob[1] = 1; /* HighRespType (1 byte) */ /* Reserved1 (2 bytes) */ /* Reserved2 (4 bytes) */ CopyMemory(&blob[8], context->Timestamp, 8); /* Timestamp (8 bytes) */ CopyMemory(&blob[16], context->ClientChallenge, 8); /* ClientChallenge (8 bytes) */ /* Reserved3 (4 bytes) */ CopyMemory(&blob[28], TargetInfo->pvBuffer, TargetInfo->cbBuffer); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NTLMv2 Response Temp Blob"); winpr_HexDump(TAG, WLOG_DEBUG, ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); #endif /* Concatenate server challenge with temp */ if (!sspi_SecBufferAlloc(&ntlm_v2_temp_chal, ntlm_v2_temp.cbBuffer + 8)) goto exit; blob = (BYTE*)ntlm_v2_temp_chal.pvBuffer; CopyMemory(blob, context->ServerChallenge, 8); CopyMemory(&blob[8], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, (BYTE*)ntlm_v2_temp_chal.pvBuffer, ntlm_v2_temp_chal.cbBuffer, context->NtProofString, WINPR_MD5_DIGEST_LENGTH); /* NtChallengeResponse, Concatenate NTProofStr with temp */ if (!sspi_SecBufferAlloc(&context->NtChallengeResponse, ntlm_v2_temp.cbBuffer + 16)) goto exit; blob = (BYTE*)context->NtChallengeResponse.pvBuffer; CopyMemory(blob, context->NtProofString, WINPR_MD5_DIGEST_LENGTH); CopyMemory(&blob[16], ntlm_v2_temp.pvBuffer, ntlm_v2_temp.cbBuffer); /* Compute SessionBaseKey, the HMAC-MD5 hash of NTProofStr using the NTLMv2 hash as the key */ winpr_HMAC(WINPR_MD_MD5, (BYTE*)context->NtlmV2Hash, WINPR_MD5_DIGEST_LENGTH, context->NtProofString, WINPR_MD5_DIGEST_LENGTH, context->SessionBaseKey, WINPR_MD5_DIGEST_LENGTH); ret = 1; exit: sspi_SecBufferFree(&ntlm_v2_temp); sspi_SecBufferFree(&ntlm_v2_temp_chal); return ret; } /** * Encrypt the given plain text using RC4 and the given key. * @param key RC4 key * @param length text length * @param plaintext plain text * @param ciphertext cipher text */ void ntlm_rc4k(BYTE* key, int length, BYTE* plaintext, BYTE* ciphertext) { WINPR_RC4_CTX* rc4 = winpr_RC4_New(key, 16); if (rc4) { winpr_RC4_Update(rc4, length, plaintext, ciphertext); winpr_RC4_Free(rc4); } } /** * Generate client challenge (8-byte nonce). * @param NTLM context */ void ntlm_generate_client_challenge(NTLM_CONTEXT* context) { /* ClientChallenge is used in computation of LMv2 and NTLMv2 responses */ if (memcmp(context->ClientChallenge, NTLM_NULL_BUFFER, 8) == 0) winpr_RAND(context->ClientChallenge, 8); } /** * Generate server challenge (8-byte nonce). * @param NTLM context */ void ntlm_generate_server_challenge(NTLM_CONTEXT* context) { if (memcmp(context->ServerChallenge, NTLM_NULL_BUFFER, 8) == 0) winpr_RAND(context->ServerChallenge, 8); } /** * Generate KeyExchangeKey (the 128-bit SessionBaseKey). * @msdn{cc236710} * @param NTLM context */ void ntlm_generate_key_exchange_key(NTLM_CONTEXT* context) { /* In NTLMv2, KeyExchangeKey is the 128-bit SessionBaseKey */ CopyMemory(context->KeyExchangeKey, context->SessionBaseKey, 16); } /** * Generate RandomSessionKey (16-byte nonce). * @param NTLM context */ void ntlm_generate_random_session_key(NTLM_CONTEXT* context) { winpr_RAND(context->RandomSessionKey, 16); } /** * Generate ExportedSessionKey (the RandomSessionKey, exported) * @param NTLM context */ void ntlm_generate_exported_session_key(NTLM_CONTEXT* context) { CopyMemory(context->ExportedSessionKey, context->RandomSessionKey, 16); } /** * Encrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key). * @param NTLM context */ void ntlm_encrypt_random_session_key(NTLM_CONTEXT* context) { /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the * KeyExchangeKey */ ntlm_rc4k(context->KeyExchangeKey, 16, context->RandomSessionKey, context->EncryptedRandomSessionKey); } /** * Decrypt RandomSessionKey (RC4-encrypted RandomSessionKey, using KeyExchangeKey as the key). * @param NTLM context */ void ntlm_decrypt_random_session_key(NTLM_CONTEXT* context) { /* In NTLMv2, EncryptedRandomSessionKey is the ExportedSessionKey RC4-encrypted with the * KeyExchangeKey */ /** * if (NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) * Set RandomSessionKey to RC4K(KeyExchangeKey, * AUTHENTICATE_MESSAGE.EncryptedRandomSessionKey) else Set RandomSessionKey to KeyExchangeKey */ if (context->NegotiateKeyExchange) ntlm_rc4k(context->KeyExchangeKey, 16, context->EncryptedRandomSessionKey, context->RandomSessionKey); else CopyMemory(context->RandomSessionKey, context->KeyExchangeKey, 16); } /** * Generate signing key. * @msdn{cc236711} * @param exported_session_key ExportedSessionKey * @param sign_magic Sign magic string * @param signing_key Destination signing key */ static int ntlm_generate_signing_key(BYTE* exported_session_key, PSecBuffer sign_magic, BYTE* signing_key) { int length; BYTE* value; length = WINPR_MD5_DIGEST_LENGTH + sign_magic->cbBuffer; value = (BYTE*)malloc(length); if (!value) return -1; /* Concatenate ExportedSessionKey with sign magic */ CopyMemory(value, exported_session_key, WINPR_MD5_DIGEST_LENGTH); CopyMemory(&value[WINPR_MD5_DIGEST_LENGTH], sign_magic->pvBuffer, sign_magic->cbBuffer); if (!winpr_Digest(WINPR_MD_MD5, value, length, signing_key, WINPR_MD5_DIGEST_LENGTH)) { free(value); return -1; } free(value); return 1; } /** * Generate client signing key (ClientSigningKey). * @msdn{cc236711} * @param NTLM context */ void ntlm_generate_client_signing_key(NTLM_CONTEXT* context) { SecBuffer signMagic; signMagic.pvBuffer = (void*)NTLM_CLIENT_SIGN_MAGIC; signMagic.cbBuffer = sizeof(NTLM_CLIENT_SIGN_MAGIC); ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic, context->ClientSigningKey); } /** * Generate server signing key (ServerSigningKey). * @msdn{cc236711} * @param NTLM context */ void ntlm_generate_server_signing_key(NTLM_CONTEXT* context) { SecBuffer signMagic; signMagic.pvBuffer = (void*)NTLM_SERVER_SIGN_MAGIC; signMagic.cbBuffer = sizeof(NTLM_SERVER_SIGN_MAGIC); ntlm_generate_signing_key(context->ExportedSessionKey, &signMagic, context->ServerSigningKey); } /** * Generate sealing key. * @msdn{cc236712} * @param exported_session_key ExportedSessionKey * @param seal_magic Seal magic string * @param sealing_key Destination sealing key */ static int ntlm_generate_sealing_key(BYTE* exported_session_key, PSecBuffer seal_magic, BYTE* sealing_key) { BYTE* p; SecBuffer buffer; if (!sspi_SecBufferAlloc(&buffer, WINPR_MD5_DIGEST_LENGTH + seal_magic->cbBuffer)) return -1; p = (BYTE*)buffer.pvBuffer; /* Concatenate ExportedSessionKey with seal magic */ CopyMemory(p, exported_session_key, WINPR_MD5_DIGEST_LENGTH); CopyMemory(&p[WINPR_MD5_DIGEST_LENGTH], seal_magic->pvBuffer, seal_magic->cbBuffer); if (!winpr_Digest(WINPR_MD_MD5, buffer.pvBuffer, buffer.cbBuffer, sealing_key, WINPR_MD5_DIGEST_LENGTH)) { sspi_SecBufferFree(&buffer); return -1; } sspi_SecBufferFree(&buffer); return 1; } /** * Generate client sealing key (ClientSealingKey). * @msdn{cc236712} * @param NTLM context */ void ntlm_generate_client_sealing_key(NTLM_CONTEXT* context) { SecBuffer sealMagic; sealMagic.pvBuffer = (void*)NTLM_CLIENT_SEAL_MAGIC; sealMagic.cbBuffer = sizeof(NTLM_CLIENT_SEAL_MAGIC); ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic, context->ClientSealingKey); } /** * Generate server sealing key (ServerSealingKey). * @msdn{cc236712} * @param NTLM context */ void ntlm_generate_server_sealing_key(NTLM_CONTEXT* context) { SecBuffer sealMagic; sealMagic.pvBuffer = (void*)NTLM_SERVER_SEAL_MAGIC; sealMagic.cbBuffer = sizeof(NTLM_SERVER_SEAL_MAGIC); ntlm_generate_signing_key(context->ExportedSessionKey, &sealMagic, context->ServerSealingKey); } /** * Initialize RC4 stream cipher states for sealing. * @param NTLM context */ void ntlm_init_rc4_seal_states(NTLM_CONTEXT* context) { if (context->server) { context->SendSigningKey = context->ServerSigningKey; context->RecvSigningKey = context->ClientSigningKey; context->SendSealingKey = context->ClientSealingKey; context->RecvSealingKey = context->ServerSealingKey; context->SendRc4Seal = winpr_RC4_New(context->ServerSealingKey, 16); context->RecvRc4Seal = winpr_RC4_New(context->ClientSealingKey, 16); } else { context->SendSigningKey = context->ClientSigningKey; context->RecvSigningKey = context->ServerSigningKey; context->SendSealingKey = context->ServerSealingKey; context->RecvSealingKey = context->ClientSealingKey; context->SendRc4Seal = winpr_RC4_New(context->ClientSealingKey, 16); context->RecvRc4Seal = winpr_RC4_New(context->ServerSealingKey, 16); } } void ntlm_compute_message_integrity_check(NTLM_CONTEXT* context, BYTE* mic, UINT32 size) { /* * Compute the HMAC-MD5 hash of ConcatenationOf(NEGOTIATE_MESSAGE, * CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE) using the ExportedSessionKey */ WINPR_HMAC_CTX* hmac = winpr_HMAC_New(); assert(size >= WINPR_MD5_DIGEST_LENGTH); if (!hmac) return; if (winpr_HMAC_Init(hmac, WINPR_MD_MD5, context->ExportedSessionKey, WINPR_MD5_DIGEST_LENGTH)) { winpr_HMAC_Update(hmac, (BYTE*)context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); winpr_HMAC_Update(hmac, (BYTE*)context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); winpr_HMAC_Update(hmac, (BYTE*)context->AuthenticateMessage.pvBuffer, context->AuthenticateMessage.cbBuffer); winpr_HMAC_Final(hmac, mic, WINPR_MD5_DIGEST_LENGTH); } winpr_HMAC_Free(hmac); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3943_0
crossvul-cpp_data_bad_5237_0
#ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /*! \brief Creates a gdImage from a TGA file * Creates a gdImage from a TGA binary file via a gdIOCtx. * \param infile Pointer to TGA binary file * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /*! \brief Creates a gdImage from a gdIOCtx * Creates a gdImage from a gdIOCtx referencing a TGA binary file. * \param ctx Pointer to a gdIOCtx structure * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; uint8_t* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int j = 0; uint8_t encoded_pixels; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < image_block_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 ); buffer_caret++; if (encoded_pixels != 0) { if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { for (j = 0; j < pixel_block_size; j++, bitmap_caret++) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } } } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if (encoded_pixels != 0) { if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } buffer_caret += pixel_block_size; } } } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5237_0
crossvul-cpp_data_good_1274_0
/*- * Copyright (c) 2003-2011 Tim Kientzle * Copyright (c) 2011-2012 Michihiro NAKAJIMA * 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 AUTHOR(S) ``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 AUTHOR(S) 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 "archive_platform.h" __FBSDID("$FreeBSD: head/lib/libarchive/archive_string.c 201095 2009-12-28 02:33:22Z kientzle $"); /* * Basic resizable string support, to simplify manipulating arbitrary-sized * strings while minimizing heap activity. * * In particular, the buffer used by a string object is only grown, it * never shrinks, so you can clear and reuse the same string object * without incurring additional memory allocations. */ #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_ICONV_H #include <iconv.h> #endif #ifdef HAVE_LANGINFO_H #include <langinfo.h> #endif #ifdef HAVE_LOCALCHARSET_H #include <localcharset.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_WCHAR_H #include <wchar.h> #endif #if defined(_WIN32) && !defined(__CYGWIN__) #include <windows.h> #include <locale.h> #endif #include "archive_endian.h" #include "archive_private.h" #include "archive_string.h" #include "archive_string_composition.h" #if !defined(HAVE_WMEMCPY) && !defined(wmemcpy) #define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t)) #endif #if !defined(HAVE_WMEMMOVE) && !defined(wmemmove) #define wmemmove(a,b,i) (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t)) #endif struct archive_string_conv { struct archive_string_conv *next; char *from_charset; char *to_charset; unsigned from_cp; unsigned to_cp; /* Set 1 if from_charset and to_charset are the same. */ int same; int flag; #define SCONV_TO_CHARSET 1 /* MBS is being converted to specified * charset. */ #define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from * specified charset. */ #define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */ #define SCONV_WIN_CP (1<<3) /* Use Windows API for converting * MBS. */ #define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive * 2.x in the wrong assumption. */ #define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C. * Before UTF-8 characters are actually * processed. */ #define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D. * Before UTF-8 characters are actually * processed. * Currently this only for MAC OS X. */ #define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */ #define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */ #define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */ #define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */ #define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */ #define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */ #define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE) #define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE) #if HAVE_ICONV iconv_t cd; iconv_t cd_w;/* Use at archive_mstring on * Windows. */ #endif /* A temporary buffer for normalization. */ struct archive_string utftmp; int (*converter[2])(struct archive_string *, const void *, size_t, struct archive_string_conv *); int nconverter; }; #define CP_C_LOCALE 0 /* "C" locale only for this file. */ #define CP_UTF16LE 1200 #define CP_UTF16BE 1201 #define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF) #define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF) #define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF) #define UNICODE_MAX 0x10FFFF #define UNICODE_R_CHAR 0xFFFD /* Replacement character. */ /* Set U+FFFD(Replacement character) in UTF-8. */ static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd}; static struct archive_string_conv *find_sconv_object(struct archive *, const char *, const char *); static void add_sconv_object(struct archive *, struct archive_string_conv *); static struct archive_string_conv *create_sconv_object(const char *, const char *, unsigned, int); static void free_sconv_object(struct archive_string_conv *); static struct archive_string_conv *get_sconv_object(struct archive *, const char *, const char *, int); static unsigned make_codepage_from_charset(const char *); static unsigned get_current_codepage(void); static unsigned get_current_oemcp(void); static size_t mbsnbytes(const void *, size_t); static size_t utf16nbytes(const void *, size_t); #if defined(_WIN32) && !defined(__CYGWIN__) static int archive_wstring_append_from_mbs_in_codepage( struct archive_wstring *, const char *, size_t, struct archive_string_conv *); static int archive_string_append_from_wcs_in_codepage(struct archive_string *, const wchar_t *, size_t, struct archive_string_conv *); static int is_big_endian(void); static int strncat_in_codepage(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_from_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_from_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_to_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_to_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); #endif static int best_effort_strncat_from_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_from_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_to_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_to_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); #if defined(HAVE_ICONV) static int iconv_strncat_in_locale(struct archive_string *, const void *, size_t, struct archive_string_conv *); #endif static int best_effort_strncat_in_locale(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int _utf8_to_unicode(uint32_t *, const char *, size_t); static int utf8_to_unicode(uint32_t *, const char *, size_t); static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t); static int cesu8_to_unicode(uint32_t *, const char *, size_t); static size_t unicode_to_utf8(char *, size_t, uint32_t); static int utf16_to_unicode(uint32_t *, const char *, size_t, int); static size_t unicode_to_utf16be(char *, size_t, uint32_t); static size_t unicode_to_utf16le(char *, size_t, uint32_t); static int strncat_from_utf8_libarchive2(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int strncat_from_utf8_to_utf8(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_normalize_C(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_normalize_D(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_append_unicode(struct archive_string *, const void *, size_t, struct archive_string_conv *); static struct archive_string * archive_string_append(struct archive_string *as, const char *p, size_t s) { if (archive_string_ensure(as, as->length + s + 1) == NULL) return (NULL); if (s) memmove(as->s + as->length, p, s); as->length += s; as->s[as->length] = 0; return (as); } static struct archive_wstring * archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s) { if (archive_wstring_ensure(as, as->length + s + 1) == NULL) return (NULL); if (s) wmemmove(as->s + as->length, p, s); as->length += s; as->s[as->length] = 0; return (as); } struct archive_string * archive_array_append(struct archive_string *as, const char *p, size_t s) { return archive_string_append(as, p, s); } void archive_string_concat(struct archive_string *dest, struct archive_string *src) { if (archive_string_append(dest, src->s, src->length) == NULL) __archive_errx(1, "Out of memory"); } void archive_wstring_concat(struct archive_wstring *dest, struct archive_wstring *src) { if (archive_wstring_append(dest, src->s, src->length) == NULL) __archive_errx(1, "Out of memory"); } void archive_string_free(struct archive_string *as) { as->length = 0; as->buffer_length = 0; free(as->s); as->s = NULL; } void archive_wstring_free(struct archive_wstring *as) { as->length = 0; as->buffer_length = 0; free(as->s); as->s = NULL; } struct archive_wstring * archive_wstring_ensure(struct archive_wstring *as, size_t s) { return (struct archive_wstring *) archive_string_ensure((struct archive_string *)as, s * sizeof(wchar_t)); } /* Returns NULL on any allocation failure. */ struct archive_string * archive_string_ensure(struct archive_string *as, size_t s) { char *p; size_t new_length; /* If buffer is already big enough, don't reallocate. */ if (as->s && (s <= as->buffer_length)) return (as); /* * Growing the buffer at least exponentially ensures that * append operations are always linear in the number of * characters appended. Using a smaller growth rate for * larger buffers reduces memory waste somewhat at the cost of * a larger constant factor. */ if (as->buffer_length < 32) /* Start with a minimum 32-character buffer. */ new_length = 32; else if (as->buffer_length < 8192) /* Buffers under 8k are doubled for speed. */ new_length = as->buffer_length + as->buffer_length; else { /* Buffers 8k and over grow by at least 25% each time. */ new_length = as->buffer_length + as->buffer_length / 4; /* Be safe: If size wraps, fail. */ if (new_length < as->buffer_length) { /* On failure, wipe the string and return NULL. */ archive_string_free(as); errno = ENOMEM;/* Make sure errno has ENOMEM. */ return (NULL); } } /* * The computation above is a lower limit to how much we'll * grow the buffer. In any case, we have to grow it enough to * hold the request. */ if (new_length < s) new_length = s; /* Now we can reallocate the buffer. */ p = (char *)realloc(as->s, new_length); if (p == NULL) { /* On failure, wipe the string and return NULL. */ archive_string_free(as); errno = ENOMEM;/* Make sure errno has ENOMEM. */ return (NULL); } as->s = p; as->buffer_length = new_length; return (as); } /* * TODO: See if there's a way to avoid scanning * the source string twice. Then test to see * if it actually helps (remember that we're almost * always called with pretty short arguments, so * such an optimization might not help). */ struct archive_string * archive_strncat(struct archive_string *as, const void *_p, size_t n) { size_t s; const char *p, *pp; p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } if ((as = archive_string_append(as, p, s)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_wstring * archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n) { size_t s; const wchar_t *pp; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } if ((as = archive_wstring_append(as, p, s)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_string * archive_strcat(struct archive_string *as, const void *p) { /* strcat is just strncat without an effective limit. * Assert that we'll never get called with a source * string over 16MB. * TODO: Review all uses of strcat in the source * and try to replace them with strncat(). */ return archive_strncat(as, p, 0x1000000); } struct archive_wstring * archive_wstrcat(struct archive_wstring *as, const wchar_t *p) { /* Ditto. */ return archive_wstrncat(as, p, 0x1000000); } struct archive_string * archive_strappend_char(struct archive_string *as, char c) { if ((as = archive_string_append(as, &c, 1)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_wstring * archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c) { if ((as = archive_wstring_append(as, &c, 1)) == NULL) __archive_errx(1, "Out of memory"); return (as); } /* * Get the "current character set" name to use with iconv. * On FreeBSD, the empty character set name "" chooses * the correct character encoding for the current locale, * so this isn't necessary. * But iconv on Mac OS 10.6 doesn't seem to handle this correctly; * on that system, we have to explicitly call nl_langinfo() * to get the right name. Not sure about other platforms. * * NOTE: GNU libiconv does not recognize the character-set name * which some platform nl_langinfo(CODESET) returns, so we should * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv. */ static const char * default_iconv_charset(const char *charset) { if (charset != NULL && charset[0] != '\0') return charset; #if HAVE_LOCALE_CHARSET && !defined(__APPLE__) /* locale_charset() is broken on Mac OS */ return locale_charset(); #elif HAVE_NL_LANGINFO return nl_langinfo(CODESET); #else return ""; #endif } #if defined(_WIN32) && !defined(__CYGWIN__) /* * Convert MBS to WCS. * Note: returns -1 if conversion fails. */ int archive_wstring_append_from_mbs(struct archive_wstring *dest, const char *p, size_t len) { return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL); } static int archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest, const char *s, size_t length, struct archive_string_conv *sc) { int count, ret = 0; UINT from_cp; if (sc != NULL) from_cp = sc->from_cp; else from_cp = get_current_codepage(); if (from_cp == CP_C_LOCALE) { /* * "C" locale special processing. */ wchar_t *ws; const unsigned char *mp; if (NULL == archive_wstring_ensure(dest, dest->length + length + 1)) return (-1); ws = dest->s + dest->length; mp = (const unsigned char *)s; count = 0; while (count < (int)length && *mp) { *ws++ = (wchar_t)*mp++; count++; } } else if (sc != NULL && (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) { /* * Normalize UTF-8 and UTF-16BE and convert it directly * to UTF-16 as wchar_t. */ struct archive_string u16; int saved_flag = sc->flag;/* save current flag. */ if (is_big_endian()) sc->flag |= SCONV_TO_UTF16BE; else sc->flag |= SCONV_TO_UTF16LE; if (sc->flag & SCONV_FROM_UTF16) { /* * UTF-16BE/LE NFD ===> UTF-16 NFC * UTF-16BE/LE NFC ===> UTF-16 NFD */ count = (int)utf16nbytes(s, length); } else { /* * UTF-8 NFD ===> UTF-16 NFC * UTF-8 NFC ===> UTF-16 NFD */ count = (int)mbsnbytes(s, length); } u16.s = (char *)dest->s; u16.length = dest->length << 1;; u16.buffer_length = dest->buffer_length; if (sc->flag & SCONV_NORMALIZATION_C) ret = archive_string_normalize_C(&u16, s, count, sc); else ret = archive_string_normalize_D(&u16, s, count, sc); dest->s = (wchar_t *)u16.s; dest->length = u16.length >> 1; dest->buffer_length = u16.buffer_length; sc->flag = saved_flag;/* restore the saved flag. */ return (ret); } else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) { count = (int)utf16nbytes(s, length); count >>= 1; /* to be WCS length */ /* Allocate memory for WCS. */ if (NULL == archive_wstring_ensure(dest, dest->length + count + 1)) return (-1); wmemcpy(dest->s + dest->length, (const wchar_t *)s, count); if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) { uint16_t *u16 = (uint16_t *)(dest->s + dest->length); int b; for (b = 0; b < count; b++) { uint16_t val = archive_le16dec(u16+b); archive_be16enc(u16+b, val); } } else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) { uint16_t *u16 = (uint16_t *)(dest->s + dest->length); int b; for (b = 0; b < count; b++) { uint16_t val = archive_be16dec(u16+b); archive_le16enc(u16+b, val); } } } else { DWORD mbflag; size_t buffsize; if (sc == NULL) mbflag = 0; else if (sc->flag & SCONV_FROM_CHARSET) { /* Do not trust the length which comes from * an archive file. */ length = mbsnbytes(s, length); mbflag = 0; } else mbflag = MB_PRECOMPOSED; buffsize = dest->length + length + 1; do { /* Allocate memory for WCS. */ if (NULL == archive_wstring_ensure(dest, buffsize)) return (-1); /* Convert MBS to WCS. */ count = MultiByteToWideChar(from_cp, mbflag, s, (int)length, dest->s + dest->length, (int)(dest->buffer_length >> 1) -1); if (count == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { /* Expand the WCS buffer. */ buffsize = dest->buffer_length << 1; continue; } if (count == 0 && length != 0) ret = -1; break; } while (1); } dest->length += count; dest->s[dest->length] = L'\0'; return (ret); } #else /* * Convert MBS to WCS. * Note: returns -1 if conversion fails. */ int archive_wstring_append_from_mbs(struct archive_wstring *dest, const char *p, size_t len) { size_t r; int ret_val = 0; /* * No single byte will be more than one wide character, * so this length estimate will always be big enough. */ // size_t wcs_length = len; size_t mbs_length = len; const char *mbs = p; wchar_t *wcs; #if HAVE_MBRTOWC mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #endif /* * As we decided to have wcs_length == mbs_length == len * we can use len here instead of wcs_length */ if (NULL == archive_wstring_ensure(dest, dest->length + len + 1)) return (-1); wcs = dest->s + dest->length; /* * We cannot use mbsrtowcs/mbstowcs here because those may convert * extra MBS when strlen(p) > len and one wide character consists of * multi bytes. */ while (*mbs && mbs_length > 0) { /* * The buffer we allocated is always big enough. * Keep this code path in a comment if we decide to choose * smaller wcs_length in the future */ /* if (wcs_length == 0) { dest->length = wcs - dest->s; dest->s[dest->length] = L'\0'; wcs_length = mbs_length; if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1)) return (-1); wcs = dest->s + dest->length; } */ #if HAVE_MBRTOWC r = mbrtowc(wcs, mbs, mbs_length, &shift_state); #else r = mbtowc(wcs, mbs, mbs_length); #endif if (r == (size_t)-1 || r == (size_t)-2) { ret_val = -1; break; } if (r == 0 || r > mbs_length) break; wcs++; // wcs_length--; mbs += r; mbs_length -= r; } dest->length = wcs - dest->s; dest->s[dest->length] = L'\0'; return (ret_val); } #endif #if defined(_WIN32) && !defined(__CYGWIN__) /* * WCS ==> MBS. * Note: returns -1 if conversion fails. * * Win32 builds use WideCharToMultiByte from the Windows API. * (Maybe Cygwin should too? WideCharToMultiByte will know a * lot more about local character encodings than the wcrtomb() * wrapper is going to know.) */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { return archive_string_append_from_wcs_in_codepage(as, w, len, NULL); } static int archive_string_append_from_wcs_in_codepage(struct archive_string *as, const wchar_t *ws, size_t len, struct archive_string_conv *sc) { BOOL defchar_used, *dp; int count, ret = 0; UINT to_cp; int wslen = (int)len; if (sc != NULL) to_cp = sc->to_cp; else to_cp = get_current_codepage(); if (to_cp == CP_C_LOCALE) { /* * "C" locale special processing. */ const wchar_t *wp = ws; char *p; if (NULL == archive_string_ensure(as, as->length + wslen +1)) return (-1); p = as->s + as->length; count = 0; defchar_used = 0; while (count < wslen && *wp) { if (*wp > 255) { *p++ = '?'; wp++; defchar_used = 1; } else *p++ = (char)*wp++; count++; } } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) { uint16_t *u16; if (NULL == archive_string_ensure(as, as->length + len * 2 + 2)) return (-1); u16 = (uint16_t *)(as->s + as->length); count = 0; defchar_used = 0; if (sc->flag & SCONV_TO_UTF16BE) { while (count < (int)len && *ws) { archive_be16enc(u16+count, *ws); ws++; count++; } } else { while (count < (int)len && *ws) { archive_le16enc(u16+count, *ws); ws++; count++; } } count <<= 1; /* to be byte size */ } else { /* Make sure the MBS buffer has plenty to set. */ if (NULL == archive_string_ensure(as, as->length + len * 2 + 1)) return (-1); do { defchar_used = 0; if (to_cp == CP_UTF8 || sc == NULL) dp = NULL; else dp = &defchar_used; count = WideCharToMultiByte(to_cp, 0, ws, wslen, as->s + as->length, (int)as->buffer_length-1, NULL, dp); if (count == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { /* Expand the MBS buffer and retry. */ if (NULL == archive_string_ensure(as, as->buffer_length + len)) return (-1); continue; } if (count == 0) ret = -1; break; } while (1); } as->length += count; as->s[as->length] = '\0'; return (defchar_used?-1:ret); } #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB) /* * Translates a wide character string into current locale character set * and appends to the archive_string. Note: returns -1 if conversion * fails. */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { /* We cannot use the standard wcstombs() here because it * cannot tell us how big the output buffer should be. So * I've built a loop around wcrtomb() or wctomb() that * converts a character at a time and resizes the string as * needed. We prefer wcrtomb() when it's available because * it's thread-safe. */ int n, ret_val = 0; char *p; char *end; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while (*w != L'\0' && len > 0) { if (p >= end) { as->length = p - as->s; as->s[as->length] = '\0'; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + len * 2 + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } #if HAVE_WCRTOMB n = wcrtomb(p, *w++, &shift_state); #else n = wctomb(p, *w++); #endif if (n == -1) { if (errno == EILSEQ) { /* Skip an illegal wide char. */ *p++ = '?'; ret_val = -1; } else { ret_val = -1; break; } } else p += n; len--; } as->length = p - as->s; as->s[as->length] = '\0'; return (ret_val); } #else /* HAVE_WCTOMB || HAVE_WCRTOMB */ /* * TODO: Test if __STDC_ISO_10646__ is defined. * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion * one character at a time. If a non-Windows platform doesn't have * either of these, fall back to the built-in UTF8 conversion. */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { (void)as;/* UNUSED */ (void)w;/* UNUSED */ (void)len;/* UNUSED */ errno = ENOSYS; return (-1); } #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */ /* * Find a string conversion object by a pair of 'from' charset name * and 'to' charset name from an archive object. * Return NULL if not found. */ static struct archive_string_conv * find_sconv_object(struct archive *a, const char *fc, const char *tc) { struct archive_string_conv *sc; if (a == NULL) return (NULL); for (sc = a->sconv; sc != NULL; sc = sc->next) { if (strcmp(sc->from_charset, fc) == 0 && strcmp(sc->to_charset, tc) == 0) break; } return (sc); } /* * Register a string object to an archive object. */ static void add_sconv_object(struct archive *a, struct archive_string_conv *sc) { struct archive_string_conv **psc; /* Add a new sconv to sconv list. */ psc = &(a->sconv); while (*psc != NULL) psc = &((*psc)->next); *psc = sc; } static void add_converter(struct archive_string_conv *sc, int (*converter) (struct archive_string *, const void *, size_t, struct archive_string_conv *)) { if (sc == NULL || sc->nconverter >= 2) __archive_errx(1, "Programming error"); sc->converter[sc->nconverter++] = converter; } static void setup_converter(struct archive_string_conv *sc) { /* Reset. */ sc->nconverter = 0; /* * Perform special sequence for the incorrect UTF-8 filenames * made by libarchive2.x. */ if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) { add_converter(sc, strncat_from_utf8_libarchive2); return; } /* * Convert a string to UTF-16BE/LE. */ if (sc->flag & SCONV_TO_UTF16) { /* * If the current locale is UTF-8, we can translate * a UTF-8 string into a UTF-16BE string. */ if (sc->flag & SCONV_FROM_UTF8) { add_converter(sc, archive_string_append_unicode); return; } #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->flag & SCONV_WIN_CP) { if (sc->flag & SCONV_TO_UTF16BE) add_converter(sc, win_strncat_to_utf16be); else add_converter(sc, win_strncat_to_utf16le); return; } #endif #if defined(HAVE_ICONV) if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); return; } #endif if (sc->flag & SCONV_BEST_EFFORT) { if (sc->flag & SCONV_TO_UTF16BE) add_converter(sc, best_effort_strncat_to_utf16be); else add_converter(sc, best_effort_strncat_to_utf16le); } else /* Make sure we have no converter. */ sc->nconverter = 0; return; } /* * Convert a string from UTF-16BE/LE. */ if (sc->flag & SCONV_FROM_UTF16) { /* * At least we should normalize a UTF-16BE string. */ if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc,archive_string_normalize_D); else if (sc->flag & SCONV_NORMALIZATION_C) add_converter(sc, archive_string_normalize_C); if (sc->flag & SCONV_TO_UTF8) { /* * If the current locale is UTF-8, we can translate * a UTF-16BE/LE string into a UTF-8 string directly. */ if (!(sc->flag & (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) add_converter(sc, archive_string_append_unicode); return; } #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->flag & SCONV_WIN_CP) { if (sc->flag & SCONV_FROM_UTF16BE) add_converter(sc, win_strncat_from_utf16be); else add_converter(sc, win_strncat_from_utf16le); return; } #endif #if defined(HAVE_ICONV) if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); return; } #endif if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) add_converter(sc, best_effort_strncat_from_utf16be); else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) add_converter(sc, best_effort_strncat_from_utf16le); else /* Make sure we have no converter. */ sc->nconverter = 0; return; } if (sc->flag & SCONV_FROM_UTF8) { /* * At least we should normalize a UTF-8 string. */ if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc,archive_string_normalize_D); else if (sc->flag & SCONV_NORMALIZATION_C) add_converter(sc, archive_string_normalize_C); /* * Copy UTF-8 string with a check of CESU-8. * Apparently, iconv does not check surrogate pairs in UTF-8 * when both from-charset and to-charset are UTF-8, and then * we use our UTF-8 copy code. */ if (sc->flag & SCONV_TO_UTF8) { /* * If the current locale is UTF-8, we can translate * a UTF-16BE string into a UTF-8 string directly. */ if (!(sc->flag & (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) add_converter(sc, strncat_from_utf8_to_utf8); return; } } #if defined(_WIN32) && !defined(__CYGWIN__) /* * On Windows we can use Windows API for a string conversion. */ if (sc->flag & SCONV_WIN_CP) { add_converter(sc, strncat_in_codepage); return; } #endif #if HAVE_ICONV if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); /* * iconv generally does not support UTF-8-MAC and so * we have to the output of iconv from NFC to NFD if * need. */ if ((sc->flag & SCONV_FROM_CHARSET) && (sc->flag & SCONV_TO_UTF8)) { if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc, archive_string_normalize_D); } return; } #endif /* * Try conversion in the best effort or no conversion. */ if ((sc->flag & SCONV_BEST_EFFORT) || sc->same) add_converter(sc, best_effort_strncat_in_locale); else /* Make sure we have no converter. */ sc->nconverter = 0; } /* * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE * and CP932 which are referenced in create_sconv_object(). */ static const char * canonical_charset_name(const char *charset) { char cs[16]; char *p; const char *s; if (charset == NULL || charset[0] == '\0' || strlen(charset) > 15) return (charset); /* Copy name to uppercase. */ p = cs; s = charset; while (*s) { char c = *s++; if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *p++ = c; } *p++ = '\0'; if (strcmp(cs, "UTF-8") == 0 || strcmp(cs, "UTF8") == 0) return ("UTF-8"); if (strcmp(cs, "UTF-16BE") == 0 || strcmp(cs, "UTF16BE") == 0) return ("UTF-16BE"); if (strcmp(cs, "UTF-16LE") == 0 || strcmp(cs, "UTF16LE") == 0) return ("UTF-16LE"); if (strcmp(cs, "CP932") == 0) return ("CP932"); return (charset); } /* * Create a string conversion object. */ static struct archive_string_conv * create_sconv_object(const char *fc, const char *tc, unsigned current_codepage, int flag) { struct archive_string_conv *sc; sc = calloc(1, sizeof(*sc)); if (sc == NULL) return (NULL); sc->next = NULL; sc->from_charset = strdup(fc); if (sc->from_charset == NULL) { free(sc); return (NULL); } sc->to_charset = strdup(tc); if (sc->to_charset == NULL) { free(sc->from_charset); free(sc); return (NULL); } archive_string_init(&sc->utftmp); if (flag & SCONV_TO_CHARSET) { /* * Convert characters from the current locale charset to * a specified charset. */ sc->from_cp = current_codepage; sc->to_cp = make_codepage_from_charset(tc); #if defined(_WIN32) && !defined(__CYGWIN__) if (IsValidCodePage(sc->to_cp)) flag |= SCONV_WIN_CP; #endif } else if (flag & SCONV_FROM_CHARSET) { /* * Convert characters from a specified charset to * the current locale charset. */ sc->to_cp = current_codepage; sc->from_cp = make_codepage_from_charset(fc); #if defined(_WIN32) && !defined(__CYGWIN__) if (IsValidCodePage(sc->from_cp)) flag |= SCONV_WIN_CP; #endif } /* * Check if "from charset" and "to charset" are the same. */ if (strcmp(fc, tc) == 0 || (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp)) sc->same = 1; else sc->same = 0; /* * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE. */ if (strcmp(tc, "UTF-8") == 0) flag |= SCONV_TO_UTF8; else if (strcmp(tc, "UTF-16BE") == 0) flag |= SCONV_TO_UTF16BE; else if (strcmp(tc, "UTF-16LE") == 0) flag |= SCONV_TO_UTF16LE; if (strcmp(fc, "UTF-8") == 0) flag |= SCONV_FROM_UTF8; else if (strcmp(fc, "UTF-16BE") == 0) flag |= SCONV_FROM_UTF16BE; else if (strcmp(fc, "UTF-16LE") == 0) flag |= SCONV_FROM_UTF16LE; #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->to_cp == CP_UTF8) flag |= SCONV_TO_UTF8; else if (sc->to_cp == CP_UTF16BE) flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP; else if (sc->to_cp == CP_UTF16LE) flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP; if (sc->from_cp == CP_UTF8) flag |= SCONV_FROM_UTF8; else if (sc->from_cp == CP_UTF16BE) flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP; else if (sc->from_cp == CP_UTF16LE) flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP; #endif /* * Set a flag for Unicode NFD. Usually iconv cannot correctly * handle it. So we have to translate NFD characters to NFC ones * ourselves before iconv handles. Another reason is to prevent * that the same sight of two filenames, one is NFC and other * is NFD, would be in its directory. * On Mac OS X, although its filesystem layer automatically * convert filenames to NFD, it would be useful for filename * comparing to find out the same filenames that we normalize * that to be NFD ourselves. */ if ((flag & SCONV_FROM_CHARSET) && (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) { #if defined(__APPLE__) if (flag & SCONV_TO_UTF8) flag |= SCONV_NORMALIZATION_D; else #endif flag |= SCONV_NORMALIZATION_C; } #if defined(__APPLE__) /* * In case writing an archive file, make sure that a filename * going to be passed to iconv is a Unicode NFC string since * a filename in HFS Plus filesystem is a Unicode NFD one and * iconv cannot handle it with "UTF-8" charset. It is simpler * than a use of "UTF-8-MAC" charset. */ if ((flag & SCONV_TO_CHARSET) && (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) flag |= SCONV_NORMALIZATION_C; /* * In case reading an archive file. make sure that a filename * will be passed to users is a Unicode NFD string in order to * correctly compare the filename with other one which comes * from HFS Plus filesystem. */ if ((flag & SCONV_FROM_CHARSET) && !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && (flag & SCONV_TO_UTF8)) flag |= SCONV_NORMALIZATION_D; #endif #if defined(HAVE_ICONV) sc->cd_w = (iconv_t)-1; /* * Create an iconv object. */ if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) && (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) || (flag & SCONV_WIN_CP)) { /* This case we won't use iconv. */ sc->cd = (iconv_t)-1; } else { sc->cd = iconv_open(tc, fc); if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) { /* * Unfortunately, all of iconv implements do support * "CP932" character-set, so we should use "SJIS" * instead if iconv_open failed. */ if (strcmp(tc, "CP932") == 0) sc->cd = iconv_open("SJIS", fc); else if (strcmp(fc, "CP932") == 0) sc->cd = iconv_open(tc, "SJIS"); } #if defined(_WIN32) && !defined(__CYGWIN__) /* * archive_mstring on Windows directly convert multi-bytes * into archive_wstring in order not to depend on locale * so that you can do a I18N programming. This will be * used only in archive_mstring_copy_mbs_len_l so far. */ if (flag & SCONV_FROM_CHARSET) { sc->cd_w = iconv_open("UTF-8", fc); if (sc->cd_w == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) { if (strcmp(fc, "CP932") == 0) sc->cd_w = iconv_open("UTF-8", "SJIS"); } } #endif /* _WIN32 && !__CYGWIN__ */ } #endif /* HAVE_ICONV */ sc->flag = flag; /* * Set up converters. */ setup_converter(sc); return (sc); } /* * Free a string conversion object. */ static void free_sconv_object(struct archive_string_conv *sc) { free(sc->from_charset); free(sc->to_charset); archive_string_free(&sc->utftmp); #if HAVE_ICONV if (sc->cd != (iconv_t)-1) iconv_close(sc->cd); if (sc->cd_w != (iconv_t)-1) iconv_close(sc->cd_w); #endif free(sc); } #if defined(_WIN32) && !defined(__CYGWIN__) static unsigned my_atoi(const char *p) { unsigned cp; cp = 0; while (*p) { if (*p >= '0' && *p <= '9') cp = cp * 10 + (*p - '0'); else return (-1); p++; } return (cp); } /* * Translate Charset name (as used by iconv) into CodePage (as used by Windows) * Return -1 if failed. * * Note: This translation code may be insufficient. */ static struct charset { const char *name; unsigned cp; } charsets[] = { /* MUST BE SORTED! */ {"ASCII", 1252}, {"ASMO-708", 708}, {"BIG5", 950}, {"CHINESE", 936}, {"CP367", 1252}, {"CP819", 1252}, {"CP1025", 21025}, {"DOS-720", 720}, {"DOS-862", 862}, {"EUC-CN", 51936}, {"EUC-JP", 51932}, {"EUC-KR", 949}, {"EUCCN", 51936}, {"EUCJP", 51932}, {"EUCKR", 949}, {"GB18030", 54936}, {"GB2312", 936}, {"HEBREW", 1255}, {"HZ-GB-2312", 52936}, {"IBM273", 20273}, {"IBM277", 20277}, {"IBM278", 20278}, {"IBM280", 20280}, {"IBM284", 20284}, {"IBM285", 20285}, {"IBM290", 20290}, {"IBM297", 20297}, {"IBM367", 1252}, {"IBM420", 20420}, {"IBM423", 20423}, {"IBM424", 20424}, {"IBM819", 1252}, {"IBM871", 20871}, {"IBM880", 20880}, {"IBM905", 20905}, {"IBM924", 20924}, {"ISO-8859-1", 28591}, {"ISO-8859-13", 28603}, {"ISO-8859-15", 28605}, {"ISO-8859-2", 28592}, {"ISO-8859-3", 28593}, {"ISO-8859-4", 28594}, {"ISO-8859-5", 28595}, {"ISO-8859-6", 28596}, {"ISO-8859-7", 28597}, {"ISO-8859-8", 28598}, {"ISO-8859-9", 28599}, {"ISO8859-1", 28591}, {"ISO8859-13", 28603}, {"ISO8859-15", 28605}, {"ISO8859-2", 28592}, {"ISO8859-3", 28593}, {"ISO8859-4", 28594}, {"ISO8859-5", 28595}, {"ISO8859-6", 28596}, {"ISO8859-7", 28597}, {"ISO8859-8", 28598}, {"ISO8859-9", 28599}, {"JOHAB", 1361}, {"KOI8-R", 20866}, {"KOI8-U", 21866}, {"KS_C_5601-1987", 949}, {"LATIN1", 1252}, {"LATIN2", 28592}, {"MACINTOSH", 10000}, {"SHIFT-JIS", 932}, {"SHIFT_JIS", 932}, {"SJIS", 932}, {"US", 1252}, {"US-ASCII", 1252}, {"UTF-16", 1200}, {"UTF-16BE", 1201}, {"UTF-16LE", 1200}, {"UTF-8", CP_UTF8}, {"X-EUROPA", 29001}, {"X-MAC-ARABIC", 10004}, {"X-MAC-CE", 10029}, {"X-MAC-CHINESEIMP", 10008}, {"X-MAC-CHINESETRAD", 10002}, {"X-MAC-CROATIAN", 10082}, {"X-MAC-CYRILLIC", 10007}, {"X-MAC-GREEK", 10006}, {"X-MAC-HEBREW", 10005}, {"X-MAC-ICELANDIC", 10079}, {"X-MAC-JAPANESE", 10001}, {"X-MAC-KOREAN", 10003}, {"X-MAC-ROMANIAN", 10010}, {"X-MAC-THAI", 10021}, {"X-MAC-TURKISH", 10081}, {"X-MAC-UKRAINIAN", 10017}, }; static unsigned make_codepage_from_charset(const char *charset) { char cs[16]; char *p; unsigned cp; int a, b; if (charset == NULL || strlen(charset) > 15) return -1; /* Copy name to uppercase. */ p = cs; while (*charset) { char c = *charset++; if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *p++ = c; } *p++ = '\0'; cp = -1; /* Look it up in the table first, so that we can easily * override CP367, which we map to 1252 instead of 367. */ a = 0; b = sizeof(charsets)/sizeof(charsets[0]); while (b > a) { int c = (b + a) / 2; int r = strcmp(charsets[c].name, cs); if (r < 0) a = c + 1; else if (r > 0) b = c; else return charsets[c].cp; } /* If it's not in the table, try to parse it. */ switch (*cs) { case 'C': if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') { cp = my_atoi(cs + 2); } else if (strcmp(cs, "CP_ACP") == 0) cp = get_current_codepage(); else if (strcmp(cs, "CP_OEMCP") == 0) cp = get_current_oemcp(); break; case 'I': if (cs[1] == 'B' && cs[2] == 'M' && cs[3] >= '0' && cs[3] <= '9') { cp = my_atoi(cs + 3); } break; case 'W': if (strncmp(cs, "WINDOWS-", 8) == 0) { cp = my_atoi(cs + 8); if (cp != 874 && (cp < 1250 || cp > 1258)) cp = -1;/* This may invalid code. */ } break; } return (cp); } /* * Return ANSI Code Page of current locale set by setlocale(). */ static unsigned get_current_codepage(void) { char *locale, *p; unsigned cp; locale = setlocale(LC_CTYPE, NULL); if (locale == NULL) return (GetACP()); if (locale[0] == 'C' && locale[1] == '\0') return (CP_C_LOCALE); p = strrchr(locale, '.'); if (p == NULL) return (GetACP()); if (strcmp(p+1, "utf8") == 0) return CP_UTF8; cp = my_atoi(p+1); if ((int)cp <= 0) return (GetACP()); return (cp); } /* * Translation table between Locale Name and ACP/OEMCP. */ static struct { unsigned acp; unsigned ocp; const char *locale; } acp_ocp_map[] = { { 950, 950, "Chinese_Taiwan" }, { 936, 936, "Chinese_People's Republic of China" }, { 950, 950, "Chinese_Taiwan" }, { 1250, 852, "Czech_Czech Republic" }, { 1252, 850, "Danish_Denmark" }, { 1252, 850, "Dutch_Netherlands" }, { 1252, 850, "Dutch_Belgium" }, { 1252, 437, "English_United States" }, { 1252, 850, "English_Australia" }, { 1252, 850, "English_Canada" }, { 1252, 850, "English_New Zealand" }, { 1252, 850, "English_United Kingdom" }, { 1252, 437, "English_United States" }, { 1252, 850, "Finnish_Finland" }, { 1252, 850, "French_France" }, { 1252, 850, "French_Belgium" }, { 1252, 850, "French_Canada" }, { 1252, 850, "French_Switzerland" }, { 1252, 850, "German_Germany" }, { 1252, 850, "German_Austria" }, { 1252, 850, "German_Switzerland" }, { 1253, 737, "Greek_Greece" }, { 1250, 852, "Hungarian_Hungary" }, { 1252, 850, "Icelandic_Iceland" }, { 1252, 850, "Italian_Italy" }, { 1252, 850, "Italian_Switzerland" }, { 932, 932, "Japanese_Japan" }, { 949, 949, "Korean_Korea" }, { 1252, 850, "Norwegian (BokmOl)_Norway" }, { 1252, 850, "Norwegian (BokmOl)_Norway" }, { 1252, 850, "Norwegian-Nynorsk_Norway" }, { 1250, 852, "Polish_Poland" }, { 1252, 850, "Portuguese_Portugal" }, { 1252, 850, "Portuguese_Brazil" }, { 1251, 866, "Russian_Russia" }, { 1250, 852, "Slovak_Slovakia" }, { 1252, 850, "Spanish_Spain" }, { 1252, 850, "Spanish_Mexico" }, { 1252, 850, "Spanish_Spain" }, { 1252, 850, "Swedish_Sweden" }, { 1254, 857, "Turkish_Turkey" }, { 0, 0, NULL} }; /* * Return OEM Code Page of current locale set by setlocale(). */ static unsigned get_current_oemcp(void) { int i; char *locale, *p; size_t len; locale = setlocale(LC_CTYPE, NULL); if (locale == NULL) return (GetOEMCP()); if (locale[0] == 'C' && locale[1] == '\0') return (CP_C_LOCALE); p = strrchr(locale, '.'); if (p == NULL) return (GetOEMCP()); len = p - locale; for (i = 0; acp_ocp_map[i].acp; i++) { if (strncmp(acp_ocp_map[i].locale, locale, len) == 0) return (acp_ocp_map[i].ocp); } return (GetOEMCP()); } #else /* * POSIX platform does not use CodePage. */ static unsigned get_current_codepage(void) { return (-1);/* Unknown */ } static unsigned make_codepage_from_charset(const char *charset) { (void)charset; /* UNUSED */ return (-1);/* Unknown */ } static unsigned get_current_oemcp(void) { return (-1);/* Unknown */ } #endif /* defined(_WIN32) && !defined(__CYGWIN__) */ /* * Return a string conversion object. */ static struct archive_string_conv * get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag) { struct archive_string_conv *sc; unsigned current_codepage; /* Check if we have made the sconv object. */ sc = find_sconv_object(a, fc, tc); if (sc != NULL) return (sc); if (a == NULL) current_codepage = get_current_codepage(); else current_codepage = a->current_codepage; sc = create_sconv_object(canonical_charset_name(fc), canonical_charset_name(tc), current_codepage, flag); if (sc == NULL) { if (a != NULL) archive_set_error(a, ENOMEM, "Could not allocate memory for " "a string conversion object"); return (NULL); } /* * If there is no converter for current string conversion object, * we cannot handle this conversion. */ if (sc->nconverter == 0) { if (a != NULL) { #if HAVE_ICONV archive_set_error(a, ARCHIVE_ERRNO_MISC, "iconv_open failed : Cannot handle ``%s''", (flag & SCONV_TO_CHARSET)?tc:fc); #else archive_set_error(a, ARCHIVE_ERRNO_MISC, "A character-set conversion not fully supported " "on this platform"); #endif } /* Failed; free a sconv object. */ free_sconv_object(sc); return (NULL); } /* * Success! */ if (a != NULL) add_sconv_object(a, sc); return (sc); } static const char * get_current_charset(struct archive *a) { const char *cur_charset; if (a == NULL) cur_charset = default_iconv_charset(""); else { cur_charset = default_iconv_charset(a->current_code); if (a->current_code == NULL) { a->current_code = strdup(cur_charset); a->current_codepage = get_current_codepage(); a->current_oemcp = get_current_oemcp(); } } return (cur_charset); } /* * Make and Return a string conversion object. * Return NULL if the platform does not support the specified conversion * and best_effort is 0. * If best_effort is set, A string conversion object must be returned * unless memory allocation for the object fails, but the conversion * might fail when non-ASCII code is found. */ struct archive_string_conv * archive_string_conversion_to_charset(struct archive *a, const char *charset, int best_effort) { int flag = SCONV_TO_CHARSET; if (best_effort) flag |= SCONV_BEST_EFFORT; return (get_sconv_object(a, get_current_charset(a), charset, flag)); } struct archive_string_conv * archive_string_conversion_from_charset(struct archive *a, const char *charset, int best_effort) { int flag = SCONV_FROM_CHARSET; if (best_effort) flag |= SCONV_BEST_EFFORT; return (get_sconv_object(a, charset, get_current_charset(a), flag)); } /* * archive_string_default_conversion_*_archive() are provided for Windows * platform because other archiver application use CP_OEMCP for * MultiByteToWideChar() and WideCharToMultiByte() for the filenames * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP). * So we should make a string conversion between CP_ACP and CP_OEMCP * for compatibility. */ #if defined(_WIN32) && !defined(__CYGWIN__) struct archive_string_conv * archive_string_default_conversion_for_read(struct archive *a) { const char *cur_charset = get_current_charset(a); char oemcp[16]; /* NOTE: a check of cur_charset is unneeded but we need * that get_current_charset() has been surely called at * this time whatever C compiler optimized. */ if (cur_charset != NULL && (a->current_codepage == CP_C_LOCALE || a->current_codepage == a->current_oemcp)) return (NULL);/* no conversion. */ _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); /* Make sure a null termination must be set. */ oemcp[sizeof(oemcp)-1] = '\0'; return (get_sconv_object(a, oemcp, cur_charset, SCONV_FROM_CHARSET)); } struct archive_string_conv * archive_string_default_conversion_for_write(struct archive *a) { const char *cur_charset = get_current_charset(a); char oemcp[16]; /* NOTE: a check of cur_charset is unneeded but we need * that get_current_charset() has been surely called at * this time whatever C compiler optimized. */ if (cur_charset != NULL && (a->current_codepage == CP_C_LOCALE || a->current_codepage == a->current_oemcp)) return (NULL);/* no conversion. */ _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); /* Make sure a null termination must be set. */ oemcp[sizeof(oemcp)-1] = '\0'; return (get_sconv_object(a, cur_charset, oemcp, SCONV_TO_CHARSET)); } #else struct archive_string_conv * archive_string_default_conversion_for_read(struct archive *a) { (void)a; /* UNUSED */ return (NULL); } struct archive_string_conv * archive_string_default_conversion_for_write(struct archive *a) { (void)a; /* UNUSED */ return (NULL); } #endif /* * Dispose of all character conversion objects in the archive object. */ void archive_string_conversion_free(struct archive *a) { struct archive_string_conv *sc; struct archive_string_conv *sc_next; for (sc = a->sconv; sc != NULL; sc = sc_next) { sc_next = sc->next; free_sconv_object(sc); } a->sconv = NULL; free(a->current_code); a->current_code = NULL; } /* * Return a conversion charset name. */ const char * archive_string_conversion_charset_name(struct archive_string_conv *sc) { if (sc->flag & SCONV_TO_CHARSET) return (sc->to_charset); else return (sc->from_charset); } /* * Change the behavior of a string conversion. */ void archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt) { switch (opt) { /* * A filename in UTF-8 was made with libarchive 2.x in a wrong * assumption that wchar_t was Unicode. * This option enables simulating the assumption in order to read * that filename correctly. */ case SCONV_SET_OPT_UTF8_LIBARCHIVE2X: #if (defined(_WIN32) && !defined(__CYGWIN__)) \ || defined(__STDC_ISO_10646__) || defined(__APPLE__) /* * Nothing to do for it since wchar_t on these platforms * is really Unicode. */ (void)sc; /* UNUSED */ #else if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) { sc->flag |= SCONV_UTF8_LIBARCHIVE_2; /* Set up string converters. */ setup_converter(sc); } #endif break; case SCONV_SET_OPT_NORMALIZATION_C: if ((sc->flag & SCONV_NORMALIZATION_C) == 0) { sc->flag |= SCONV_NORMALIZATION_C; sc->flag &= ~SCONV_NORMALIZATION_D; /* Set up string converters. */ setup_converter(sc); } break; case SCONV_SET_OPT_NORMALIZATION_D: #if defined(HAVE_ICONV) /* * If iconv will take the string, do not change the * setting of the normalization. */ if (!(sc->flag & SCONV_WIN_CP) && (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) break; #endif if ((sc->flag & SCONV_NORMALIZATION_D) == 0) { sc->flag |= SCONV_NORMALIZATION_D; sc->flag &= ~SCONV_NORMALIZATION_C; /* Set up string converters. */ setup_converter(sc); } break; default: break; } } /* * * Copy one archive_string to another in locale conversion. * * archive_strncat_l(); * archive_strncpy_l(); * */ static size_t mbsnbytes(const void *_p, size_t n) { size_t s; const char *p, *pp; if (_p == NULL) return (0); p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } return (s); } static size_t utf16nbytes(const void *_p, size_t n) { size_t s; const char *p, *pp; if (_p == NULL) return (0); p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; n >>= 1; while (s < n && (pp[0] || pp[1])) { pp += 2; s++; } return (s<<1); } int archive_strncpy_l(struct archive_string *as, const void *_p, size_t n, struct archive_string_conv *sc) { as->length = 0; return (archive_strncat_l(as, _p, n, sc)); } int archive_strncat_l(struct archive_string *as, const void *_p, size_t n, struct archive_string_conv *sc) { const void *s; size_t length = 0; int i, r = 0, r2; if (_p != NULL && n > 0) { if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) length = utf16nbytes(_p, n); else length = mbsnbytes(_p, n); } /* We must allocate memory even if there is no data for conversion * or copy. This simulates archive_string_append behavior. */ if (length == 0) { int tn = 1; if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) tn = 2; if (archive_string_ensure(as, as->length + tn) == NULL) return (-1); as->s[as->length] = 0; if (tn == 2) as->s[as->length+1] = 0; return (0); } /* * If sc is NULL, we just make a copy. */ if (sc == NULL) { if (archive_string_append(as, _p, length) == NULL) return (-1);/* No memory */ return (0); } s = _p; i = 0; if (sc->nconverter > 1) { sc->utftmp.length = 0; r2 = sc->converter[0](&(sc->utftmp), s, length, sc); if (r2 != 0 && errno == ENOMEM) return (r2); if (r > r2) r = r2; s = sc->utftmp.s; length = sc->utftmp.length; ++i; } r2 = sc->converter[i](as, s, length, sc); if (r > r2) r = r2; return (r); } #if HAVE_ICONV /* * Return -1 if conversion fails. */ static int iconv_strncat_in_locale(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { ICONV_CONST char *itp; size_t remaining; iconv_t cd; char *outp; size_t avail, bs; int return_value = 0; /* success */ int to_size, from_size; if (sc->flag & SCONV_TO_UTF16) to_size = 2; else to_size = 1; if (sc->flag & SCONV_FROM_UTF16) from_size = 2; else from_size = 1; if (archive_string_ensure(as, as->length + length*2+to_size) == NULL) return (-1); cd = sc->cd; itp = (char *)(uintptr_t)_p; remaining = length; outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; while (remaining >= (size_t)from_size) { size_t result = iconv(cd, &itp, &remaining, &outp, &avail); if (result != (size_t)-1) break; /* Conversion completed. */ if (errno == EILSEQ || errno == EINVAL) { /* * If an output charset is UTF-8 or UTF-16BE/LE, * unknown character should be U+FFFD * (replacement character). */ if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) { size_t rbytes; if (sc->flag & SCONV_TO_UTF8) rbytes = sizeof(utf8_replacement_char); else rbytes = 2; if (avail < rbytes) { as->length = outp - as->s; bs = as->buffer_length + (remaining * to_size) + rbytes; if (NULL == archive_string_ensure(as, bs)) return (-1); outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; } if (sc->flag & SCONV_TO_UTF8) memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char)); else if (sc->flag & SCONV_TO_UTF16BE) archive_be16enc(outp, UNICODE_R_CHAR); else archive_le16enc(outp, UNICODE_R_CHAR); outp += rbytes; avail -= rbytes; } else { /* Skip the illegal input bytes. */ *outp++ = '?'; avail--; } itp += from_size; remaining -= from_size; return_value = -1; /* failure */ } else { /* E2BIG no output buffer, * Increase an output buffer. */ as->length = outp - as->s; bs = as->buffer_length + remaining * 2; if (NULL == archive_string_ensure(as, bs)) return (-1); outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; } } as->length = outp - as->s; as->s[as->length] = 0; if (to_size == 2) as->s[as->length+1] = 0; return (return_value); } #endif /* HAVE_ICONV */ #if defined(_WIN32) && !defined(__CYGWIN__) /* * Translate a string from a some CodePage to an another CodePage by * Windows APIs, and copy the result. Return -1 if conversion fails. */ static int strncat_in_codepage(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { const char *s = (const char *)_p; struct archive_wstring aws; size_t l; int r, saved_flag; archive_string_init(&aws); saved_flag = sc->flag; sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C); r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc); sc->flag = saved_flag; if (r != 0) { archive_wstring_free(&aws); if (errno != ENOMEM) archive_string_append(as, s, length); return (-1); } l = as->length; r = archive_string_append_from_wcs_in_codepage( as, aws.s, aws.length, sc); if (r != 0 && errno != ENOMEM && l == as->length) archive_string_append(as, s, length); archive_wstring_free(&aws); return (r); } /* * Test whether MBS ==> WCS is okay. */ static int invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) { const char *p = (const char *)_p; unsigned codepage; DWORD mbflag = MB_ERR_INVALID_CHARS; if (sc->flag & SCONV_FROM_CHARSET) codepage = sc->to_cp; else codepage = sc->from_cp; if (codepage == CP_C_LOCALE) return (0); if (codepage != CP_UTF8) mbflag |= MB_PRECOMPOSED; if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0) return (-1); /* Invalid */ return (0); /* Okay */ } #else /* * Test whether MBS ==> WCS is okay. */ static int invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) { const char *p = (const char *)_p; size_t r; #if HAVE_MBRTOWC mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ mbtowc(NULL, NULL, 0); #endif while (n) { wchar_t wc; #if HAVE_MBRTOWC r = mbrtowc(&wc, p, n, &shift_state); #else r = mbtowc(&wc, p, n); #endif if (r == (size_t)-1 || r == (size_t)-2) return (-1);/* Invalid. */ if (r == 0) break; p += r; n -= r; } (void)sc; /* UNUSED */ return (0); /* All Okey. */ } #endif /* defined(_WIN32) && !defined(__CYGWIN__) */ /* * Basically returns -1 because we cannot make a conversion of charset * without iconv but in some cases this would return 0. * Returns 0 if all copied characters are ASCII. * Returns 0 if both from-locale and to-locale are the same and those * can be WCS with no error. */ static int best_effort_strncat_in_locale(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { size_t remaining; const uint8_t *itp; int return_value = 0; /* success */ /* * If both from-locale and to-locale is the same, this makes a copy. * And then this checks all copied MBS can be WCS if so returns 0. */ if (sc->same) { if (archive_string_append(as, _p, length) == NULL) return (-1);/* No memory */ return (invalid_mbs(_p, length, sc)); } /* * If a character is ASCII, this just copies it. If not, this * assigns '?' character instead but in UTF-8 locale this assigns * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD, * a Replacement Character in Unicode. */ remaining = length; itp = (const uint8_t *)_p; while (*itp && remaining > 0) { if (*itp > 127) { // Non-ASCII: Substitute with suitable replacement if (sc->flag & SCONV_TO_UTF8) { if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) { __archive_errx(1, "Out of memory"); } } else { archive_strappend_char(as, '?'); } return_value = -1; } else { archive_strappend_char(as, *itp); } ++itp; } return (return_value); } /* * Unicode conversion functions. * - UTF-8 <===> UTF-8 in removing surrogate pairs. * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs. * - UTF-8 made by libarchive 2.x ===> UTF-8. * - UTF-16BE <===> UTF-8. * */ /* * Utility to convert a single UTF-8 sequence. * * Usually return used bytes, return used byte in negative value when * a unicode character is replaced with U+FFFD. * See also http://unicode.org/review/pr-121.html Public Review Issue #121 * Recommended Practice for Replacement Characters. */ static int _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) { static const char utf8_count[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */ 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */ 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */ }; int ch, i; int cnt; uint32_t wc; /* Sanity check. */ if (n == 0) return (0); /* * Decode 1-4 bytes depending on the value of the first byte. */ ch = (unsigned char)*s; if (ch == 0) return (0); /* Standard: return 0 for end-of-string. */ cnt = utf8_count[ch]; /* Invalid sequence or there are not plenty bytes. */ if ((int)n < cnt) { cnt = (int)n; for (i = 1; i < cnt; i++) { if ((s[i] & 0xc0) != 0x80) { cnt = i; break; } } goto invalid_sequence; } /* Make a Unicode code point from a single UTF-8 sequence. */ switch (cnt) { case 1: /* 1 byte sequence. */ *pwc = ch & 0x7f; return (cnt); case 2: /* 2 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f); return (cnt); case 3: /* 3 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } if ((s[2] & 0xc0) != 0x80) { cnt = 2; goto invalid_sequence; } wc = ((ch & 0x0f) << 12) | ((s[1] & 0x3f) << 6) | (s[2] & 0x3f); if (wc < 0x800) goto invalid_sequence;/* Overlong sequence. */ break; case 4: /* 4 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } if ((s[2] & 0xc0) != 0x80) { cnt = 2; goto invalid_sequence; } if ((s[3] & 0xc0) != 0x80) { cnt = 3; goto invalid_sequence; } wc = ((ch & 0x07) << 18) | ((s[1] & 0x3f) << 12) | ((s[2] & 0x3f) << 6) | (s[3] & 0x3f); if (wc < 0x10000) goto invalid_sequence;/* Overlong sequence. */ break; default: /* Others are all invalid sequence. */ if (ch == 0xc0 || ch == 0xc1) cnt = 2; else if (ch >= 0xf5 && ch <= 0xf7) cnt = 4; else if (ch >= 0xf8 && ch <= 0xfb) cnt = 5; else if (ch == 0xfc || ch == 0xfd) cnt = 6; else cnt = 1; if ((int)n < cnt) cnt = (int)n; for (i = 1; i < cnt; i++) { if ((s[i] & 0xc0) != 0x80) { cnt = i; break; } } goto invalid_sequence; } /* The code point larger than 0x10FFFF is not legal * Unicode values. */ if (wc > UNICODE_MAX) goto invalid_sequence; /* Correctly gets a Unicode, returns used bytes. */ *pwc = wc; return (cnt); invalid_sequence: *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ return (cnt * -1); } static int utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) { int cnt; cnt = _utf8_to_unicode(pwc, s, n); /* Any of Surrogate pair is not legal Unicode values. */ if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc)) return (-3); return (cnt); } static inline uint32_t combine_surrogate_pair(uint32_t uc, uint32_t uc2) { uc -= 0xD800; uc *= 0x400; uc += uc2 - 0xDC00; uc += 0x10000; return (uc); } /* * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in * removing surrogate pairs. * * CESU-8: The Compatibility Encoding Scheme for UTF-16. * * Usually return used bytes, return used byte in negative value when * a unicode character is replaced with U+FFFD. */ static int cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n) { uint32_t wc = 0; int cnt; cnt = _utf8_to_unicode(&wc, s, n); if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) { uint32_t wc2 = 0; if (n - 3 < 3) { /* Invalid byte sequence. */ goto invalid_sequence; } cnt = _utf8_to_unicode(&wc2, s+3, n-3); if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) { /* Invalid byte sequence. */ goto invalid_sequence; } wc = combine_surrogate_pair(wc, wc2); cnt = 6; } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) { /* Invalid byte sequence. */ goto invalid_sequence; } *pwc = wc; return (cnt); invalid_sequence: *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ if (cnt > 0) cnt *= -1; return (cnt); } /* * Convert a Unicode code point to a single UTF-8 sequence. * * NOTE:This function does not check if the Unicode is legal or not. * Please you definitely check it before calling this. */ static size_t unicode_to_utf8(char *p, size_t remaining, uint32_t uc) { char *_p = p; /* Invalid Unicode char maps to Replacement character */ if (uc > UNICODE_MAX) uc = UNICODE_R_CHAR; /* Translate code point to UTF8 */ if (uc <= 0x7f) { if (remaining == 0) return (0); *p++ = (char)uc; } else if (uc <= 0x7ff) { if (remaining < 2) return (0); *p++ = 0xc0 | ((uc >> 6) & 0x1f); *p++ = 0x80 | (uc & 0x3f); } else if (uc <= 0xffff) { if (remaining < 3) return (0); *p++ = 0xe0 | ((uc >> 12) & 0x0f); *p++ = 0x80 | ((uc >> 6) & 0x3f); *p++ = 0x80 | (uc & 0x3f); } else { if (remaining < 4) return (0); *p++ = 0xf0 | ((uc >> 18) & 0x07); *p++ = 0x80 | ((uc >> 12) & 0x3f); *p++ = 0x80 | ((uc >> 6) & 0x3f); *p++ = 0x80 | (uc & 0x3f); } return (p - _p); } static int utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n) { return (utf16_to_unicode(pwc, s, n, 1)); } static int utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n) { return (utf16_to_unicode(pwc, s, n, 0)); } static int utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be) { const char *utf16 = s; unsigned uc; if (n == 0) return (0); if (n == 1) { /* set the Replacement Character instead. */ *pwc = UNICODE_R_CHAR; return (-1); } if (be) uc = archive_be16dec(utf16); else uc = archive_le16dec(utf16); utf16 += 2; /* If this is a surrogate pair, assemble the full code point.*/ if (IS_HIGH_SURROGATE_LA(uc)) { unsigned uc2; if (n >= 4) { if (be) uc2 = archive_be16dec(utf16); else uc2 = archive_le16dec(utf16); } else uc2 = 0; if (IS_LOW_SURROGATE_LA(uc2)) { uc = combine_surrogate_pair(uc, uc2); utf16 += 2; } else { /* Undescribed code point should be U+FFFD * (replacement character). */ *pwc = UNICODE_R_CHAR; return (-2); } } /* * Surrogate pair values(0xd800 through 0xdfff) are only * used by UTF-16, so, after above calculation, the code * must not be surrogate values, and Unicode has no codes * larger than 0x10ffff. Thus, those are not legal Unicode * values. */ if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) { /* Undescribed code point should be U+FFFD * (replacement character). */ *pwc = UNICODE_R_CHAR; return (((int)(utf16 - s)) * -1); } *pwc = uc; return ((int)(utf16 - s)); } static size_t unicode_to_utf16be(char *p, size_t remaining, uint32_t uc) { char *utf16 = p; if (uc > 0xffff) { /* We have a code point that won't fit into a * wchar_t; convert it to a surrogate pair. */ if (remaining < 4) return (0); uc -= 0x10000; archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00); return (4); } else { if (remaining < 2) return (0); archive_be16enc(utf16, uc); return (2); } } static size_t unicode_to_utf16le(char *p, size_t remaining, uint32_t uc) { char *utf16 = p; if (uc > 0xffff) { /* We have a code point that won't fit into a * wchar_t; convert it to a surrogate pair. */ if (remaining < 4) return (0); uc -= 0x10000; archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00); return (4); } else { if (remaining < 2) return (0); archive_le16enc(utf16, uc); return (2); } } /* * Copy UTF-8 string in checking surrogate pair. * If any surrogate pair are found, it would be canonicalized. */ static int strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; char *p, *endp; int n, ret = 0; (void)sc; /* UNUSED */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; endp = as->s + as->buffer_length -1; do { uint32_t uc; const char *ss = s; size_t w; /* * Forward byte sequence until a conversion of that is needed. */ while ((n = utf8_to_unicode(&uc, s, len)) > 0) { s += n; len -= n; } if (ss < s) { if (p + (s - ss) > endp) { as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len + 1) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length -1; } memcpy(p, ss, s - ss); p += s - ss; } /* * If n is negative, current byte sequence needs a replacement. */ if (n < 0) { if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) { /* Current byte sequence may be CESU-8. */ n = cesu8_to_unicode(&uc, s, len); } if (n < 0) { ret = -1; n *= -1;/* Use a replaced unicode character. */ } /* Rebuild UTF-8 byte sequence. */ while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) { as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len + 1) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length -1; } p += w; s += n; len -= n; } } while (n > 0); as->length = p - as->s; as->s[as->length] = '\0'; return (ret); } static int archive_string_append_unicode(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; char *p, *endp; uint32_t uc; size_t w; int n, ret = 0, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; ts = 1; } else { /* * This case is going to be converted to another * character-set through iconv. */ if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; ts = 1; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; } else { parse = cesu8_to_unicode; tm = ts; } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { if (n < 0) { /* Use a replaced unicode character. */ n *= -1; ret = -1; } s += n; len -= n; while ((w = unparse(p, endp - p, uc)) == 0) { /* There is not enough output buffer so * we have to expand it. */ as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; } p += w; } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } /* * Following Constants for Hangul compositions this information comes from * Unicode Standard Annex #15 http://unicode.org/reports/tr15/ */ #define HC_SBASE 0xAC00 #define HC_LBASE 0x1100 #define HC_VBASE 0x1161 #define HC_TBASE 0x11A7 #define HC_LCOUNT 19 #define HC_VCOUNT 21 #define HC_TCOUNT 28 #define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT) #define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT) static uint32_t get_nfc(uint32_t uc, uint32_t uc2) { int t, b; t = 0; b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1; while (b >= t) { int m = (t + b) / 2; if (u_composition_table[m].cp1 < uc) t = m + 1; else if (u_composition_table[m].cp1 > uc) b = m - 1; else if (u_composition_table[m].cp2 < uc2) t = m + 1; else if (u_composition_table[m].cp2 > uc2) b = m - 1; else return (u_composition_table[m].nfc); } return (0); } #define FDC_MAX 10 /* The maximum number of Following Decomposable * Characters. */ /* * Update first code point. */ #define UPDATE_UC(new_uc) do { \ uc = new_uc; \ ucptr = NULL; \ } while (0) /* * Replace first code point with second code point. */ #define REPLACE_UC_WITH_UC2() do { \ uc = uc2; \ ucptr = uc2ptr; \ n = n2; \ } while (0) #define EXPAND_BUFFER() do { \ as->length = p - as->s; \ if (archive_string_ensure(as, \ as->buffer_length + len * tm + ts) == NULL)\ return (-1); \ p = as->s + as->length; \ endp = as->s + as->buffer_length - ts; \ } while (0) #define UNPARSE(p, endp, uc) do { \ while ((w = unparse(p, (endp) - (p), uc)) == 0) {\ EXPAND_BUFFER(); \ } \ p += w; \ } while (0) /* * Write first code point. * If the code point has not be changed from its original code, * this just copies it from its original buffer pointer. * If not, this converts it to UTF-8 byte sequence and copies it. */ #define WRITE_UC() do { \ if (ucptr) { \ if (p + n > endp) \ EXPAND_BUFFER(); \ switch (n) { \ case 4: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 3: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 2: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 1: \ *p++ = *ucptr; \ break; \ } \ ucptr = NULL; \ } else { \ UNPARSE(p, endp, uc); \ } \ } while (0) /* * Collect following decomposable code points. */ #define COLLECT_CPS(start) do { \ int _i; \ for (_i = start; _i < FDC_MAX ; _i++) { \ nx = parse(&ucx[_i], s, len); \ if (nx <= 0) \ break; \ cx = CCC(ucx[_i]); \ if (cl >= cx && cl != 228 && cx != 228)\ break; \ s += nx; \ len -= nx; \ cl = cx; \ ccx[_i] = cx; \ } \ if (_i >= FDC_MAX) { \ ret = -1; \ ucx_size = FDC_MAX; \ } else \ ucx_size = _i; \ } while (0) /* * Normalize UTF-8/UTF-16BE characters to Form C and copy the result. * * TODO: Convert composition exclusions, which are never converted * from NFC,NFD,NFKC and NFKD, to Form C. */ static int archive_string_normalize_C(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s = (const char *)_p; char *p, *endp; uint32_t uc, uc2; size_t w; int always_replace, n, n2, ret = 0, spair, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); always_replace = 1; ts = 1;/* text size. */ if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; if (sc->flag & SCONV_FROM_UTF16BE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; if (sc->flag & SCONV_FROM_UTF16LE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; if (sc->flag & SCONV_FROM_UTF8) always_replace = 0; } else { /* * This case is going to be converted to another * character-set through iconv. */ always_replace = 0; if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else { parse = cesu8_to_unicode; tm = ts; spair = 6;/* surrogate pair size in UTF-8. */ } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { const char *ucptr, *uc2ptr; if (n < 0) { /* Use a replaced unicode character. */ UNPARSE(p, endp, uc); s += n*-1; len -= n*-1; ret = -1; continue; } else if (n == spair || always_replace) /* uc is converted from a surrogate pair. * this should be treated as a changed code. */ ucptr = NULL; else ucptr = s; s += n; len -= n; /* Read second code point. */ while ((n2 = parse(&uc2, s, len)) > 0) { uint32_t ucx[FDC_MAX]; int ccx[FDC_MAX]; int cl, cx, i, nx, ucx_size; int LIndex,SIndex; uint32_t nfc; if (n2 == spair || always_replace) /* uc2 is converted from a surrogate pair. * this should be treated as a changed code. */ uc2ptr = NULL; else uc2ptr = s; s += n2; len -= n2; /* * If current second code point is out of decomposable * code points, finding compositions is unneeded. */ if (!IS_DECOMPOSABLE_BLOCK(uc2)) { WRITE_UC(); REPLACE_UC_WITH_UC2(); continue; } /* * Try to combine current code points. */ /* * We have to combine Hangul characters according to * http://uniicode.org/reports/tr15/#Hangul */ if (0 <= (LIndex = uc - HC_LBASE) && LIndex < HC_LCOUNT) { /* * Hangul Composition. * 1. Two current code points are L and V. */ int VIndex = uc2 - HC_VBASE; if (0 <= VIndex && VIndex < HC_VCOUNT) { /* Make syllable of form LV. */ UPDATE_UC(HC_SBASE + (LIndex * HC_VCOUNT + VIndex) * HC_TCOUNT); } else { WRITE_UC(); REPLACE_UC_WITH_UC2(); } continue; } else if (0 <= (SIndex = uc - HC_SBASE) && SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) { /* * Hangul Composition. * 2. Two current code points are LV and T. */ int TIndex = uc2 - HC_TBASE; if (0 < TIndex && TIndex < HC_TCOUNT) { /* Make syllable of form LVT. */ UPDATE_UC(uc + TIndex); } else { WRITE_UC(); REPLACE_UC_WITH_UC2(); } continue; } else if ((nfc = get_nfc(uc, uc2)) != 0) { /* A composition to current code points * is found. */ UPDATE_UC(nfc); continue; } else if ((cl = CCC(uc2)) == 0) { /* Clearly 'uc2' the second code point is not * a decomposable code. */ WRITE_UC(); REPLACE_UC_WITH_UC2(); continue; } /* * Collect following decomposable code points. */ cx = 0; ucx[0] = uc2; ccx[0] = cl; COLLECT_CPS(1); /* * Find a composed code in the collected code points. */ i = 1; while (i < ucx_size) { int j; if ((nfc = get_nfc(uc, ucx[i])) == 0) { i++; continue; } /* * nfc is composed of uc and ucx[i]. */ UPDATE_UC(nfc); /* * Remove ucx[i] by shifting * following code points. */ for (j = i; j+1 < ucx_size; j++) { ucx[j] = ucx[j+1]; ccx[j] = ccx[j+1]; } ucx_size --; /* * Collect following code points blocked * by ucx[i] the removed code point. */ if (ucx_size > 0 && i == ucx_size && nx > 0 && cx == cl) { cl = ccx[ucx_size-1]; COLLECT_CPS(ucx_size); } /* * Restart finding a composed code with * the updated uc from the top of the * collected code points. */ i = 0; } /* * Apparently the current code points are not * decomposed characters or already composed. */ WRITE_UC(); for (i = 0; i < ucx_size; i++) UNPARSE(p, endp, ucx[i]); /* * Flush out remaining canonical combining characters. */ if (nx > 0 && cx == cl && len > 0) { while ((nx = parse(&ucx[0], s, len)) > 0) { cx = CCC(ucx[0]); if (cl > cx) break; s += nx; len -= nx; cl = cx; UNPARSE(p, endp, ucx[0]); } } break; } if (n2 < 0) { WRITE_UC(); /* Use a replaced unicode character. */ UNPARSE(p, endp, uc2); s += n2*-1; len -= n2*-1; ret = -1; continue; } else if (n2 == 0) { WRITE_UC(); break; } } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } static int get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc) { int t, b; /* * These are not converted to NFD on Mac OS. */ if ((uc >= 0x2000 && uc <= 0x2FFF) || (uc >= 0xF900 && uc <= 0xFAFF) || (uc >= 0x2F800 && uc <= 0x2FAFF)) return (0); /* * Those code points are not converted to NFD on Mac OS. * I do not know the reason because it is undocumented. * NFC NFD * 1109A ==> 11099 110BA * 1109C ==> 1109B 110BA * 110AB ==> 110A5 110BA */ if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB) return (0); t = 0; b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1; while (b >= t) { int m = (t + b) / 2; if (u_decomposition_table[m].nfc < uc) t = m + 1; else if (u_decomposition_table[m].nfc > uc) b = m - 1; else { *cp1 = u_decomposition_table[m].cp1; *cp2 = u_decomposition_table[m].cp2; return (1); } } return (0); } #define REPLACE_UC_WITH(cp) do { \ uc = cp; \ ucptr = NULL; \ } while (0) /* * Normalize UTF-8 characters to Form D and copy the result. */ static int archive_string_normalize_D(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s = (const char *)_p; char *p, *endp; uint32_t uc, uc2; size_t w; int always_replace, n, n2, ret = 0, spair, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); always_replace = 1; ts = 1;/* text size. */ if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; if (sc->flag & SCONV_FROM_UTF16BE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; if (sc->flag & SCONV_FROM_UTF16LE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; if (sc->flag & SCONV_FROM_UTF8) always_replace = 0; } else { /* * This case is going to be converted to another * character-set through iconv. */ always_replace = 0; if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else { parse = cesu8_to_unicode; tm = ts; spair = 6;/* surrogate pair size in UTF-8. */ } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { const char *ucptr; uint32_t cp1, cp2; int SIndex; struct { uint32_t uc; int ccc; } fdc[FDC_MAX]; int fdi, fdj; int ccc; check_first_code: if (n < 0) { /* Use a replaced unicode character. */ UNPARSE(p, endp, uc); s += n*-1; len -= n*-1; ret = -1; continue; } else if (n == spair || always_replace) /* uc is converted from a surrogate pair. * this should be treated as a changed code. */ ucptr = NULL; else ucptr = s; s += n; len -= n; /* Hangul Decomposition. */ if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) { int L = HC_LBASE + SIndex / HC_NCOUNT; int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT; int T = HC_TBASE + SIndex % HC_TCOUNT; REPLACE_UC_WITH(L); WRITE_UC(); REPLACE_UC_WITH(V); WRITE_UC(); if (T != HC_TBASE) { REPLACE_UC_WITH(T); WRITE_UC(); } continue; } if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) { WRITE_UC(); continue; } fdi = 0; while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) { int k; for (k = fdi; k > 0; k--) fdc[k] = fdc[k-1]; fdc[0].ccc = CCC(cp2); fdc[0].uc = cp2; fdi++; REPLACE_UC_WITH(cp1); } /* Read following code points. */ while ((n2 = parse(&uc2, s, len)) > 0 && (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) { int j, k; s += n2; len -= n2; for (j = 0; j < fdi; j++) { if (fdc[j].ccc > ccc) break; } if (j < fdi) { for (k = fdi; k > j; k--) fdc[k] = fdc[k-1]; fdc[j].ccc = ccc; fdc[j].uc = uc2; } else { fdc[fdi].ccc = ccc; fdc[fdi].uc = uc2; } fdi++; } WRITE_UC(); for (fdj = 0; fdj < fdi; fdj++) { REPLACE_UC_WITH(fdc[fdj].uc); WRITE_UC(); } if (n2 == 0) break; REPLACE_UC_WITH(uc2); n = n2; goto check_first_code; } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } /* * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption * that WCS is Unicode. It is true for several platforms but some are false. * And then people who did not use UTF-8 locale on the non Unicode WCS * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those * now cannot get right filename from libarchive 3.x and later since we * fixed the wrong assumption and it is incompatible to older its versions. * So we provide special option, "compat-2x.x", for resolving it. * That option enable the string conversion of libarchive 2.x. * * Translates the wrong UTF-8 string made by libarchive 2.x into current * locale character set and appends to the archive_string. * Note: returns -1 if conversion fails. */ static int strncat_from_utf8_libarchive2(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; int n; char *p; char *end; uint32_t unicode; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif (void)sc; /* UNUSED */ /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) { wchar_t wc; if (p >= end) { as->length = p - as->s; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + len * 2 + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } /* * As libarchive 2.x, translates the UTF-8 characters into * wide-characters in the assumption that WCS is Unicode. */ if (n < 0) { n *= -1; wc = L'?'; } else wc = (wchar_t)unicode; s += n; len -= n; /* * Translates the wide-character into the current locale MBS. */ #if HAVE_WCRTOMB n = (int)wcrtomb(p, wc, &shift_state); #else n = (int)wctomb(p, wc); #endif if (n == -1) return (-1); p += n; } as->length = p - as->s; as->s[as->length] = '\0'; return (0); } /* * Conversion functions between current locale dependent MBS and UTF-16BE. * strncat_from_utf16be() : UTF-16BE --> MBS * strncat_to_utf16be() : MBS --> UTF16BE */ #if defined(_WIN32) && !defined(__CYGWIN__) /* * Convert a UTF-16BE/LE string to current locale and copy the result. * Return -1 if conversion fails. */ static int win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc, int be) { struct archive_string tmp; const char *u16; int ll; BOOL defchar; char *mbs; size_t mbs_size, b; int ret = 0; bytes &= ~1; if (archive_string_ensure(as, as->length + bytes +1) == NULL) return (-1); mbs = as->s + as->length; mbs_size = as->buffer_length - as->length -1; if (sc->to_cp == CP_C_LOCALE) { /* * "C" locale special process. */ u16 = _p; ll = 0; for (b = 0; b < bytes; b += 2) { uint16_t val; if (be) val = archive_be16dec(u16+b); else val = archive_le16dec(u16+b); if (val > 255) { *mbs++ = '?'; ret = -1; } else *mbs++ = (char)(val&0xff); ll++; } as->length += ll; as->s[as->length] = '\0'; return (ret); } archive_string_init(&tmp); if (be) { if (is_big_endian()) { u16 = _p; } else { if (archive_string_ensure(&tmp, bytes+2) == NULL) return (-1); memcpy(tmp.s, _p, bytes); for (b = 0; b < bytes; b += 2) { uint16_t val = archive_be16dec(tmp.s+b); archive_le16enc(tmp.s+b, val); } u16 = tmp.s; } } else { if (!is_big_endian()) { u16 = _p; } else { if (archive_string_ensure(&tmp, bytes+2) == NULL) return (-1); memcpy(tmp.s, _p, bytes); for (b = 0; b < bytes; b += 2) { uint16_t val = archive_le16dec(tmp.s+b); archive_be16enc(tmp.s+b, val); } u16 = tmp.s; } } do { defchar = 0; ll = WideCharToMultiByte(sc->to_cp, 0, (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size, NULL, &defchar); /* Exit loop if we succeeded */ if (ll != 0 || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { break; } /* Else expand buffer and loop to try again. */ ll = WideCharToMultiByte(sc->to_cp, 0, (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL); if (archive_string_ensure(as, ll +1) == NULL) return (-1); mbs = as->s + as->length; mbs_size = as->buffer_length - as->length -1; } while (1); archive_string_free(&tmp); as->length += ll; as->s[as->length] = '\0'; if (ll == 0 || defchar) ret = -1; return (ret); } static int win_strncat_from_utf16be(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (win_strncat_from_utf16(as, _p, bytes, sc, 1)); } static int win_strncat_from_utf16le(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (win_strncat_from_utf16(as, _p, bytes, sc, 0)); } static int is_big_endian(void) { uint16_t d = 1; return (archive_be16dec(&d) == 1); } /* * Convert a current locale string to UTF-16BE/LE and copy the result. * Return -1 if conversion fails. */ static int win_strncat_to_utf16(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc, int bigendian) { const char *s = (const char *)_p; char *u16; size_t count, avail; if (archive_string_ensure(as16, as16->length + (length + 1) * 2) == NULL) return (-1); u16 = as16->s + as16->length; avail = as16->buffer_length - 2; if (sc->from_cp == CP_C_LOCALE) { /* * "C" locale special process. */ count = 0; while (count < length && *s) { if (bigendian) archive_be16enc(u16, *s); else archive_le16enc(u16, *s); u16 += 2; s++; count++; } as16->length += count << 1; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; return (0); } do { count = MultiByteToWideChar(sc->from_cp, MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1); /* Exit loop if we succeeded */ if (count != 0 || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { break; } /* Expand buffer and try again */ count = MultiByteToWideChar(sc->from_cp, MB_PRECOMPOSED, s, (int)length, NULL, 0); if (archive_string_ensure(as16, (count +1) * 2) == NULL) return (-1); u16 = as16->s + as16->length; avail = as16->buffer_length - 2; } while (1); as16->length += count * 2; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; if (count == 0) return (-1); if (is_big_endian()) { if (!bigendian) { while (count > 0) { uint16_t v = archive_be16dec(u16); archive_le16enc(u16, v); u16 += 2; count--; } } } else { if (bigendian) { while (count > 0) { uint16_t v = archive_le16dec(u16); archive_be16enc(u16, v); u16 += 2; count--; } } } return (0); } static int win_strncat_to_utf16be(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (win_strncat_to_utf16(as16, _p, length, sc, 1)); } static int win_strncat_to_utf16le(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (win_strncat_to_utf16(as16, _p, length, sc, 0)); } #endif /* _WIN32 && !__CYGWIN__ */ /* * Do the best effort for conversions. * We cannot handle UTF-16BE character-set without such iconv, * but there is a chance if a string consists just ASCII code or * a current locale is UTF-8. */ /* * Convert a UTF-16BE string to current locale and copy the result. * Return -1 if conversion fails. */ static int best_effort_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc, int be) { const char *utf16 = (const char *)_p; char *mbs; uint32_t uc; int n, ret; (void)sc; /* UNUSED */ /* * Other case, we should do the best effort. * If all character are ASCII(<0x7f), we can convert it. * if not , we set a alternative character and return -1. */ ret = 0; if (archive_string_ensure(as, as->length + bytes +1) == NULL) return (-1); mbs = as->s + as->length; while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) { if (n < 0) { n *= -1; ret = -1; } bytes -= n; utf16 += n; if (uc > 127) { /* We cannot handle it. */ *mbs++ = '?'; ret = -1; } else *mbs++ = (char)uc; } as->length = mbs - as->s; as->s[as->length] = '\0'; return (ret); } static int best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1)); } static int best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0)); } /* * Convert a current locale string to UTF-16BE/LE and copy the result. * Return -1 if conversion fails. */ static int best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc, int bigendian) { const char *s = (const char *)_p; char *utf16; size_t remaining; int ret; (void)sc; /* UNUSED */ /* * Other case, we should do the best effort. * If all character are ASCII(<0x7f), we can convert it. * if not , we set a alternative character and return -1. */ ret = 0; remaining = length; if (archive_string_ensure(as16, as16->length + (length + 1) * 2) == NULL) return (-1); utf16 = as16->s + as16->length; while (remaining--) { unsigned c = *s++; if (c > 127) { /* We cannot handle it. */ c = UNICODE_R_CHAR; ret = -1; } if (bigendian) archive_be16enc(utf16, c); else archive_le16enc(utf16, c); utf16 += 2; } as16->length = utf16 - as16->s; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; return (ret); } static int best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1)); } static int best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0)); } /* * Multistring operations. */ void archive_mstring_clean(struct archive_mstring *aes) { archive_wstring_free(&(aes->aes_wcs)); archive_string_free(&(aes->aes_mbs)); archive_string_free(&(aes->aes_utf8)); archive_string_free(&(aes->aes_mbs_in_locale)); aes->aes_set = 0; } void archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src) { dest->aes_set = src->aes_set; archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs)); archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8)); archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs)); } int archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes, const char **p) { struct archive_string_conv *sc; int r; /* If we already have a UTF8 form, return that immediately. */ if (aes->aes_set & AES_SET_UTF8) { *p = aes->aes_utf8.s; return (0); } *p = NULL; if (aes->aes_set & AES_SET_MBS) { sc = archive_string_conversion_to_charset(a, "UTF-8", 1); if (sc == NULL) return (-1);/* Couldn't allocate memory for sc. */ r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s, aes->aes_mbs.length, sc); if (a == NULL) free_sconv_object(sc); if (r == 0) { aes->aes_set |= AES_SET_UTF8; *p = aes->aes_utf8.s; return (0);/* success. */ } else return (-1);/* failure. */ } return (0);/* success. */ } int archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes, const char **p) { int r, ret = 0; (void)a; /* UNUSED */ /* If we already have an MBS form, return that immediately. */ if (aes->aes_set & AES_SET_MBS) { *p = aes->aes_mbs.s; return (ret); } *p = NULL; /* If there's a WCS form, try converting with the native locale. */ if (aes->aes_set & AES_SET_WCS) { archive_string_empty(&(aes->aes_mbs)); r = archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s, aes->aes_wcs.length); *p = aes->aes_mbs.s; if (r == 0) { aes->aes_set |= AES_SET_MBS; return (ret); } else ret = -1; } /* * Only a UTF-8 form cannot avail because its conversion already * failed at archive_mstring_update_utf8(). */ return (ret); } int archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes, const wchar_t **wp) { int r, ret = 0; (void)a;/* UNUSED */ /* Return WCS form if we already have it. */ if (aes->aes_set & AES_SET_WCS) { *wp = aes->aes_wcs.s; return (ret); } *wp = NULL; /* Try converting MBS to WCS using native locale. */ if (aes->aes_set & AES_SET_MBS) { archive_wstring_empty(&(aes->aes_wcs)); r = archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s, aes->aes_mbs.length); if (r == 0) { aes->aes_set |= AES_SET_WCS; *wp = aes->aes_wcs.s; } else ret = -1;/* failure. */ } return (ret); } int archive_mstring_get_mbs_l(struct archive_mstring *aes, const char **p, size_t *length, struct archive_string_conv *sc) { int r, ret = 0; #if defined(_WIN32) && !defined(__CYGWIN__) /* * Internationalization programming on Windows must use Wide * characters because Windows platform cannot make locale UTF-8. */ if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) { archive_string_empty(&(aes->aes_mbs_in_locale)); r = archive_string_append_from_wcs_in_codepage( &(aes->aes_mbs_in_locale), aes->aes_wcs.s, aes->aes_wcs.length, sc); if (r == 0) { *p = aes->aes_mbs_in_locale.s; if (length != NULL) *length = aes->aes_mbs_in_locale.length; return (0); } else if (errno == ENOMEM) return (-1); else ret = -1; } #endif /* If there is not an MBS form but is a WCS form, try converting * with the native locale to be used for translating it to specified * character-set. */ if ((aes->aes_set & AES_SET_MBS) == 0 && (aes->aes_set & AES_SET_WCS) != 0) { archive_string_empty(&(aes->aes_mbs)); r = archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s, aes->aes_wcs.length); if (r == 0) aes->aes_set |= AES_SET_MBS; else if (errno == ENOMEM) return (-1); else ret = -1; } /* If we already have an MBS form, use it to be translated to * specified character-set. */ if (aes->aes_set & AES_SET_MBS) { if (sc == NULL) { /* Conversion is unneeded. */ *p = aes->aes_mbs.s; if (length != NULL) *length = aes->aes_mbs.length; return (0); } ret = archive_strncpy_l(&(aes->aes_mbs_in_locale), aes->aes_mbs.s, aes->aes_mbs.length, sc); *p = aes->aes_mbs_in_locale.s; if (length != NULL) *length = aes->aes_mbs_in_locale.length; } else { *p = NULL; if (length != NULL) *length = 0; } return (ret); } int archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs) { if (mbs == NULL) { aes->aes_set = 0; return (0); } return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs))); } int archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs, size_t len) { if (mbs == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ archive_strncpy(&(aes->aes_mbs), mbs, len); archive_string_empty(&(aes->aes_utf8)); archive_wstring_empty(&(aes->aes_wcs)); return (0); } int archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs) { return archive_mstring_copy_wcs_len(aes, wcs, wcs == NULL ? 0 : wcslen(wcs)); } int archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8) { if (utf8 == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_UTF8; archive_string_empty(&(aes->aes_mbs)); archive_string_empty(&(aes->aes_wcs)); archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8)); return (int)strlen(utf8); } int archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs, size_t len) { if (wcs == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_WCS; /* Only WCS form set. */ archive_string_empty(&(aes->aes_mbs)); archive_string_empty(&(aes->aes_utf8)); archive_wstrncpy(&(aes->aes_wcs), wcs, len); return (0); } int archive_mstring_copy_mbs_len_l(struct archive_mstring *aes, const char *mbs, size_t len, struct archive_string_conv *sc) { int r; if (mbs == NULL) { aes->aes_set = 0; return (0); } archive_string_empty(&(aes->aes_mbs)); archive_wstring_empty(&(aes->aes_wcs)); archive_string_empty(&(aes->aes_utf8)); #if defined(_WIN32) && !defined(__CYGWIN__) /* * Internationalization programming on Windows must use Wide * characters because Windows platform cannot make locale UTF-8. */ if (sc == NULL) { if (archive_string_append(&(aes->aes_mbs), mbs, mbsnbytes(mbs, len)) == NULL) { aes->aes_set = 0; r = -1; } else { aes->aes_set = AES_SET_MBS; r = 0; } #if defined(HAVE_ICONV) } else if (sc != NULL && sc->cd_w != (iconv_t)-1) { /* * This case happens only when MultiByteToWideChar() cannot * handle sc->from_cp, and we have to iconv in order to * translate character-set to wchar_t,UTF-16. */ iconv_t cd = sc->cd; unsigned from_cp; int flag; /* * Translate multi-bytes from some character-set to UTF-8. */ sc->cd = sc->cd_w; r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc); sc->cd = cd; if (r != 0) { aes->aes_set = 0; return (r); } aes->aes_set = AES_SET_UTF8; /* * Append the UTF-8 string into wstring. */ flag = sc->flag; sc->flag &= ~(SCONV_NORMALIZATION_C | SCONV_TO_UTF16| SCONV_FROM_UTF16); from_cp = sc->from_cp; sc->from_cp = CP_UTF8; r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs), aes->aes_utf8.s, aes->aes_utf8.length, sc); sc->flag = flag; sc->from_cp = from_cp; if (r == 0) aes->aes_set |= AES_SET_WCS; #endif } else { r = archive_wstring_append_from_mbs_in_codepage( &(aes->aes_wcs), mbs, len, sc); if (r == 0) aes->aes_set = AES_SET_WCS; else aes->aes_set = 0; } #else r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc); if (r == 0) aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ else aes->aes_set = 0; #endif return (r); } /* * The 'update' form tries to proactively update all forms of * this string (WCS and MBS) and returns an error if any of * them fail. This is used by the 'pax' handler, for instance, * to detect and report character-conversion failures early while * still allowing clients to get potentially useful values from * the more tolerant lazy conversions. (get_mbs and get_wcs will * strive to give the user something useful, so you can get hopefully * usable values even if some of the character conversions are failing.) */ int archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes, const char *utf8) { struct archive_string_conv *sc; int r; if (utf8 == NULL) { aes->aes_set = 0; return (0); /* Succeeded in clearing everything. */ } /* Save the UTF8 string. */ archive_strcpy(&(aes->aes_utf8), utf8); /* Empty the mbs and wcs strings. */ archive_string_empty(&(aes->aes_mbs)); archive_wstring_empty(&(aes->aes_wcs)); aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */ /* Try converting UTF-8 to MBS, return false on failure. */ sc = archive_string_conversion_from_charset(a, "UTF-8", 1); if (sc == NULL) return (-1);/* Couldn't allocate memory for sc. */ r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc); if (a == NULL) free_sconv_object(sc); if (r != 0) return (-1); aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */ /* Try converting MBS to WCS, return false on failure. */ if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s, aes->aes_mbs.length)) return (-1); aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS; /* All conversions succeeded. */ return (0); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1274_0
crossvul-cpp_data_good_220_0
/* * VC-1 and WMV3 decoder * Copyright (c) 2011 Mashiat Sarker Shakkhar * Copyright (c) 2006-2007 Konstantin Shishkov * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer * * 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 */ /** * @file * VC-1 and WMV3 block decoding routines */ #include "avcodec.h" #include "mpegutils.h" #include "mpegvideo.h" #include "msmpeg4data.h" #include "unary.h" #include "vc1.h" #include "vc1_pred.h" #include "vc1acdata.h" #include "vc1data.h" #define MB_INTRA_VLC_BITS 9 #define DC_VLC_BITS 9 // offset tables for interlaced picture MVDATA decoding static const uint8_t offset_table[2][9] = { { 0, 1, 2, 4, 8, 16, 32, 64, 128 }, { 0, 1, 3, 7, 15, 31, 63, 127, 255 }, }; // mapping table for internal block representation static const int block_map[6] = {0, 2, 1, 3, 4, 5}; /***********************************************************************/ /** * @name VC-1 Bitplane decoding * @see 8.7, p56 * @{ */ static inline void init_block_index(VC1Context *v) { MpegEncContext *s = &v->s; ff_init_block_index(s); if (v->field_mode && !(v->second_field ^ v->tff)) { s->dest[0] += s->current_picture_ptr->f->linesize[0]; s->dest[1] += s->current_picture_ptr->f->linesize[1]; s->dest[2] += s->current_picture_ptr->f->linesize[2]; } } /** @} */ //Bitplane group static void vc1_put_blocks_clamped(VC1Context *v, int put_signed) { MpegEncContext *s = &v->s; uint8_t *dest; int block_count = CONFIG_GRAY && (s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 4 : 6; int fieldtx = 0; int i; /* The put pixels loop is one MB row and one MB column behind the decoding * loop because we can only put pixels when overlap filtering is done. For * interlaced frame pictures, however, the put pixels loop is only one * column behind the decoding loop as interlaced frame pictures only need * horizontal overlap filtering. */ if (!s->first_slice_line && v->fcm != ILACE_FRAME) { if (s->mb_x) { for (i = 0; i < block_count; i++) { if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i] - 1] : v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i] - 2]) { dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + ((i & 1) - 2) * 8; if (put_signed) s->idsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, i > 3 ? s->uvlinesize : s->linesize); else s->idsp.put_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, i > 3 ? s->uvlinesize : s->linesize); } } } if (s->mb_x == v->end_mb_x - 1) { for (i = 0; i < block_count; i++) { if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i]] : v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i]]) { dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + (i & 1) * 8; if (put_signed) s->idsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, i > 3 ? s->uvlinesize : s->linesize); else s->idsp.put_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, i > 3 ? s->uvlinesize : s->linesize); } } } } if (s->mb_y == s->end_mb_y - 1 || v->fcm == ILACE_FRAME) { if (s->mb_x) { if (v->fcm == ILACE_FRAME) fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x - 1]; for (i = 0; i < block_count; i++) { if (i > 3 ? v->mb_type[0][s->block_index[i] - 1] : v->mb_type[0][s->block_index[i] - 2]) { if (fieldtx) dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + ((i & 1) - 2) * 8; else dest = s->dest[0] + (i & 2) * 4 * s->linesize + ((i & 1) - 2) * 8; if (put_signed) s->idsp.put_signed_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 : dest, i > 3 ? s->uvlinesize : s->linesize << fieldtx); else s->idsp.put_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] - 8 : dest, i > 3 ? s->uvlinesize : s->linesize << fieldtx); } } } if (s->mb_x == v->end_mb_x - 1) { if (v->fcm == ILACE_FRAME) fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x]; for (i = 0; i < block_count; i++) { if (v->mb_type[0][s->block_index[i]]) { if (fieldtx) dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + (i & 1) * 8; else dest = s->dest[0] + (i & 2) * 4 * s->linesize + (i & 1) * 8; if (put_signed) s->idsp.put_signed_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] : dest, i > 3 ? s->uvlinesize : s->linesize << fieldtx); else s->idsp.put_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], i > 3 ? s->dest[i - 3] : dest, i > 3 ? s->uvlinesize : s->linesize << fieldtx); } } } } } #define inc_blk_idx(idx) do { \ idx++; \ if (idx >= v->n_allocated_blks) \ idx = 0; \ } while (0) /***********************************************************************/ /** * @name VC-1 Block-level functions * @see 7.1.4, p91 and 8.1.1.7, p(1)04 * @{ */ /** * @def GET_MQUANT * @brief Get macroblock-level quantizer scale */ #define GET_MQUANT() \ if (v->dquantfrm) { \ int edges = 0; \ if (v->dqprofile == DQPROFILE_ALL_MBS) { \ if (v->dqbilevel) { \ mquant = (get_bits1(gb)) ? -v->altpq : v->pq; \ } else { \ mqdiff = get_bits(gb, 3); \ if (mqdiff != 7) \ mquant = -v->pq - mqdiff; \ else \ mquant = -get_bits(gb, 5); \ } \ } \ if (v->dqprofile == DQPROFILE_SINGLE_EDGE) \ edges = 1 << v->dqsbedge; \ else if (v->dqprofile == DQPROFILE_DOUBLE_EDGES) \ edges = (3 << v->dqsbedge) % 15; \ else if (v->dqprofile == DQPROFILE_FOUR_EDGES) \ edges = 15; \ if ((edges&1) && !s->mb_x) \ mquant = -v->altpq; \ if ((edges&2) && !s->mb_y) \ mquant = -v->altpq; \ if ((edges&4) && s->mb_x == (s->mb_width - 1)) \ mquant = -v->altpq; \ if ((edges&8) && \ s->mb_y == ((s->mb_height >> v->field_mode) - 1)) \ mquant = -v->altpq; \ if (!mquant || mquant > 31 || mquant < -31) { \ av_log(v->s.avctx, AV_LOG_ERROR, \ "Overriding invalid mquant %d\n", mquant); \ mquant = 1; \ } \ } /** * @def GET_MVDATA(_dmv_x, _dmv_y) * @brief Get MV differentials * @see MVDATA decoding from 8.3.5.2, p(1)20 * @param _dmv_x Horizontal differential for decoded MV * @param _dmv_y Vertical differential for decoded MV */ #define GET_MVDATA(_dmv_x, _dmv_y) \ index = 1 + get_vlc2(gb, ff_vc1_mv_diff_vlc[s->mv_table_index].table, \ VC1_MV_DIFF_VLC_BITS, 2); \ if (index > 36) { \ mb_has_coeffs = 1; \ index -= 37; \ } else \ mb_has_coeffs = 0; \ s->mb_intra = 0; \ if (!index) { \ _dmv_x = _dmv_y = 0; \ } else if (index == 35) { \ _dmv_x = get_bits(gb, v->k_x - 1 + s->quarter_sample); \ _dmv_y = get_bits(gb, v->k_y - 1 + s->quarter_sample); \ } else if (index == 36) { \ _dmv_x = 0; \ _dmv_y = 0; \ s->mb_intra = 1; \ } else { \ index1 = index % 6; \ _dmv_x = offset_table[1][index1]; \ val = size_table[index1] - (!s->quarter_sample && index1 == 5); \ if (val > 0) { \ val = get_bits(gb, val); \ sign = 0 - (val & 1); \ _dmv_x = (sign ^ ((val >> 1) + _dmv_x)) - sign; \ } \ \ index1 = index / 6; \ _dmv_y = offset_table[1][index1]; \ val = size_table[index1] - (!s->quarter_sample && index1 == 5); \ if (val > 0) { \ val = get_bits(gb, val); \ sign = 0 - (val & 1); \ _dmv_y = (sign ^ ((val >> 1) + _dmv_y)) - sign; \ } \ } static av_always_inline void get_mvdata_interlaced(VC1Context *v, int *dmv_x, int *dmv_y, int *pred_flag) { int index, index1; int extend_x, extend_y; GetBitContext *gb = &v->s.gb; int bits, esc; int val, sign; if (v->numref) { bits = VC1_2REF_MVDATA_VLC_BITS; esc = 125; } else { bits = VC1_1REF_MVDATA_VLC_BITS; esc = 71; } extend_x = v->dmvrange & 1; extend_y = (v->dmvrange >> 1) & 1; index = get_vlc2(gb, v->imv_vlc->table, bits, 3); if (index == esc) { *dmv_x = get_bits(gb, v->k_x); *dmv_y = get_bits(gb, v->k_y); if (v->numref) { if (pred_flag) *pred_flag = *dmv_y & 1; *dmv_y = (*dmv_y + (*dmv_y & 1)) >> 1; } } else { av_assert0(index < esc); index1 = (index + 1) % 9; if (index1 != 0) { val = get_bits(gb, index1 + extend_x); sign = 0 - (val & 1); *dmv_x = (sign ^ ((val >> 1) + offset_table[extend_x][index1])) - sign; } else *dmv_x = 0; index1 = (index + 1) / 9; if (index1 > v->numref) { val = get_bits(gb, (index1 >> v->numref) + extend_y); sign = 0 - (val & 1); *dmv_y = (sign ^ ((val >> 1) + offset_table[extend_y][index1 >> v->numref])) - sign; } else *dmv_y = 0; if (v->numref && pred_flag) *pred_flag = index1 & 1; } } /** Reconstruct motion vector for B-frame and do motion compensation */ static inline void vc1_b_mc(VC1Context *v, int dmv_x[2], int dmv_y[2], int direct, int mode) { if (direct) { ff_vc1_mc_1mv(v, 0); ff_vc1_interp_mc(v); return; } if (mode == BMV_TYPE_INTERPOLATED) { ff_vc1_mc_1mv(v, 0); ff_vc1_interp_mc(v); return; } ff_vc1_mc_1mv(v, (mode == BMV_TYPE_BACKWARD)); } /** Get predicted DC value for I-frames only * prediction dir: left=0, top=1 * @param s MpegEncContext * @param overlap flag indicating that overlap filtering is used * @param pq integer part of picture quantizer * @param[in] n block index in the current MB * @param dc_val_ptr Pointer to DC predictor * @param dir_ptr Prediction direction for use in AC prediction */ static inline int vc1_i_pred_dc(MpegEncContext *s, int overlap, int pq, int n, int16_t **dc_val_ptr, int *dir_ptr) { int a, b, c, wrap, pred, scale; int16_t *dc_val; static const uint16_t dcpred[32] = { -1, 1024, 512, 341, 256, 205, 171, 146, 128, 114, 102, 93, 85, 79, 73, 68, 64, 60, 57, 54, 51, 49, 47, 45, 43, 41, 39, 38, 37, 35, 34, 33 }; /* find prediction - wmv3_dc_scale always used here in fact */ if (n < 4) scale = s->y_dc_scale; else scale = s->c_dc_scale; wrap = s->block_wrap[n]; dc_val = s->dc_val[0] + s->block_index[n]; /* B A * C X */ c = dc_val[ - 1]; b = dc_val[ - 1 - wrap]; a = dc_val[ - wrap]; if (pq < 9 || !overlap) { /* Set outer values */ if (s->first_slice_line && (n != 2 && n != 3)) b = a = dcpred[scale]; if (s->mb_x == 0 && (n != 1 && n != 3)) b = c = dcpred[scale]; } else { /* Set outer values */ if (s->first_slice_line && (n != 2 && n != 3)) b = a = 0; if (s->mb_x == 0 && (n != 1 && n != 3)) b = c = 0; } if (abs(a - b) <= abs(b - c)) { pred = c; *dir_ptr = 1; // left } else { pred = a; *dir_ptr = 0; // top } /* update predictor */ *dc_val_ptr = &dc_val[0]; return pred; } /** Get predicted DC value * prediction dir: left=0, top=1 * @param s MpegEncContext * @param overlap flag indicating that overlap filtering is used * @param pq integer part of picture quantizer * @param[in] n block index in the current MB * @param a_avail flag indicating top block availability * @param c_avail flag indicating left block availability * @param dc_val_ptr Pointer to DC predictor * @param dir_ptr Prediction direction for use in AC prediction */ static inline int ff_vc1_pred_dc(MpegEncContext *s, int overlap, int pq, int n, int a_avail, int c_avail, int16_t **dc_val_ptr, int *dir_ptr) { int a, b, c, wrap, pred; int16_t *dc_val; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int q1, q2 = 0; int dqscale_index; /* scale predictors if needed */ q1 = FFABS(s->current_picture.qscale_table[mb_pos]); dqscale_index = s->y_dc_scale_table[q1] - 1; if (dqscale_index < 0) return 0; wrap = s->block_wrap[n]; dc_val = s->dc_val[0] + s->block_index[n]; /* B A * C X */ c = dc_val[ - 1]; b = dc_val[ - 1 - wrap]; a = dc_val[ - wrap]; if (c_avail && (n != 1 && n != 3)) { q2 = FFABS(s->current_picture.qscale_table[mb_pos - 1]); if (q2 && q2 != q1) c = (c * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18; } if (a_avail && (n != 2 && n != 3)) { q2 = FFABS(s->current_picture.qscale_table[mb_pos - s->mb_stride]); if (q2 && q2 != q1) a = (a * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18; } if (a_avail && c_avail && (n != 3)) { int off = mb_pos; if (n != 1) off--; if (n != 2) off -= s->mb_stride; q2 = FFABS(s->current_picture.qscale_table[off]); if (q2 && q2 != q1) b = (b * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18; } if (c_avail && (!a_avail || abs(a - b) <= abs(b - c))) { pred = c; *dir_ptr = 1; // left } else if (a_avail) { pred = a; *dir_ptr = 0; // top } else { pred = 0; *dir_ptr = 1; // left } /* update predictor */ *dc_val_ptr = &dc_val[0]; return pred; } /** @} */ // Block group /** * @name VC1 Macroblock-level functions in Simple/Main Profiles * @see 7.1.4, p91 and 8.1.1.7, p(1)04 * @{ */ static inline int vc1_coded_block_pred(MpegEncContext * s, int n, uint8_t **coded_block_ptr) { int xy, wrap, pred, a, b, c; xy = s->block_index[n]; wrap = s->b8_stride; /* B C * A X */ a = s->coded_block[xy - 1 ]; b = s->coded_block[xy - 1 - wrap]; c = s->coded_block[xy - wrap]; if (b == c) { pred = a; } else { pred = c; } /* store value */ *coded_block_ptr = &s->coded_block[xy]; return pred; } /** * Decode one AC coefficient * @param v The VC1 context * @param last Last coefficient * @param skip How much zero coefficients to skip * @param value Decoded AC coefficient value * @param codingset set of VLC to decode data * @see 8.1.3.4 */ static void vc1_decode_ac_coeff(VC1Context *v, int *last, int *skip, int *value, int codingset) { GetBitContext *gb = &v->s.gb; int index, run, level, lst, sign; index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3); if (index != ff_vc1_ac_sizes[codingset] - 1) { run = vc1_index_decode_table[codingset][index][0]; level = vc1_index_decode_table[codingset][index][1]; lst = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0; sign = get_bits1(gb); } else { int escape = decode210(gb); if (escape != 2) { index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3); run = vc1_index_decode_table[codingset][index][0]; level = vc1_index_decode_table[codingset][index][1]; lst = index >= vc1_last_decode_table[codingset]; if (escape == 0) { if (lst) level += vc1_last_delta_level_table[codingset][run]; else level += vc1_delta_level_table[codingset][run]; } else { if (lst) run += vc1_last_delta_run_table[codingset][level] + 1; else run += vc1_delta_run_table[codingset][level] + 1; } sign = get_bits1(gb); } else { lst = get_bits1(gb); if (v->s.esc3_level_length == 0) { if (v->pq < 8 || v->dquantfrm) { // table 59 v->s.esc3_level_length = get_bits(gb, 3); if (!v->s.esc3_level_length) v->s.esc3_level_length = get_bits(gb, 2) + 8; } else { // table 60 v->s.esc3_level_length = get_unary(gb, 1, 6) + 2; } v->s.esc3_run_length = 3 + get_bits(gb, 2); } run = get_bits(gb, v->s.esc3_run_length); sign = get_bits1(gb); level = get_bits(gb, v->s.esc3_level_length); } } *last = lst; *skip = run; *value = (level ^ -sign) + sign; } /** Decode intra block in intra frames - should be faster than decode_intra_block * @param v VC1Context * @param block block to decode * @param[in] n subblock index * @param coded are AC coeffs present or not * @param codingset set of VLC to decode data */ static int vc1_decode_i_block(VC1Context *v, int16_t block[64], int n, int coded, int codingset) { GetBitContext *gb = &v->s.gb; MpegEncContext *s = &v->s; int dc_pred_dir = 0; /* Direction of the DC prediction used */ int i; int16_t *dc_val; int16_t *ac_val, *ac_val2; int dcdiff, scale; /* Get DC differential */ if (n < 4) { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } else { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } if (dcdiff < 0) { av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n"); return -1; } if (dcdiff) { const int m = (v->pq == 1 || v->pq == 2) ? 3 - v->pq : 0; if (dcdiff == 119 /* ESC index value */) { dcdiff = get_bits(gb, 8 + m); } else { if (m) dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1); } if (get_bits1(gb)) dcdiff = -dcdiff; } /* Prediction */ dcdiff += vc1_i_pred_dc(&v->s, v->overlap, v->pq, n, &dc_val, &dc_pred_dir); *dc_val = dcdiff; /* Store the quantized DC coeff, used for prediction */ if (n < 4) scale = s->y_dc_scale; else scale = s->c_dc_scale; block[0] = dcdiff * scale; ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; if (dc_pred_dir) // left ac_val -= 16; else // top ac_val -= 16 * s->block_wrap[n]; scale = v->pq * 2 + v->halfpq; //AC Decoding i = !!coded; if (coded) { int last = 0, skip, value; const uint8_t *zz_table; int k; if (v->s.ac_pred) { if (!dc_pred_dir) zz_table = v->zz_8x8[2]; else zz_table = v->zz_8x8[3]; } else zz_table = v->zz_8x8[1]; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, codingset); i += skip; if (i > 63) break; block[zz_table[i++]] = value; } /* apply AC prediction if needed */ if (s->ac_pred) { int sh; if (dc_pred_dir) { // left sh = v->left_blk_sh; } else { // top sh = v->top_blk_sh; ac_val += 8; } for (k = 1; k < 8; k++) block[k << sh] += ac_val[k]; } /* save AC coeffs for further prediction */ for (k = 1; k < 8; k++) { ac_val2[k] = block[k << v->left_blk_sh]; ac_val2[k + 8] = block[k << v->top_blk_sh]; } /* scale AC coeffs */ for (k = 1; k < 64; k++) if (block[k]) { block[k] *= scale; if (!v->pquantizer) block[k] += (block[k] < 0) ? -v->pq : v->pq; } } else { int k; memset(ac_val2, 0, 16 * 2); /* apply AC prediction if needed */ if (s->ac_pred) { int sh; if (dc_pred_dir) { //left sh = v->left_blk_sh; } else { // top sh = v->top_blk_sh; ac_val += 8; ac_val2 += 8; } memcpy(ac_val2, ac_val, 8 * 2); for (k = 1; k < 8; k++) { block[k << sh] = ac_val[k] * scale; if (!v->pquantizer && block[k << sh]) block[k << sh] += (block[k << sh] < 0) ? -v->pq : v->pq; } } } if (s->ac_pred) i = 63; s->block_last_index[n] = i; return 0; } /** Decode intra block in intra frames - should be faster than decode_intra_block * @param v VC1Context * @param block block to decode * @param[in] n subblock number * @param coded are AC coeffs present or not * @param codingset set of VLC to decode data * @param mquant quantizer value for this macroblock */ static int vc1_decode_i_block_adv(VC1Context *v, int16_t block[64], int n, int coded, int codingset, int mquant) { GetBitContext *gb = &v->s.gb; MpegEncContext *s = &v->s; int dc_pred_dir = 0; /* Direction of the DC prediction used */ int i; int16_t *dc_val = NULL; int16_t *ac_val, *ac_val2; int dcdiff; int a_avail = v->a_avail, c_avail = v->c_avail; int use_pred = s->ac_pred; int scale; int q1, q2 = 0; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int quant = FFABS(mquant); /* Get DC differential */ if (n < 4) { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } else { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } if (dcdiff < 0) { av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n"); return -1; } if (dcdiff) { const int m = (quant == 1 || quant == 2) ? 3 - quant : 0; if (dcdiff == 119 /* ESC index value */) { dcdiff = get_bits(gb, 8 + m); } else { if (m) dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1); } if (get_bits1(gb)) dcdiff = -dcdiff; } /* Prediction */ dcdiff += ff_vc1_pred_dc(&v->s, v->overlap, quant, n, v->a_avail, v->c_avail, &dc_val, &dc_pred_dir); *dc_val = dcdiff; /* Store the quantized DC coeff, used for prediction */ if (n < 4) scale = s->y_dc_scale; else scale = s->c_dc_scale; block[0] = dcdiff * scale; /* check if AC is needed at all */ if (!a_avail && !c_avail) use_pred = 0; scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq); ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; if (dc_pred_dir) // left ac_val -= 16; else // top ac_val -= 16 * s->block_wrap[n]; q1 = s->current_picture.qscale_table[mb_pos]; if (n == 3) q2 = q1; else if (dc_pred_dir) { if (n == 1) q2 = q1; else if (c_avail && mb_pos) q2 = s->current_picture.qscale_table[mb_pos - 1]; } else { if (n == 2) q2 = q1; else if (a_avail && mb_pos >= s->mb_stride) q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride]; } //AC Decoding i = 1; if (coded) { int last = 0, skip, value; const uint8_t *zz_table; int k; if (v->s.ac_pred) { if (!use_pred && v->fcm == ILACE_FRAME) { zz_table = v->zzi_8x8; } else { if (!dc_pred_dir) // top zz_table = v->zz_8x8[2]; else // left zz_table = v->zz_8x8[3]; } } else { if (v->fcm != ILACE_FRAME) zz_table = v->zz_8x8[1]; else zz_table = v->zzi_8x8; } while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, codingset); i += skip; if (i > 63) break; block[zz_table[i++]] = value; } /* apply AC prediction if needed */ if (use_pred) { int sh; if (dc_pred_dir) { // left sh = v->left_blk_sh; } else { // top sh = v->top_blk_sh; ac_val += 8; } /* scale predictors if needed*/ q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1; if (q1 < 1) return AVERROR_INVALIDDATA; if (q2) q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1; if (q2 && q1 != q2) { for (k = 1; k < 8; k++) block[k << sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } else { for (k = 1; k < 8; k++) block[k << sh] += ac_val[k]; } } /* save AC coeffs for further prediction */ for (k = 1; k < 8; k++) { ac_val2[k ] = block[k << v->left_blk_sh]; ac_val2[k + 8] = block[k << v->top_blk_sh]; } /* scale AC coeffs */ for (k = 1; k < 64; k++) if (block[k]) { block[k] *= scale; if (!v->pquantizer) block[k] += (block[k] < 0) ? -quant : quant; } } else { // no AC coeffs int k; memset(ac_val2, 0, 16 * 2); /* apply AC prediction if needed */ if (use_pred) { int sh; if (dc_pred_dir) { // left sh = v->left_blk_sh; } else { // top sh = v->top_blk_sh; ac_val += 8; ac_val2 += 8; } memcpy(ac_val2, ac_val, 8 * 2); q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1; if (q1 < 1) return AVERROR_INVALIDDATA; if (q2) q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1; if (q2 && q1 != q2) { for (k = 1; k < 8; k++) ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } for (k = 1; k < 8; k++) { block[k << sh] = ac_val2[k] * scale; if (!v->pquantizer && block[k << sh]) block[k << sh] += (block[k << sh] < 0) ? -quant : quant; } } } if (use_pred) i = 63; s->block_last_index[n] = i; return 0; } /** Decode intra block in inter frames - more generic version than vc1_decode_i_block * @param v VC1Context * @param block block to decode * @param[in] n subblock index * @param coded are AC coeffs present or not * @param mquant block quantizer * @param codingset set of VLC to decode data */ static int vc1_decode_intra_block(VC1Context *v, int16_t block[64], int n, int coded, int mquant, int codingset) { GetBitContext *gb = &v->s.gb; MpegEncContext *s = &v->s; int dc_pred_dir = 0; /* Direction of the DC prediction used */ int i; int16_t *dc_val = NULL; int16_t *ac_val, *ac_val2; int dcdiff; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int a_avail = v->a_avail, c_avail = v->c_avail; int use_pred = s->ac_pred; int scale; int q1, q2 = 0; int quant = FFABS(mquant); s->bdsp.clear_block(block); /* XXX: Guard against dumb values of mquant */ quant = av_clip_uintp2(quant, 5); /* Set DC scale - y and c use the same */ s->y_dc_scale = s->y_dc_scale_table[quant]; s->c_dc_scale = s->c_dc_scale_table[quant]; /* Get DC differential */ if (n < 4) { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } else { dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3); } if (dcdiff < 0) { av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n"); return -1; } if (dcdiff) { const int m = (quant == 1 || quant == 2) ? 3 - quant : 0; if (dcdiff == 119 /* ESC index value */) { dcdiff = get_bits(gb, 8 + m); } else { if (m) dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1); } if (get_bits1(gb)) dcdiff = -dcdiff; } /* Prediction */ dcdiff += ff_vc1_pred_dc(&v->s, v->overlap, quant, n, a_avail, c_avail, &dc_val, &dc_pred_dir); *dc_val = dcdiff; /* Store the quantized DC coeff, used for prediction */ if (n < 4) { block[0] = dcdiff * s->y_dc_scale; } else { block[0] = dcdiff * s->c_dc_scale; } //AC Decoding i = 1; /* check if AC is needed at all and adjust direction if needed */ if (!a_avail) dc_pred_dir = 1; if (!c_avail) dc_pred_dir = 0; if (!a_avail && !c_avail) use_pred = 0; ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq); if (dc_pred_dir) //left ac_val -= 16; else //top ac_val -= 16 * s->block_wrap[n]; q1 = s->current_picture.qscale_table[mb_pos]; if (dc_pred_dir && c_avail && mb_pos) q2 = s->current_picture.qscale_table[mb_pos - 1]; if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride) q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride]; if (dc_pred_dir && n == 1) q2 = q1; if (!dc_pred_dir && n == 2) q2 = q1; if (n == 3) q2 = q1; if (coded) { int last = 0, skip, value; int k; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, codingset); i += skip; if (i > 63) break; if (v->fcm == PROGRESSIVE) block[v->zz_8x8[0][i++]] = value; else { if (use_pred && (v->fcm == ILACE_FRAME)) { if (!dc_pred_dir) // top block[v->zz_8x8[2][i++]] = value; else // left block[v->zz_8x8[3][i++]] = value; } else { block[v->zzi_8x8[i++]] = value; } } } /* apply AC prediction if needed */ if (use_pred) { /* scale predictors if needed*/ q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1; if (q1 < 1) return AVERROR_INVALIDDATA; if (q2) q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1; if (q2 && q1 != q2) { if (dc_pred_dir) { // left for (k = 1; k < 8; k++) block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } else { //top for (k = 1; k < 8; k++) block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } } else { if (dc_pred_dir) { // left for (k = 1; k < 8; k++) block[k << v->left_blk_sh] += ac_val[k]; } else { // top for (k = 1; k < 8; k++) block[k << v->top_blk_sh] += ac_val[k + 8]; } } } /* save AC coeffs for further prediction */ for (k = 1; k < 8; k++) { ac_val2[k ] = block[k << v->left_blk_sh]; ac_val2[k + 8] = block[k << v->top_blk_sh]; } /* scale AC coeffs */ for (k = 1; k < 64; k++) if (block[k]) { block[k] *= scale; if (!v->pquantizer) block[k] += (block[k] < 0) ? -quant : quant; } if (use_pred) i = 63; } else { // no AC coeffs int k; memset(ac_val2, 0, 16 * 2); if (dc_pred_dir) { // left if (use_pred) { memcpy(ac_val2, ac_val, 8 * 2); q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1; if (q1 < 1) return AVERROR_INVALIDDATA; if (q2) q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1; if (q2 && q1 != q2) { for (k = 1; k < 8; k++) ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } } } else { // top if (use_pred) { memcpy(ac_val2 + 8, ac_val + 8, 8 * 2); q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1; if (q1 < 1) return AVERROR_INVALIDDATA; if (q2) q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1; if (q2 && q1 != q2) { for (k = 1; k < 8; k++) ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18; } } } /* apply AC prediction if needed */ if (use_pred) { if (dc_pred_dir) { // left for (k = 1; k < 8; k++) { block[k << v->left_blk_sh] = ac_val2[k] * scale; if (!v->pquantizer && block[k << v->left_blk_sh]) block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -quant : quant; } } else { // top for (k = 1; k < 8; k++) { block[k << v->top_blk_sh] = ac_val2[k + 8] * scale; if (!v->pquantizer && block[k << v->top_blk_sh]) block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -quant : quant; } } i = 63; } } s->block_last_index[n] = i; return 0; } /** Decode P block */ static int vc1_decode_p_block(VC1Context *v, int16_t block[64], int n, int mquant, int ttmb, int first_block, uint8_t *dst, int linesize, int skip_block, int *ttmb_out) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i, j; int subblkpat = 0; int scale, off, idx, last, skip, value; int ttblk = ttmb & 7; int pat = 0; int quant = FFABS(mquant); s->bdsp.clear_block(block); if (ttmb == -1) { ttblk = ff_vc1_ttblk_to_tt[v->tt_index][get_vlc2(gb, ff_vc1_ttblk_vlc[v->tt_index].table, VC1_TTBLK_VLC_BITS, 1)]; } if (ttblk == TT_4X4) { subblkpat = ~(get_vlc2(gb, ff_vc1_subblkpat_vlc[v->tt_index].table, VC1_SUBBLKPAT_VLC_BITS, 1) + 1); } if ((ttblk != TT_8X8 && ttblk != TT_4X4) && ((v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block)) || (!v->res_rtm_flag && !first_block))) { subblkpat = decode012(gb); if (subblkpat) subblkpat ^= 3; // swap decoded pattern bits if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) ttblk = TT_8X4; if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) ttblk = TT_4X8; } scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq); // convert transforms like 8X4_TOP to generic TT and SUBBLKPAT if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) { subblkpat = 2 - (ttblk == TT_8X4_TOP); ttblk = TT_8X4; } if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) { subblkpat = 2 - (ttblk == TT_4X8_LEFT); ttblk = TT_4X8; } switch (ttblk) { case TT_8X8: pat = 0xF; i = 0; last = 0; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2); i += skip; if (i > 63) break; if (!v->fcm) idx = v->zz_8x8[0][i++]; else idx = v->zzi_8x8[i++]; block[idx] = value * scale; if (!v->pquantizer) block[idx] += (block[idx] < 0) ? -quant : quant; } if (!skip_block) { if (i == 1) v->vc1dsp.vc1_inv_trans_8x8_dc(dst, linesize, block); else { v->vc1dsp.vc1_inv_trans_8x8(block); s->idsp.add_pixels_clamped(block, dst, linesize); } } break; case TT_4X4: pat = ~subblkpat & 0xF; for (j = 0; j < 4; j++) { last = subblkpat & (1 << (3 - j)); i = 0; off = (j & 1) * 4 + (j & 2) * 16; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2); i += skip; if (i > 15) break; if (!v->fcm) idx = ff_vc1_simple_progressive_4x4_zz[i++]; else idx = ff_vc1_adv_interlaced_4x4_zz[i++]; block[idx + off] = value * scale; if (!v->pquantizer) block[idx + off] += (block[idx + off] < 0) ? -quant : quant; } if (!(subblkpat & (1 << (3 - j))) && !skip_block) { if (i == 1) v->vc1dsp.vc1_inv_trans_4x4_dc(dst + (j & 1) * 4 + (j & 2) * 2 * linesize, linesize, block + off); else v->vc1dsp.vc1_inv_trans_4x4(dst + (j & 1) * 4 + (j & 2) * 2 * linesize, linesize, block + off); } } break; case TT_8X4: pat = ~((subblkpat & 2) * 6 + (subblkpat & 1) * 3) & 0xF; for (j = 0; j < 2; j++) { last = subblkpat & (1 << (1 - j)); i = 0; off = j * 32; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2); i += skip; if (i > 31) break; if (!v->fcm) idx = v->zz_8x4[i++] + off; else idx = ff_vc1_adv_interlaced_8x4_zz[i++] + off; block[idx] = value * scale; if (!v->pquantizer) block[idx] += (block[idx] < 0) ? -quant : quant; } if (!(subblkpat & (1 << (1 - j))) && !skip_block) { if (i == 1) v->vc1dsp.vc1_inv_trans_8x4_dc(dst + j * 4 * linesize, linesize, block + off); else v->vc1dsp.vc1_inv_trans_8x4(dst + j * 4 * linesize, linesize, block + off); } } break; case TT_4X8: pat = ~(subblkpat * 5) & 0xF; for (j = 0; j < 2; j++) { last = subblkpat & (1 << (1 - j)); i = 0; off = j * 4; while (!last) { vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2); i += skip; if (i > 31) break; if (!v->fcm) idx = v->zz_4x8[i++] + off; else idx = ff_vc1_adv_interlaced_4x8_zz[i++] + off; block[idx] = value * scale; if (!v->pquantizer) block[idx] += (block[idx] < 0) ? -quant : quant; } if (!(subblkpat & (1 << (1 - j))) && !skip_block) { if (i == 1) v->vc1dsp.vc1_inv_trans_4x8_dc(dst + j * 4, linesize, block + off); else v->vc1dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off); } } break; } if (ttmb_out) *ttmb_out |= ttblk << (n * 4); return pat; } /** @} */ // Macroblock group static const uint8_t size_table[6] = { 0, 2, 3, 4, 5, 8 }; /** Decode one P-frame MB */ static int vc1_decode_p_mb(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i, j; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mb_has_coeffs = 1; /* last_flag */ int dmv_x, dmv_y; /* Differential MV components */ int index, index1; /* LUT indexes */ int val, sign; /* temp values */ int first_block = 1; int dst_idx, off; int skipped, fourmv; int block_cbp = 0, pat, block_tt = 0, block_intra = 0; mquant = v->pq; /* lossy initialization */ if (v->mv_type_is_raw) fourmv = get_bits1(gb); else fourmv = v->mv_type_mb_plane[mb_pos]; if (v->skip_is_raw) skipped = get_bits1(gb); else skipped = v->s.mbskip_table[mb_pos]; if (!fourmv) { /* 1MV mode */ if (!skipped) { GET_MVDATA(dmv_x, dmv_y); if (s->mb_intra) { s->current_picture.motion_val[1][s->block_index[0]][0] = 0; s->current_picture.motion_val[1][s->block_index[0]][1] = 0; } s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16; ff_vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0); /* FIXME Set DC val for inter block ? */ if (s->mb_intra && !mb_has_coeffs) { GET_MQUANT(); s->ac_pred = get_bits1(gb); cbp = 0; } else if (mb_has_coeffs) { if (s->mb_intra) s->ac_pred = get_bits1(gb); cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); GET_MQUANT(); } else { mquant = v->pq; cbp = 0; } s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && !s->mb_intra && mb_has_coeffs) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); if (!s->mb_intra) ff_vc1_mc_1mv(v, 0); dst_idx = 0; for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); v->mb_type[0][s->block_index[i]] = s->mb_intra; if (s->mb_intra) { /* check if prediction blocks A and C are available */ v->a_avail = v->c_avail = 0; if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]); if (v->rangeredfrm) for (j = 0; j < 64; j++) v->block[v->cur_blk_idx][block_map[i]][j] <<= 1; block_cbp |= 0xF << (i << 2); block_intra |= 1 << i; } else if (val) { pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize, CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } else { // skipped s->mb_intra = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP; s->current_picture.qscale_table[mb_pos] = 0; ff_vc1_pred_mv(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0); ff_vc1_mc_1mv(v, 0); } } else { // 4MV mode if (!skipped /* unskipped MB */) { int intra_count = 0, coded_inter = 0; int is_intra[6], is_coded[6]; /* Get CBPCY */ cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); for (i = 0; i < 6; i++) { val = ((cbp >> (5 - i)) & 1); s->dc_val[0][s->block_index[i]] = 0; s->mb_intra = 0; if (i < 4) { dmv_x = dmv_y = 0; s->mb_intra = 0; mb_has_coeffs = 0; if (val) { GET_MVDATA(dmv_x, dmv_y); } ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0); if (!s->mb_intra) ff_vc1_mc_4mv_luma(v, i, 0, 0); intra_count += s->mb_intra; is_intra[i] = s->mb_intra; is_coded[i] = mb_has_coeffs; } if (i & 4) { is_intra[i] = (intra_count >= 3); is_coded[i] = val; } if (i == 4) ff_vc1_mc_4mv_chroma(v, 0); v->mb_type[0][s->block_index[i]] = is_intra[i]; if (!coded_inter) coded_inter = !is_intra[i] & is_coded[i]; } // if there are no coded blocks then don't do anything more dst_idx = 0; if (!intra_count && !coded_inter) goto end; GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* test if block is intra and has pred */ { int intrapred = 0; for (i = 0; i < 6; i++) if (is_intra[i]) { if (((!s->first_slice_line || (i == 2 || i == 3)) && v->mb_type[0][s->block_index[i] - s->block_wrap[i]]) || ((s->mb_x || (i == 1 || i == 3)) && v->mb_type[0][s->block_index[i] - 1])) { intrapred = 1; break; } } if (intrapred) s->ac_pred = get_bits1(gb); else s->ac_pred = 0; } if (!v->ttmbf && coded_inter) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); for (i = 0; i < 6; i++) { dst_idx += i >> 2; off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); s->mb_intra = is_intra[i]; if (is_intra[i]) { /* check if prediction blocks A and C are available */ v->a_avail = v->c_avail = 0; if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, is_coded[i], mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]); if (v->rangeredfrm) for (j = 0; j < 64; j++) v->block[v->cur_blk_idx][block_map[i]][j] <<= 1; block_cbp |= 0xF << (i << 2); block_intra |= 1 << i; } else if (is_coded[i]) { pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize, CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } else { // skipped MB s->mb_intra = 0; s->current_picture.qscale_table[mb_pos] = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } for (i = 0; i < 4; i++) { ff_vc1_pred_mv(v, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0); ff_vc1_mc_4mv_luma(v, i, 0, 0); } ff_vc1_mc_4mv_chroma(v, 0); s->current_picture.qscale_table[mb_pos] = 0; } } end: if (v->overlap && v->pq >= 9) ff_vc1_p_overlap_filter(v); vc1_put_blocks_clamped(v, 1); v->cbp[s->mb_x] = block_cbp; v->ttblk[s->mb_x] = block_tt; v->is_intra[s->mb_x] = block_intra; return 0; } /* Decode one macroblock in an interlaced frame p picture */ static int vc1_decode_p_mb_intfr(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mb_has_coeffs = 1; /* last_flag */ int dmv_x, dmv_y; /* Differential MV components */ int val; /* temp value */ int first_block = 1; int dst_idx, off; int skipped, fourmv = 0, twomv = 0; int block_cbp = 0, pat, block_tt = 0; int idx_mbmode = 0, mvbp; int fieldtx; mquant = v->pq; /* Lossy initialization */ if (v->skip_is_raw) skipped = get_bits1(gb); else skipped = v->s.mbskip_table[mb_pos]; if (!skipped) { if (v->fourmvswitch) idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); // try getting this done else idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); // in a single line switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) { /* store the motion vector type in a flag (useful later) */ case MV_PMODE_INTFR_4MV: fourmv = 1; v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; break; case MV_PMODE_INTFR_4MV_FIELD: fourmv = 1; v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; break; case MV_PMODE_INTFR_2MV_FIELD: twomv = 1; v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; break; case MV_PMODE_INTFR_1MV: v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; break; } if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB for (i = 0; i < 4; i++) { s->current_picture.motion_val[1][s->block_index[i]][0] = 0; s->current_picture.motion_val[1][s->block_index[i]][1] = 0; } v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1. s->mb_intra = 1; s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA; fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb); mb_has_coeffs = get_bits1(gb); if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb); GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* Set DC scale - y and c use the same (not sure if necessary here) */ s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)]; s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)]; dst_idx = 0; for (i = 0; i < 6; i++) { v->a_avail = v->c_avail = 0; v->mb_type[0][s->block_index[i]] = 1; s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]); if (i < 4) off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize; else off = 0; block_cbp |= 0xf << (i << 2); } } else { // inter MB mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][3]; if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) { v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1); } else { if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV) || (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) { v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1); } } s->mb_intra = v->is_intra[s->mb_x] = 0; for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0; fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][1]; /* for all motion vector read MVDATA and motion compensate each block */ dst_idx = 0; if (fourmv) { mvbp = v->fourmvbp; for (i = 0; i < 4; i++) { dmv_x = dmv_y = 0; if (mvbp & (8 >> i)) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_4mv_luma(v, i, 0, 0); } ff_vc1_mc_4mv_chroma4(v, 0, 0, 0); } else if (twomv) { mvbp = v->twomvbp; dmv_x = dmv_y = 0; if (mvbp & 2) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_4mv_luma(v, 0, 0, 0); ff_vc1_mc_4mv_luma(v, 1, 0, 0); dmv_x = dmv_y = 0; if (mvbp & 1) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_4mv_luma(v, 2, 0, 0); ff_vc1_mc_4mv_luma(v, 3, 0, 0); ff_vc1_mc_4mv_chroma4(v, 0, 0, 0); } else { mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2]; dmv_x = dmv_y = 0; if (mvbp) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); } ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_1mv(v, 0); } if (cbp) GET_MQUANT(); // p. 227 s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && cbp) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (!fieldtx) off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); else off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize)); if (val) { pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : (s->linesize << fieldtx), CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } } else { // skipped s->mb_intra = v->is_intra[s->mb_x] = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP; s->current_picture.qscale_table[mb_pos] = 0; v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_1mv(v, 0); v->fieldtx_plane[mb_pos] = 0; } if (v->overlap && v->pq >= 9) ff_vc1_p_overlap_filter(v); vc1_put_blocks_clamped(v, 1); v->cbp[s->mb_x] = block_cbp; v->ttblk[s->mb_x] = block_tt; return 0; } static int vc1_decode_p_mb_intfi(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mb_has_coeffs = 1; /* last_flag */ int dmv_x, dmv_y; /* Differential MV components */ int val; /* temp values */ int first_block = 1; int dst_idx, off; int pred_flag = 0; int block_cbp = 0, pat, block_tt = 0; int idx_mbmode = 0; mquant = v->pq; /* Lossy initialization */ idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2); if (idx_mbmode <= 1) { // intra MB v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1. s->mb_intra = 1; s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0; s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0; s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA; GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* Set DC scale - y and c use the same (not sure if necessary here) */ s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)]; s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)]; v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb); mb_has_coeffs = idx_mbmode & 1; if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2); dst_idx = 0; for (i = 0; i < 6; i++) { v->a_avail = v->c_avail = 0; v->mb_type[0][s->block_index[i]] = 1; s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]); off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); block_cbp |= 0xf << (i << 2); } } else { s->mb_intra = v->is_intra[s->mb_x] = 0; s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16; for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0; if (idx_mbmode <= 5) { // 1-MV dmv_x = dmv_y = pred_flag = 0; if (idx_mbmode & 1) { get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag); } ff_vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0); ff_vc1_mc_1mv(v, 0); mb_has_coeffs = !(idx_mbmode & 2); } else { // 4-MV v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1); for (i = 0; i < 4; i++) { dmv_x = dmv_y = pred_flag = 0; if (v->fourmvbp & (8 >> i)) get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag); ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0); ff_vc1_mc_4mv_luma(v, i, 0, 0); } ff_vc1_mc_4mv_chroma(v, 0); mb_has_coeffs = idx_mbmode & 1; } if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); if (cbp) { GET_MQUANT(); } s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && cbp) { ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); } dst_idx = 0; for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize; if (val) { pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize, CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } if (v->overlap && v->pq >= 9) ff_vc1_p_overlap_filter(v); vc1_put_blocks_clamped(v, 1); v->cbp[s->mb_x] = block_cbp; v->ttblk[s->mb_x] = block_tt; return 0; } /** Decode one B-frame MB (in Main profile) */ static void vc1_decode_b_mb(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i, j; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mb_has_coeffs = 0; /* last_flag */ int index, index1; /* LUT indexes */ int val, sign; /* temp values */ int first_block = 1; int dst_idx, off; int skipped, direct; int dmv_x[2], dmv_y[2]; int bmvtype = BMV_TYPE_BACKWARD; mquant = v->pq; /* lossy initialization */ s->mb_intra = 0; if (v->dmb_is_raw) direct = get_bits1(gb); else direct = v->direct_mb_plane[mb_pos]; if (v->skip_is_raw) skipped = get_bits1(gb); else skipped = v->s.mbskip_table[mb_pos]; dmv_x[0] = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } s->current_picture.qscale_table[mb_pos] = 0; if (!direct) { if (!skipped) { GET_MVDATA(dmv_x[0], dmv_y[0]); dmv_x[1] = dmv_x[0]; dmv_y[1] = dmv_y[0]; } if (skipped || !s->mb_intra) { bmvtype = decode012(gb); switch (bmvtype) { case 0: bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD; break; case 1: bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD; break; case 2: bmvtype = BMV_TYPE_INTERPOLATED; dmv_x[0] = dmv_y[0] = 0; } } } for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = s->mb_intra; if (skipped) { if (direct) bmvtype = BMV_TYPE_INTERPOLATED; ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype); return; } if (direct) { cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); GET_MQUANT(); s->mb_intra = 0; s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); dmv_x[0] = dmv_y[0] = dmv_x[1] = dmv_y[1] = 0; ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype); } else { if (!mb_has_coeffs && !s->mb_intra) { /* no coded blocks - effectively skipped */ ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype); return; } if (s->mb_intra && !mb_has_coeffs) { GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; s->ac_pred = get_bits1(gb); cbp = 0; ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); } else { if (bmvtype == BMV_TYPE_INTERPOLATED) { GET_MVDATA(dmv_x[0], dmv_y[0]); if (!mb_has_coeffs) { /* interpolated skipped block */ ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype); return; } } ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype); if (!s->mb_intra) { vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype); } if (s->mb_intra) s->ac_pred = get_bits1(gb); cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && !s->mb_intra && mb_has_coeffs) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); } } dst_idx = 0; for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); v->mb_type[0][s->block_index[i]] = s->mb_intra; if (s->mb_intra) { /* check if prediction blocks A and C are available */ v->a_avail = v->c_avail = 0; if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(s->block[i]); if (v->rangeredfrm) for (j = 0; j < 64; j++) s->block[i][j] <<= 1; s->idsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize); } else if (val) { vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize, CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), NULL); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } /** Decode one B-frame MB (in interlaced field B picture) */ static void vc1_decode_b_mb_intfi(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i, j; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mb_has_coeffs = 0; /* last_flag */ int val; /* temp value */ int first_block = 1; int dst_idx, off; int fwd; int dmv_x[2], dmv_y[2], pred_flag[2]; int bmvtype = BMV_TYPE_BACKWARD; int block_cbp = 0, pat, block_tt = 0; int idx_mbmode; mquant = v->pq; /* Lossy initialization */ s->mb_intra = 0; idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2); if (idx_mbmode <= 1) { // intra MB v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1. s->mb_intra = 1; s->current_picture.motion_val[1][s->block_index[0]][0] = 0; s->current_picture.motion_val[1][s->block_index[0]][1] = 0; s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA; GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* Set DC scale - y and c use the same (not sure if necessary here) */ s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)]; s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)]; v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb); mb_has_coeffs = idx_mbmode & 1; if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2); dst_idx = 0; for (i = 0; i < 6; i++) { v->a_avail = v->c_avail = 0; v->mb_type[0][s->block_index[i]] = 1; s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(s->block[i]); if (v->rangeredfrm) for (j = 0; j < 64; j++) s->block[i][j] <<= 1; off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); s->idsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize); } } else { s->mb_intra = v->is_intra[s->mb_x] = 0; s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16; for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0; if (v->fmb_is_raw) fwd = v->forward_mb_plane[mb_pos] = get_bits1(gb); else fwd = v->forward_mb_plane[mb_pos]; if (idx_mbmode <= 5) { // 1-MV int interpmvp = 0; dmv_x[0] = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0; pred_flag[0] = pred_flag[1] = 0; if (fwd) bmvtype = BMV_TYPE_FORWARD; else { bmvtype = decode012(gb); switch (bmvtype) { case 0: bmvtype = BMV_TYPE_BACKWARD; break; case 1: bmvtype = BMV_TYPE_DIRECT; break; case 2: bmvtype = BMV_TYPE_INTERPOLATED; interpmvp = get_bits1(gb); } } v->bmvtype = bmvtype; if (bmvtype != BMV_TYPE_DIRECT && idx_mbmode & 1) { get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD], &dmv_y[bmvtype == BMV_TYPE_BACKWARD], &pred_flag[bmvtype == BMV_TYPE_BACKWARD]); } if (interpmvp) { get_mvdata_interlaced(v, &dmv_x[1], &dmv_y[1], &pred_flag[1]); } if (bmvtype == BMV_TYPE_DIRECT) { dmv_x[0] = dmv_y[0] = pred_flag[0] = 0; dmv_x[1] = dmv_y[1] = pred_flag[0] = 0; if (!s->next_picture_ptr->field_picture) { av_log(s->avctx, AV_LOG_ERROR, "Mixed field/frame direct mode not supported\n"); return; } } ff_vc1_pred_b_mv_intfi(v, 0, dmv_x, dmv_y, 1, pred_flag); vc1_b_mc(v, dmv_x, dmv_y, (bmvtype == BMV_TYPE_DIRECT), bmvtype); mb_has_coeffs = !(idx_mbmode & 2); } else { // 4-MV if (fwd) bmvtype = BMV_TYPE_FORWARD; v->bmvtype = bmvtype; v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1); for (i = 0; i < 4; i++) { dmv_x[0] = dmv_y[0] = pred_flag[0] = 0; dmv_x[1] = dmv_y[1] = pred_flag[1] = 0; if (v->fourmvbp & (8 >> i)) { get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD], &dmv_y[bmvtype == BMV_TYPE_BACKWARD], &pred_flag[bmvtype == BMV_TYPE_BACKWARD]); } ff_vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag); ff_vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD, 0); } ff_vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD); mb_has_coeffs = idx_mbmode & 1; } if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); if (cbp) { GET_MQUANT(); } s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && cbp) { ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); } dst_idx = 0; for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize; if (val) { pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize, CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } v->cbp[s->mb_x] = block_cbp; v->ttblk[s->mb_x] = block_tt; } /** Decode one B-frame MB (in interlaced frame B picture) */ static int vc1_decode_b_mb_intfr(VC1Context *v) { MpegEncContext *s = &v->s; GetBitContext *gb = &s->gb; int i, j; int mb_pos = s->mb_x + s->mb_y * s->mb_stride; int cbp = 0; /* cbp decoding stuff */ int mqdiff, mquant; /* MB quantization */ int ttmb = v->ttfrm; /* MB Transform type */ int mvsw = 0; /* motion vector switch */ int mb_has_coeffs = 1; /* last_flag */ int dmv_x, dmv_y; /* Differential MV components */ int val; /* temp value */ int first_block = 1; int dst_idx, off; int skipped, direct, twomv = 0; int block_cbp = 0, pat, block_tt = 0; int idx_mbmode = 0, mvbp; int stride_y, fieldtx; int bmvtype = BMV_TYPE_BACKWARD; int dir, dir2; mquant = v->pq; /* Lossy initialization */ s->mb_intra = 0; if (v->skip_is_raw) skipped = get_bits1(gb); else skipped = v->s.mbskip_table[mb_pos]; if (!skipped) { idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) { twomv = 1; v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; } else { v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; } } if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = 0; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = 0; s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = 0; s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = 0; } v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1. s->mb_intra = 1; s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA; fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb); mb_has_coeffs = get_bits1(gb); if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb); GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* Set DC scale - y and c use the same (not sure if necessary here) */ s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)]; s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)]; dst_idx = 0; for (i = 0; i < 6; i++) { v->a_avail = v->c_avail = 0; v->mb_type[0][s->block_index[i]] = 1; s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (i == 2 || i == 3 || !s->first_slice_line) v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]]; if (i == 1 || i == 3 || s->mb_x) v->c_avail = v->mb_type[0][s->block_index[i] - 1]; vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i & 4) ? v->codingset2 : v->codingset); if (CONFIG_GRAY && i > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(s->block[i]); if (i < 4) { stride_y = s->linesize << fieldtx; off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize; } else { stride_y = s->uvlinesize; off = 0; } s->idsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, stride_y); } } else { s->mb_intra = v->is_intra[s->mb_x] = 0; if (v->dmb_is_raw) direct = get_bits1(gb); else direct = v->direct_mb_plane[mb_pos]; if (direct) { if (s->next_picture_ptr->field_picture) av_log(s->avctx, AV_LOG_WARNING, "Mixed frame/field direct mode not supported\n"); s->mv[0][0][0] = s->current_picture.motion_val[0][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 0, s->quarter_sample); s->mv[0][0][1] = s->current_picture.motion_val[0][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 0, s->quarter_sample); s->mv[1][0][0] = s->current_picture.motion_val[1][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 1, s->quarter_sample); s->mv[1][0][1] = s->current_picture.motion_val[1][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 1, s->quarter_sample); if (twomv) { s->mv[0][2][0] = s->current_picture.motion_val[0][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 0, s->quarter_sample); s->mv[0][2][1] = s->current_picture.motion_val[0][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 0, s->quarter_sample); s->mv[1][2][0] = s->current_picture.motion_val[1][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 1, s->quarter_sample); s->mv[1][2][1] = s->current_picture.motion_val[1][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 1, s->quarter_sample); for (i = 1; i < 4; i += 2) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][i-1][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][i-1][1]; s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][i-1][0]; s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][i-1][1]; } } else { for (i = 1; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][0][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][0][1]; s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][0][0]; s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][0][1]; } } } if (!direct) { if (skipped || !s->mb_intra) { bmvtype = decode012(gb); switch (bmvtype) { case 0: bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD; break; case 1: bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD; break; case 2: bmvtype = BMV_TYPE_INTERPOLATED; } } if (twomv && bmvtype != BMV_TYPE_INTERPOLATED) mvsw = get_bits1(gb); } if (!skipped) { // inter MB mb_has_coeffs = ff_vc1_mbmode_intfrp[0][idx_mbmode][3]; if (mb_has_coeffs) cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2); if (!direct) { if (bmvtype == BMV_TYPE_INTERPOLATED && twomv) { v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1); } else if (bmvtype == BMV_TYPE_INTERPOLATED || twomv) { v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1); } } for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0; fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[0][idx_mbmode][1]; /* for all motion vector read MVDATA and motion compensate each block */ dst_idx = 0; if (direct) { if (twomv) { for (i = 0; i < 4; i++) { ff_vc1_mc_4mv_luma(v, i, 0, 0); ff_vc1_mc_4mv_luma(v, i, 1, 1); } ff_vc1_mc_4mv_chroma4(v, 0, 0, 0); ff_vc1_mc_4mv_chroma4(v, 1, 1, 1); } else { ff_vc1_mc_1mv(v, 0); ff_vc1_interp_mc(v); } } else if (twomv && bmvtype == BMV_TYPE_INTERPOLATED) { mvbp = v->fourmvbp; for (i = 0; i < 4; i++) { dir = i==1 || i==3; dmv_x = dmv_y = 0; val = ((mvbp >> (3 - i)) & 1); if (val) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); j = i > 1 ? 2 : 0; ff_vc1_pred_mv_intfr(v, j, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir); ff_vc1_mc_4mv_luma(v, j, dir, dir); ff_vc1_mc_4mv_luma(v, j+1, dir, dir); } ff_vc1_mc_4mv_chroma4(v, 0, 0, 0); ff_vc1_mc_4mv_chroma4(v, 1, 1, 1); } else if (bmvtype == BMV_TYPE_INTERPOLATED) { mvbp = v->twomvbp; dmv_x = dmv_y = 0; if (mvbp & 2) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_mc_1mv(v, 0); dmv_x = dmv_y = 0; if (mvbp & 1) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 1); ff_vc1_interp_mc(v); } else if (twomv) { dir = bmvtype == BMV_TYPE_BACKWARD; dir2 = dir; if (mvsw) dir2 = !dir; mvbp = v->twomvbp; dmv_x = dmv_y = 0; if (mvbp & 2) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir); dmv_x = dmv_y = 0; if (mvbp & 1) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir2); if (mvsw) { for (i = 0; i < 2; i++) { s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0]; s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1]; s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0]; s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1]; } } else { ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir); ff_vc1_pred_mv_intfr(v, 2, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir); } ff_vc1_mc_4mv_luma(v, 0, dir, 0); ff_vc1_mc_4mv_luma(v, 1, dir, 0); ff_vc1_mc_4mv_luma(v, 2, dir2, 0); ff_vc1_mc_4mv_luma(v, 3, dir2, 0); ff_vc1_mc_4mv_chroma4(v, dir, dir2, 0); } else { dir = bmvtype == BMV_TYPE_BACKWARD; mvbp = ff_vc1_mbmode_intfrp[0][idx_mbmode][2]; dmv_x = dmv_y = 0; if (mvbp) get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0); ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], dir); v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir); for (i = 0; i < 2; i++) { s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0]; s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1]; } ff_vc1_mc_1mv(v, dir); } if (cbp) GET_MQUANT(); // p. 227 s->current_picture.qscale_table[mb_pos] = mquant; if (!v->ttmbf && cbp) ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2); for (i = 0; i < 6; i++) { s->dc_val[0][s->block_index[i]] = 0; dst_idx += i >> 2; val = ((cbp >> (5 - i)) & 1); if (!fieldtx) off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize); else off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize)); if (val) { pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : (s->linesize << fieldtx), CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt); block_cbp |= pat << (i << 2); if (!v->ttmbf && ttmb < 8) ttmb = -1; first_block = 0; } } } else { // skipped dir = 0; for (i = 0; i < 6; i++) { v->mb_type[0][s->block_index[i]] = 0; s->dc_val[0][s->block_index[i]] = 0; } s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP; s->current_picture.qscale_table[mb_pos] = 0; v->blk_mv_type[s->block_index[0]] = 0; v->blk_mv_type[s->block_index[1]] = 0; v->blk_mv_type[s->block_index[2]] = 0; v->blk_mv_type[s->block_index[3]] = 0; if (!direct) { if (bmvtype == BMV_TYPE_INTERPOLATED) { ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0); ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 1); } else { dir = bmvtype == BMV_TYPE_BACKWARD; ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], dir); if (mvsw) { int dir2 = dir; if (mvsw) dir2 = !dir; for (i = 0; i < 2; i++) { s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0]; s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1]; s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0]; s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1]; } } else { v->blk_mv_type[s->block_index[0]] = 1; v->blk_mv_type[s->block_index[1]] = 1; v->blk_mv_type[s->block_index[2]] = 1; v->blk_mv_type[s->block_index[3]] = 1; ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir); for (i = 0; i < 2; i++) { s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0]; s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1]; } } } } ff_vc1_mc_1mv(v, dir); if (direct || bmvtype == BMV_TYPE_INTERPOLATED) { ff_vc1_interp_mc(v); } v->fieldtx_plane[mb_pos] = 0; } } v->cbp[s->mb_x] = block_cbp; v->ttblk[s->mb_x] = block_tt; return 0; } /** Decode blocks of I-frame */ static void vc1_decode_i_blocks(VC1Context *v) { int k, j; MpegEncContext *s = &v->s; int cbp, val; uint8_t *coded_val; int mb_pos; /* select coding mode used for VLC tables selection */ switch (v->y_ac_table_index) { case 0: v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA; break; case 1: v->codingset = CS_HIGH_MOT_INTRA; break; case 2: v->codingset = CS_MID_RATE_INTRA; break; } switch (v->c_ac_table_index) { case 0: v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER; break; case 1: v->codingset2 = CS_HIGH_MOT_INTER; break; case 2: v->codingset2 = CS_MID_RATE_INTER; break; } /* Set DC scale - y and c use the same */ s->y_dc_scale = s->y_dc_scale_table[v->pq]; s->c_dc_scale = s->c_dc_scale_table[v->pq]; //do frame decode s->mb_x = s->mb_y = 0; s->mb_intra = 1; s->first_slice_line = 1; for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) { s->mb_x = 0; init_block_index(v); for (; s->mb_x < v->end_mb_x; s->mb_x++) { ff_update_block_index(s); s->bdsp.clear_blocks(v->block[v->cur_blk_idx][0]); mb_pos = s->mb_x + s->mb_y * s->mb_width; s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA; s->current_picture.qscale_table[mb_pos] = v->pq; for (int i = 0; i < 4; i++) { s->current_picture.motion_val[1][s->block_index[i]][0] = 0; s->current_picture.motion_val[1][s->block_index[i]][1] = 0; } // do actual MB decoding and displaying cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2); v->s.ac_pred = get_bits1(&v->s.gb); for (k = 0; k < 6; k++) { v->mb_type[0][s->block_index[k]] = 1; val = ((cbp >> (5 - k)) & 1); if (k < 4) { int pred = vc1_coded_block_pred(&v->s, k, &coded_val); val = val ^ pred; *coded_val = val; } cbp |= val << (5 - k); vc1_decode_i_block(v, v->block[v->cur_blk_idx][block_map[k]], k, val, (k < 4) ? v->codingset : v->codingset2); if (CONFIG_GRAY && k > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[k]]); } if (v->overlap && v->pq >= 9) { ff_vc1_i_overlap_filter(v); if (v->rangeredfrm) for (k = 0; k < 6; k++) for (j = 0; j < 64; j++) v->block[v->cur_blk_idx][block_map[k]][j] <<= 1; vc1_put_blocks_clamped(v, 1); } else { if (v->rangeredfrm) for (k = 0; k < 6; k++) for (j = 0; j < 64; j++) v->block[v->cur_blk_idx][block_map[k]][j] = (v->block[v->cur_blk_idx][block_map[k]][j] - 64) << 1; vc1_put_blocks_clamped(v, 0); } if (v->s.loop_filter) ff_vc1_i_loop_filter(v); if (get_bits_count(&s->gb) > v->bits) { ff_er_add_slice(&s->er, 0, 0, s->mb_x, s->mb_y, ER_MB_ERROR); av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits); return; } v->topleft_blk_idx = (v->topleft_blk_idx + 1) % (v->end_mb_x + 2); v->top_blk_idx = (v->top_blk_idx + 1) % (v->end_mb_x + 2); v->left_blk_idx = (v->left_blk_idx + 1) % (v->end_mb_x + 2); v->cur_blk_idx = (v->cur_blk_idx + 1) % (v->end_mb_x + 2); } if (!v->s.loop_filter) ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16); else if (s->mb_y) ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16); s->first_slice_line = 0; } if (v->s.loop_filter) ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16); /* This is intentionally mb_height and not end_mb_y - unlike in advanced * profile, these only differ are when decoding MSS2 rectangles. */ ff_er_add_slice(&s->er, 0, 0, s->mb_width - 1, s->mb_height - 1, ER_MB_END); } /** Decode blocks of I-frame for advanced profile */ static void vc1_decode_i_blocks_adv(VC1Context *v) { int k; MpegEncContext *s = &v->s; int cbp, val; uint8_t *coded_val; int mb_pos; int mquant; int mqdiff; GetBitContext *gb = &s->gb; /* select coding mode used for VLC tables selection */ switch (v->y_ac_table_index) { case 0: v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA; break; case 1: v->codingset = CS_HIGH_MOT_INTRA; break; case 2: v->codingset = CS_MID_RATE_INTRA; break; } switch (v->c_ac_table_index) { case 0: v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER; break; case 1: v->codingset2 = CS_HIGH_MOT_INTER; break; case 2: v->codingset2 = CS_MID_RATE_INTER; break; } // do frame decode s->mb_x = s->mb_y = 0; s->mb_intra = 1; s->first_slice_line = 1; s->mb_y = s->start_mb_y; if (s->start_mb_y) { s->mb_x = 0; init_block_index(v); memset(&s->coded_block[s->block_index[0] - s->b8_stride], 0, (1 + s->b8_stride) * sizeof(*s->coded_block)); } for (; s->mb_y < s->end_mb_y; s->mb_y++) { s->mb_x = 0; init_block_index(v); for (;s->mb_x < s->mb_width; s->mb_x++) { mquant = v->pq; ff_update_block_index(s); s->bdsp.clear_blocks(v->block[v->cur_blk_idx][0]); mb_pos = s->mb_x + s->mb_y * s->mb_stride; s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA; for (int i = 0; i < 4; i++) { s->current_picture.motion_val[1][s->block_index[i] + v->blocks_off][0] = 0; s->current_picture.motion_val[1][s->block_index[i] + v->blocks_off][1] = 0; } // do actual MB decoding and displaying if (v->fieldtx_is_raw) v->fieldtx_plane[mb_pos] = get_bits1(&v->s.gb); cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2); if (v->acpred_is_raw) v->s.ac_pred = get_bits1(&v->s.gb); else v->s.ac_pred = v->acpred_plane[mb_pos]; if (v->condover == CONDOVER_SELECT && v->overflg_is_raw) v->over_flags_plane[mb_pos] = get_bits1(&v->s.gb); GET_MQUANT(); s->current_picture.qscale_table[mb_pos] = mquant; /* Set DC scale - y and c use the same */ s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)]; s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)]; for (k = 0; k < 6; k++) { v->mb_type[0][s->block_index[k]] = 1; val = ((cbp >> (5 - k)) & 1); if (k < 4) { int pred = vc1_coded_block_pred(&v->s, k, &coded_val); val = val ^ pred; *coded_val = val; } cbp |= val << (5 - k); v->a_avail = !s->first_slice_line || (k == 2 || k == 3); v->c_avail = !!s->mb_x || (k == 1 || k == 3); vc1_decode_i_block_adv(v, v->block[v->cur_blk_idx][block_map[k]], k, val, (k < 4) ? v->codingset : v->codingset2, mquant); if (CONFIG_GRAY && k > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY)) continue; v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[k]]); } if (v->overlap && (v->pq >= 9 || v->condover != CONDOVER_NONE)) ff_vc1_i_overlap_filter(v); vc1_put_blocks_clamped(v, 1); if (v->s.loop_filter) ff_vc1_i_loop_filter(v); if (get_bits_count(&s->gb) > v->bits) { // TODO: may need modification to handle slice coding ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR); av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits); return; } inc_blk_idx(v->topleft_blk_idx); inc_blk_idx(v->top_blk_idx); inc_blk_idx(v->left_blk_idx); inc_blk_idx(v->cur_blk_idx); } if (!v->s.loop_filter) ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16); else if (s->mb_y) ff_mpeg_draw_horiz_band(s, (s->mb_y-1) * 16, 16); s->first_slice_line = 0; } if (v->s.loop_filter) ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16); ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1, (s->end_mb_y << v->field_mode) - 1, ER_MB_END); } static void vc1_decode_p_blocks(VC1Context *v) { MpegEncContext *s = &v->s; int apply_loop_filter; /* select coding mode used for VLC tables selection */ switch (v->c_ac_table_index) { case 0: v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA; break; case 1: v->codingset = CS_HIGH_MOT_INTRA; break; case 2: v->codingset = CS_MID_RATE_INTRA; break; } switch (v->c_ac_table_index) { case 0: v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER; break; case 1: v->codingset2 = CS_HIGH_MOT_INTER; break; case 2: v->codingset2 = CS_MID_RATE_INTER; break; } apply_loop_filter = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY); s->first_slice_line = 1; memset(v->cbp_base, 0, sizeof(v->cbp_base[0]) * 3 * s->mb_stride); for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) { s->mb_x = 0; init_block_index(v); for (; s->mb_x < s->mb_width; s->mb_x++) { ff_update_block_index(s); if (v->fcm == ILACE_FIELD) { vc1_decode_p_mb_intfi(v); if (apply_loop_filter) ff_vc1_p_loop_filter(v); } else if (v->fcm == ILACE_FRAME) { vc1_decode_p_mb_intfr(v); if (apply_loop_filter) ff_vc1_p_intfr_loop_filter(v); } else { vc1_decode_p_mb(v); if (apply_loop_filter) ff_vc1_p_loop_filter(v); } if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) { // TODO: may need modification to handle slice coding ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR); av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n", get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y); return; } inc_blk_idx(v->topleft_blk_idx); inc_blk_idx(v->top_blk_idx); inc_blk_idx(v->left_blk_idx); inc_blk_idx(v->cur_blk_idx); } memmove(v->cbp_base, v->cbp - s->mb_stride, sizeof(v->cbp_base[0]) * 2 * s->mb_stride); memmove(v->ttblk_base, v->ttblk - s->mb_stride, sizeof(v->ttblk_base[0]) * 2 * s->mb_stride); memmove(v->is_intra_base, v->is_intra - s->mb_stride, sizeof(v->is_intra_base[0]) * 2 * s->mb_stride); memmove(v->luma_mv_base, v->luma_mv - s->mb_stride, sizeof(v->luma_mv_base[0]) * 2 * s->mb_stride); if (s->mb_y != s->start_mb_y) ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16); s->first_slice_line = 0; } if (s->end_mb_y >= s->start_mb_y) ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16); ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1, (s->end_mb_y << v->field_mode) - 1, ER_MB_END); } static void vc1_decode_b_blocks(VC1Context *v) { MpegEncContext *s = &v->s; /* select coding mode used for VLC tables selection */ switch (v->c_ac_table_index) { case 0: v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA; break; case 1: v->codingset = CS_HIGH_MOT_INTRA; break; case 2: v->codingset = CS_MID_RATE_INTRA; break; } switch (v->c_ac_table_index) { case 0: v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER; break; case 1: v->codingset2 = CS_HIGH_MOT_INTER; break; case 2: v->codingset2 = CS_MID_RATE_INTER; break; } s->first_slice_line = 1; for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) { s->mb_x = 0; init_block_index(v); for (; s->mb_x < s->mb_width; s->mb_x++) { ff_update_block_index(s); if (v->fcm == ILACE_FIELD) { vc1_decode_b_mb_intfi(v); if (v->s.loop_filter) ff_vc1_b_intfi_loop_filter(v); } else if (v->fcm == ILACE_FRAME) { vc1_decode_b_mb_intfr(v); if (v->s.loop_filter) ff_vc1_p_intfr_loop_filter(v); } else { vc1_decode_b_mb(v); if (v->s.loop_filter) ff_vc1_i_loop_filter(v); } if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) { // TODO: may need modification to handle slice coding ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR); av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n", get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y); return; } } memmove(v->cbp_base, v->cbp - s->mb_stride, sizeof(v->cbp_base[0]) * 2 * s->mb_stride); memmove(v->ttblk_base, v->ttblk - s->mb_stride, sizeof(v->ttblk_base[0]) * 2 * s->mb_stride); memmove(v->is_intra_base, v->is_intra - s->mb_stride, sizeof(v->is_intra_base[0]) * 2 * s->mb_stride); if (!v->s.loop_filter) ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16); else if (s->mb_y) ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16); s->first_slice_line = 0; } if (v->s.loop_filter) ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16); ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1, (s->end_mb_y << v->field_mode) - 1, ER_MB_END); } static void vc1_decode_skip_blocks(VC1Context *v) { MpegEncContext *s = &v->s; if (!v->s.last_picture.f->data[0]) return; ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_width - 1, s->end_mb_y - 1, ER_MB_END); s->first_slice_line = 1; for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) { s->mb_x = 0; init_block_index(v); ff_update_block_index(s); memcpy(s->dest[0], s->last_picture.f->data[0] + s->mb_y * 16 * s->linesize, s->linesize * 16); memcpy(s->dest[1], s->last_picture.f->data[1] + s->mb_y * 8 * s->uvlinesize, s->uvlinesize * 8); memcpy(s->dest[2], s->last_picture.f->data[2] + s->mb_y * 8 * s->uvlinesize, s->uvlinesize * 8); ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16); s->first_slice_line = 0; } s->pict_type = AV_PICTURE_TYPE_P; } void ff_vc1_decode_blocks(VC1Context *v) { v->s.esc3_level_length = 0; if (v->x8_type) { ff_intrax8_decode_picture(&v->x8, &v->s.current_picture, &v->s.gb, &v->s.mb_x, &v->s.mb_y, 2 * v->pq + v->halfpq, v->pq * !v->pquantizer, v->s.loop_filter, v->s.low_delay); ff_er_add_slice(&v->s.er, 0, 0, (v->s.mb_x >> 1) - 1, (v->s.mb_y >> 1) - 1, ER_MB_END); } else { v->cur_blk_idx = 0; v->left_blk_idx = -1; v->topleft_blk_idx = 1; v->top_blk_idx = 2; switch (v->s.pict_type) { case AV_PICTURE_TYPE_I: if (v->profile == PROFILE_ADVANCED) vc1_decode_i_blocks_adv(v); else vc1_decode_i_blocks(v); break; case AV_PICTURE_TYPE_P: if (v->p_frame_skipped) vc1_decode_skip_blocks(v); else vc1_decode_p_blocks(v); break; case AV_PICTURE_TYPE_B: if (v->bi_type) { if (v->profile == PROFILE_ADVANCED) vc1_decode_i_blocks_adv(v); else vc1_decode_i_blocks(v); } else vc1_decode_b_blocks(v); break; } } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_220_0
crossvul-cpp_data_bad_2747_0
/* * Copyright (c) 1998-2007 The TCPDUMP project * Copyright (c) 2009 Florian Forster * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler <hannes@gredler.at> * IPv6 additions by Florian Forster <octo at verplant.org> */ /* \summary: Optimized Link State Routing Protocol (OLSR) printer */ /* specification: RFC 3626 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" /* * RFC 3626 common 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Packet Length | Packet Sequence Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Message Type | Vtime | Message Size | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Originator Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Time To Live | Hop Count | Message Sequence Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * : MESSAGE : * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Message Type | Vtime | Message Size | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Originator Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Time To Live | Hop Count | Message Sequence Number | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * : MESSAGE : * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * : : */ struct olsr_common { uint8_t packet_len[2]; uint8_t packet_seq[2]; }; #define OLSR_HELLO_MSG 1 /* rfc3626 */ #define OLSR_TC_MSG 2 /* rfc3626 */ #define OLSR_MID_MSG 3 /* rfc3626 */ #define OLSR_HNA_MSG 4 /* rfc3626 */ #define OLSR_POWERINFO_MSG 128 #define OLSR_NAMESERVICE_MSG 130 #define OLSR_HELLO_LQ_MSG 201 /* LQ extensions olsr.org */ #define OLSR_TC_LQ_MSG 202 /* LQ extensions olsr.org */ static const struct tok olsr_msg_values[] = { { OLSR_HELLO_MSG, "Hello" }, { OLSR_TC_MSG, "TC" }, { OLSR_MID_MSG, "MID" }, { OLSR_HNA_MSG, "HNA" }, { OLSR_POWERINFO_MSG, "Powerinfo" }, { OLSR_NAMESERVICE_MSG, "Nameservice" }, { OLSR_HELLO_LQ_MSG, "Hello-LQ" }, { OLSR_TC_LQ_MSG, "TC-LQ" }, { 0, NULL} }; struct olsr_msg4 { uint8_t msg_type; uint8_t vtime; uint8_t msg_len[2]; uint8_t originator[4]; uint8_t ttl; uint8_t hopcount; uint8_t msg_seq[2]; }; struct olsr_msg6 { uint8_t msg_type; uint8_t vtime; uint8_t msg_len[2]; uint8_t originator[16]; uint8_t ttl; uint8_t hopcount; uint8_t msg_seq[2]; }; struct olsr_hello { uint8_t res[2]; uint8_t htime; uint8_t will; }; struct olsr_hello_link { uint8_t link_code; uint8_t res; uint8_t len[2]; }; struct olsr_tc { uint8_t ans_seq[2]; uint8_t res[2]; }; struct olsr_hna4 { uint8_t network[4]; uint8_t mask[4]; }; struct olsr_hna6 { uint8_t network[16]; uint8_t mask[16]; }; /** gateway HNA flags */ enum gateway_hna_flags { GW_HNA_FLAG_LINKSPEED = 1 << 0, GW_HNA_FLAG_IPV4 = 1 << 1, GW_HNA_FLAG_IPV4_NAT = 1 << 2, GW_HNA_FLAG_IPV6 = 1 << 3, GW_HNA_FLAG_IPV6PREFIX = 1 << 4 }; /** gateway HNA field byte offsets in the netmask field of the HNA */ enum gateway_hna_fields { GW_HNA_PAD = 0, GW_HNA_FLAGS = 1, GW_HNA_UPLINK = 2, GW_HNA_DOWNLINK = 3, GW_HNA_V6PREFIXLEN = 4, GW_HNA_V6PREFIX = 5 }; #define OLSR_EXTRACT_LINK_TYPE(link_code) (link_code & 0x3) #define OLSR_EXTRACT_NEIGHBOR_TYPE(link_code) (link_code >> 2) static const struct tok olsr_link_type_values[] = { { 0, "Unspecified" }, { 1, "Asymmetric" }, { 2, "Symmetric" }, { 3, "Lost" }, { 0, NULL} }; static const struct tok olsr_neighbor_type_values[] = { { 0, "Not-Neighbor" }, { 1, "Symmetric" }, { 2, "Symmetric-MPR" }, { 0, NULL} }; struct olsr_lq_neighbor4 { uint8_t neighbor[4]; uint8_t link_quality; uint8_t neighbor_link_quality; uint8_t res[2]; }; struct olsr_lq_neighbor6 { uint8_t neighbor[16]; uint8_t link_quality; uint8_t neighbor_link_quality; uint8_t res[2]; }; #define MAX_SMARTGW_SPEED 320000000 /** * Convert an encoded 1 byte transport value (5 bits mantissa, 3 bits exponent) * to an uplink/downlink speed value * * @param value the encoded 1 byte transport value * @return the uplink/downlink speed value (in kbit/s) */ static uint32_t deserialize_gw_speed(uint8_t value) { uint32_t speed; uint32_t exp; if (!value) { return 0; } if (value == UINT8_MAX) { /* maximum value: also return maximum value */ return MAX_SMARTGW_SPEED; } speed = (value >> 3) + 1; exp = value & 7; while (exp-- > 0) { speed *= 10; } return speed; } /* * macro to convert the 8-bit mantissa/exponent to a double float * taken from olsr.org. */ #define VTIME_SCALE_FACTOR 0.0625 #define ME_TO_DOUBLE(me) \ (double)(VTIME_SCALE_FACTOR*(1+(double)(me>>4)/16)*(double)(1<<(me&0x0F))) /* * print a neighbor list with LQ extensions. */ static int olsr_print_lq_neighbor4(netdissect_options *ndo, const u_char *msg_data, u_int hello_len) { const struct olsr_lq_neighbor4 *lq_neighbor; while (hello_len >= sizeof(struct olsr_lq_neighbor4)) { lq_neighbor = (const struct olsr_lq_neighbor4 *)msg_data; if (!ND_TTEST(*lq_neighbor)) return (-1); ND_PRINT((ndo, "\n\t neighbor %s, link-quality %.2f%%" ", neighbor-link-quality %.2f%%", ipaddr_string(ndo, lq_neighbor->neighbor), ((double)lq_neighbor->link_quality/2.55), ((double)lq_neighbor->neighbor_link_quality/2.55))); msg_data += sizeof(struct olsr_lq_neighbor4); hello_len -= sizeof(struct olsr_lq_neighbor4); } return (0); } static int olsr_print_lq_neighbor6(netdissect_options *ndo, const u_char *msg_data, u_int hello_len) { const struct olsr_lq_neighbor6 *lq_neighbor; while (hello_len >= sizeof(struct olsr_lq_neighbor6)) { lq_neighbor = (const struct olsr_lq_neighbor6 *)msg_data; if (!ND_TTEST(*lq_neighbor)) return (-1); ND_PRINT((ndo, "\n\t neighbor %s, link-quality %.2f%%" ", neighbor-link-quality %.2f%%", ip6addr_string(ndo, lq_neighbor->neighbor), ((double)lq_neighbor->link_quality/2.55), ((double)lq_neighbor->neighbor_link_quality/2.55))); msg_data += sizeof(struct olsr_lq_neighbor6); hello_len -= sizeof(struct olsr_lq_neighbor6); } return (0); } /* * print a neighbor list. */ static int olsr_print_neighbor(netdissect_options *ndo, const u_char *msg_data, u_int hello_len) { int neighbor; ND_PRINT((ndo, "\n\t neighbor\n\t\t")); neighbor = 1; while (hello_len >= sizeof(struct in_addr)) { if (!ND_TTEST2(*msg_data, sizeof(struct in_addr))) return (-1); /* print 4 neighbors per line */ ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, msg_data), neighbor % 4 == 0 ? "\n\t\t" : " ")); msg_data += sizeof(struct in_addr); hello_len -= sizeof(struct in_addr); } return (0); } void olsr_print(netdissect_options *ndo, const u_char *pptr, u_int length, int is_ipv6) { union { const struct olsr_common *common; const struct olsr_msg4 *msg4; const struct olsr_msg6 *msg6; const struct olsr_hello *hello; const struct olsr_hello_link *hello_link; const struct olsr_tc *tc; const struct olsr_hna4 *hna; } ptr; u_int msg_type, msg_len, msg_tlen, hello_len; uint16_t name_entry_type, name_entry_len; u_int name_entry_padding; uint8_t link_type, neighbor_type; const u_char *tptr, *msg_data; tptr = pptr; if (length < sizeof(struct olsr_common)) { goto trunc; } ND_TCHECK2(*tptr, sizeof(struct olsr_common)); ptr.common = (const struct olsr_common *)tptr; length = min(length, EXTRACT_16BITS(ptr.common->packet_len)); ND_PRINT((ndo, "OLSRv%i, seq 0x%04x, length %u", (is_ipv6 == 0) ? 4 : 6, EXTRACT_16BITS(ptr.common->packet_seq), length)); tptr += sizeof(struct olsr_common); /* * In non-verbose mode, just print version. */ if (ndo->ndo_vflag < 1) { return; } while (tptr < (pptr+length)) { union { const struct olsr_msg4 *v4; const struct olsr_msg6 *v6; } msgptr; int msg_len_valid = 0; ND_TCHECK2(*tptr, sizeof(struct olsr_msg4)); if (is_ipv6) { msgptr.v6 = (const struct olsr_msg6 *) tptr; msg_type = msgptr.v6->msg_type; msg_len = EXTRACT_16BITS(msgptr.v6->msg_len); if ((msg_len >= sizeof (struct olsr_msg6)) && (msg_len <= length)) msg_len_valid = 1; /* infinite loop check */ if (msg_type == 0 || msg_len == 0) { return; } ND_PRINT((ndo, "\n\t%s Message (%#04x), originator %s, ttl %u, hop %u" "\n\t vtime %.3fs, msg-seq 0x%04x, length %u%s", tok2str(olsr_msg_values, "Unknown", msg_type), msg_type, ip6addr_string(ndo, msgptr.v6->originator), msgptr.v6->ttl, msgptr.v6->hopcount, ME_TO_DOUBLE(msgptr.v6->vtime), EXTRACT_16BITS(msgptr.v6->msg_seq), msg_len, (msg_len_valid == 0) ? " (invalid)" : "")); if (!msg_len_valid) { return; } msg_tlen = msg_len - sizeof(struct olsr_msg6); msg_data = tptr + sizeof(struct olsr_msg6); } else /* (!is_ipv6) */ { msgptr.v4 = (const struct olsr_msg4 *) tptr; msg_type = msgptr.v4->msg_type; msg_len = EXTRACT_16BITS(msgptr.v4->msg_len); if ((msg_len >= sizeof (struct olsr_msg4)) && (msg_len <= length)) msg_len_valid = 1; /* infinite loop check */ if (msg_type == 0 || msg_len == 0) { return; } ND_PRINT((ndo, "\n\t%s Message (%#04x), originator %s, ttl %u, hop %u" "\n\t vtime %.3fs, msg-seq 0x%04x, length %u%s", tok2str(olsr_msg_values, "Unknown", msg_type), msg_type, ipaddr_string(ndo, msgptr.v4->originator), msgptr.v4->ttl, msgptr.v4->hopcount, ME_TO_DOUBLE(msgptr.v4->vtime), EXTRACT_16BITS(msgptr.v4->msg_seq), msg_len, (msg_len_valid == 0) ? " (invalid)" : "")); if (!msg_len_valid) { return; } msg_tlen = msg_len - sizeof(struct olsr_msg4); msg_data = tptr + sizeof(struct olsr_msg4); } switch (msg_type) { case OLSR_HELLO_MSG: case OLSR_HELLO_LQ_MSG: if (msg_tlen < sizeof(struct olsr_hello)) goto trunc; ND_TCHECK2(*msg_data, sizeof(struct olsr_hello)); ptr.hello = (const struct olsr_hello *)msg_data; ND_PRINT((ndo, "\n\t hello-time %.3fs, MPR willingness %u", ME_TO_DOUBLE(ptr.hello->htime), ptr.hello->will)); msg_data += sizeof(struct olsr_hello); msg_tlen -= sizeof(struct olsr_hello); while (msg_tlen >= sizeof(struct olsr_hello_link)) { int hello_len_valid = 0; /* * link-type. */ ND_TCHECK2(*msg_data, sizeof(struct olsr_hello_link)); ptr.hello_link = (const struct olsr_hello_link *)msg_data; hello_len = EXTRACT_16BITS(ptr.hello_link->len); link_type = OLSR_EXTRACT_LINK_TYPE(ptr.hello_link->link_code); neighbor_type = OLSR_EXTRACT_NEIGHBOR_TYPE(ptr.hello_link->link_code); if ((hello_len <= msg_tlen) && (hello_len >= sizeof(struct olsr_hello_link))) hello_len_valid = 1; ND_PRINT((ndo, "\n\t link-type %s, neighbor-type %s, len %u%s", tok2str(olsr_link_type_values, "Unknown", link_type), tok2str(olsr_neighbor_type_values, "Unknown", neighbor_type), hello_len, (hello_len_valid == 0) ? " (invalid)" : "")); if (hello_len_valid == 0) break; msg_data += sizeof(struct olsr_hello_link); msg_tlen -= sizeof(struct olsr_hello_link); hello_len -= sizeof(struct olsr_hello_link); ND_TCHECK2(*msg_data, hello_len); if (msg_type == OLSR_HELLO_MSG) { if (olsr_print_neighbor(ndo, msg_data, hello_len) == -1) goto trunc; } else { if (is_ipv6) { if (olsr_print_lq_neighbor6(ndo, msg_data, hello_len) == -1) goto trunc; } else { if (olsr_print_lq_neighbor4(ndo, msg_data, hello_len) == -1) goto trunc; } } msg_data += hello_len; msg_tlen -= hello_len; } break; case OLSR_TC_MSG: case OLSR_TC_LQ_MSG: if (msg_tlen < sizeof(struct olsr_tc)) goto trunc; ND_TCHECK2(*msg_data, sizeof(struct olsr_tc)); ptr.tc = (const struct olsr_tc *)msg_data; ND_PRINT((ndo, "\n\t advertised neighbor seq 0x%04x", EXTRACT_16BITS(ptr.tc->ans_seq))); msg_data += sizeof(struct olsr_tc); msg_tlen -= sizeof(struct olsr_tc); if (msg_type == OLSR_TC_MSG) { if (olsr_print_neighbor(ndo, msg_data, msg_tlen) == -1) goto trunc; } else { if (is_ipv6) { if (olsr_print_lq_neighbor6(ndo, msg_data, msg_tlen) == -1) goto trunc; } else { if (olsr_print_lq_neighbor4(ndo, msg_data, msg_tlen) == -1) goto trunc; } } break; case OLSR_MID_MSG: { size_t addr_size = sizeof(struct in_addr); if (is_ipv6) addr_size = sizeof(struct in6_addr); while (msg_tlen >= addr_size) { ND_TCHECK2(*msg_data, addr_size); ND_PRINT((ndo, "\n\t interface address %s", is_ipv6 ? ip6addr_string(ndo, msg_data) : ipaddr_string(ndo, msg_data))); msg_data += addr_size; msg_tlen -= addr_size; } break; } case OLSR_HNA_MSG: if (is_ipv6) { int i = 0; ND_PRINT((ndo, "\n\t Advertised networks (total %u)", (unsigned int) (msg_tlen / sizeof(struct olsr_hna6)))); while (msg_tlen >= sizeof(struct olsr_hna6)) { const struct olsr_hna6 *hna6; ND_TCHECK2(*msg_data, sizeof(struct olsr_hna6)); hna6 = (const struct olsr_hna6 *)msg_data; ND_PRINT((ndo, "\n\t #%i: %s/%u", i, ip6addr_string(ndo, hna6->network), mask62plen (hna6->mask))); msg_data += sizeof(struct olsr_hna6); msg_tlen -= sizeof(struct olsr_hna6); } } else { int col = 0; ND_PRINT((ndo, "\n\t Advertised networks (total %u)", (unsigned int) (msg_tlen / sizeof(struct olsr_hna4)))); while (msg_tlen >= sizeof(struct olsr_hna4)) { ND_TCHECK2(*msg_data, sizeof(struct olsr_hna4)); ptr.hna = (const struct olsr_hna4 *)msg_data; /* print 4 prefixes per line */ if (!ptr.hna->network[0] && !ptr.hna->network[1] && !ptr.hna->network[2] && !ptr.hna->network[3] && !ptr.hna->mask[GW_HNA_PAD] && ptr.hna->mask[GW_HNA_FLAGS]) { /* smart gateway */ ND_PRINT((ndo, "%sSmart-Gateway:%s%s%s%s%s %u/%u", col == 0 ? "\n\t " : ", ", /* indent */ /* sgw */ /* LINKSPEED */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? " LINKSPEED" : "", /* IPV4 */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV4) ? " IPV4" : "", /* IPV4-NAT */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV4_NAT) ? " IPV4-NAT" : "", /* IPV6 */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV6) ? " IPV6" : "", /* IPv6PREFIX */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_IPV6PREFIX) ? " IPv6-PREFIX" : "", /* uplink */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? deserialize_gw_speed(ptr.hna->mask[GW_HNA_UPLINK]) : 0, /* downlink */ (ptr.hna->mask[GW_HNA_FLAGS] & GW_HNA_FLAG_LINKSPEED) ? deserialize_gw_speed(ptr.hna->mask[GW_HNA_DOWNLINK]) : 0 )); } else { /* normal route */ ND_PRINT((ndo, "%s%s/%u", col == 0 ? "\n\t " : ", ", ipaddr_string(ndo, ptr.hna->network), mask2plen(EXTRACT_32BITS(ptr.hna->mask)))); } msg_data += sizeof(struct olsr_hna4); msg_tlen -= sizeof(struct olsr_hna4); col = (col + 1) % 4; } } break; case OLSR_NAMESERVICE_MSG: { u_int name_entries = EXTRACT_16BITS(msg_data+2); u_int addr_size = 4; int name_entries_valid = 0; u_int i; if (is_ipv6) addr_size = 16; if ((name_entries > 0) && ((name_entries * (4 + addr_size)) <= msg_tlen)) name_entries_valid = 1; if (msg_tlen < 4) goto trunc; ND_TCHECK2(*msg_data, 4); ND_PRINT((ndo, "\n\t Version %u, Entries %u%s", EXTRACT_16BITS(msg_data), name_entries, (name_entries_valid == 0) ? " (invalid)" : "")); if (name_entries_valid == 0) break; msg_data += 4; msg_tlen -= 4; for (i = 0; i < name_entries; i++) { int name_entry_len_valid = 0; if (msg_tlen < 4) break; ND_TCHECK2(*msg_data, 4); name_entry_type = EXTRACT_16BITS(msg_data); name_entry_len = EXTRACT_16BITS(msg_data+2); msg_data += 4; msg_tlen -= 4; if ((name_entry_len > 0) && ((addr_size + name_entry_len) <= msg_tlen)) name_entry_len_valid = 1; ND_PRINT((ndo, "\n\t #%u: type %#06x, length %u%s", (unsigned int) i, name_entry_type, name_entry_len, (name_entry_len_valid == 0) ? " (invalid)" : "")); if (name_entry_len_valid == 0) break; /* 32-bit alignment */ name_entry_padding = 0; if (name_entry_len%4 != 0) name_entry_padding = 4-(name_entry_len%4); if (msg_tlen < addr_size + name_entry_len + name_entry_padding) goto trunc; ND_TCHECK2(*msg_data, addr_size + name_entry_len + name_entry_padding); if (is_ipv6) ND_PRINT((ndo, ", address %s, name \"", ip6addr_string(ndo, msg_data))); else ND_PRINT((ndo, ", address %s, name \"", ipaddr_string(ndo, msg_data))); (void)fn_printn(ndo, msg_data + addr_size, name_entry_len, NULL); ND_PRINT((ndo, "\"")); msg_data += addr_size + name_entry_len + name_entry_padding; msg_tlen -= addr_size + name_entry_len + name_entry_padding; } /* for (i = 0; i < name_entries; i++) */ break; } /* case OLSR_NAMESERVICE_MSG */ /* * FIXME those are the defined messages that lack a decoder * you are welcome to contribute code ;-) */ case OLSR_POWERINFO_MSG: default: print_unknown_data(ndo, msg_data, "\n\t ", msg_tlen); break; } /* switch (msg_type) */ tptr += msg_len; } /* while (tptr < (pptr+length)) */ return; trunc: ND_PRINT((ndo, "[|olsr]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2747_0
crossvul-cpp_data_good_2804_1
#ifndef IGNOREALL /* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.476 $ $Date: 2015/05/25 02:29:14 $ */ /*@out DEFINES #ifndef USE_JPEG #define NO_JPEG #endif #ifndef USE_JASPER #define NO_JASPER #endif @end DEFINES */ #define NO_LCMS #define DCRAW_VERBOSE //@out DEFINES #define DCRAW_VERSION "9.26" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _USE_MATH_DEFINES #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> //@end DEFINES #if defined(DJGPP) || defined(__MINGW32__) #define fseeko fseek #define ftello ftell #else #define fgetc getc_unlocked #endif //@out DEFINES #ifdef __CYGWIN__ #include <io.h> #endif #if defined WIN32 || defined (__MINGW32__) #include <sys/utime.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define snprintf _snprintf #define strcasecmp stricmp #define strncasecmp strnicmp //@end DEFINES typedef __int64 INT64; typedef unsigned __int64 UINT64; //@out DEFINES #else #include <unistd.h> #include <utime.h> #include <netinet/in.h> typedef long long INT64; typedef unsigned long long UINT64; #endif #ifdef NODEPS #define NO_JASPER #define NO_JPEG #define NO_LCMS #endif #ifndef NO_JASPER #include <jasper/jasper.h> /* Decode Red camera movies */ #endif #ifndef NO_JPEG #include <jpeglib.h> /* Decode compressed Kodak DC120 photos */ #endif /* and Adobe Lossy DNGs */ #ifndef NO_LCMS #ifdef USE_LCMS #include <lcms.h> /* Support color profiles */ #else #include <lcms2.h> /* Support color profiles */ #endif #endif #ifdef LOCALEDIR #include <libintl.h> #define _(String) gettext(String) #else #define _(String) (String) #endif #ifdef LJPEG_DECODE #error Please compile dcraw.c by itself. #error Do not link it with ljpeg_decode. #endif #ifndef LONG_BIT #define LONG_BIT (8 * sizeof (long)) #endif //@end DEFINES #if !defined(uchar) #define uchar unsigned char #endif #if !defined(ushort) #define ushort unsigned short #endif /* All global variables are defined here, and all functions that access them are prefixed with "CLASS". Note that a thread-safe C++ class cannot have non-const static local variables. */ FILE *ifp, *ofp; short order; const char *ifname; char *meta_data, xtrans[6][6], xtrans_abs[6][6]; char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64],software[64]; float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len; time_t timestamp; off_t strip_offset, data_offset; off_t thumb_offset, meta_offset, profile_offset; unsigned shot_order, kodak_cbpp, exif_cfa, unique_id; unsigned thumb_length, meta_length, profile_length; unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0; unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress; unsigned black, maximum, mix_green, raw_color, zero_is_bad; unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error; unsigned tile_width, tile_length, gpsdata[32], load_flags; unsigned flip, tiff_flip, filters, colors; ushort raw_height, raw_width, height, width, top_margin, left_margin; ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height; ushort *raw_image, (*image)[4], cblack[4102]; ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4]; double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 }; float bright=1, user_mul[4]={0,0,0,0}, threshold=0; int mask[8][4]; int half_size=0, four_color_rgb=0, document_mode=0, highlight=0; int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=1; int output_color=1, output_bps=8, output_tiff=0, med_passes=0; int no_auto_bright=0; unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX }; float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4]; const double xyz_rgb[3][3] = { /* XYZ from RGB */ { 0.412453, 0.357580, 0.180423 }, { 0.212671, 0.715160, 0.072169 }, { 0.019334, 0.119193, 0.950227 } }; const float d65_white[3] = { 0.950456, 1, 1.088754 }; int histogram[4][0x2000]; void (*write_thumb)(), (*write_fun)(); void (*load_raw)(), (*thumb_load_raw)(); jmp_buf failure; struct decode { struct decode *branch[2]; int leaf; } first_decode[2048], *second_decode, *free_decode; struct tiff_ifd { int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes; int t_tile_width, t_tile_length,sample_format,predictor; float t_shutter; } tiff_ifd[10]; struct ph1 { int format, key_off, tag_21a; int t_black, split_col, black_col, split_row, black_row; float tag_210; } ph1; #define CLASS //@out DEFINES #define FORC(cnt) for (c=0; c < cnt; c++) #define FORC3 FORC(3) #define FORC4 FORC(4) #define FORCC for (c=0; c < colors && c < 4; c++) #define SQR(x) ((x)*(x)) #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31)) #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y)) #define CLIP(x) LIM((int)(x),0,65535) #define SWAP(a,b) { a=a+b; b=a-b; a=a-b; } #define my_swap(type, i, j) {type t = i; i = j; j = t;} static float fMAX(float a, float b) { return MAX(a,b); } /* In order to inline this calculation, I make the risky assumption that all filter patterns can be described by a repeating pattern of eight rows and two columns Do not use the FC or BAYER macros with the Leaf CatchLight, because its pattern is 16x16, not 2x8. Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2 PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1 0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M 1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C 2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y 3 C Y C Y C Y 3 G M G M G M 3 G M G M G M 4 C Y C Y C Y 4 Y C Y C Y C PowerShot A5 5 G M G M G M 5 G M G M G M 0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y 7 M G M G M G 7 M G M G M G 0 1 2 3 4 5 0 C Y C Y C Y 1 G M G M G M 2 C Y C Y C Y 3 M G M G M G All RGB cameras use one of these Bayer grids: 0x16161616: 0x61616161: 0x49494949: 0x94949494: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G 1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B 2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G 3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B */ #define RAW(row,col) \ raw_image[(row)*raw_width+(col)] //@end DEFINES #define FC(row,col) \ (filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3) //@out DEFINES #define BAYER(row,col) \ image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)] #define BAYER2(row,col) \ image[((row) >> shrink)*iwidth + ((col) >> shrink)][fcol(row,col)] //@end DEFINES /* @out COMMON #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end COMMON */ //@out COMMON int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) //@end COMMON void CLASS merror (void *ptr, const char *where) { if (ptr) return; fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where); longjmp (failure, 1); } void CLASS derror() { if (!data_error) { fprintf (stderr, "%s: ", ifname); if (feof(ifp)) fprintf (stderr,_("Unexpected end of file\n")); else fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp)); } data_error++; } //@out COMMON ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, int count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } //@end COMMON struct jhead { int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6]; ushort quant[64], idct[64], *huff[20], *free[20], *row; }; //@out COMMON int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width*3*tiff_bps/8; if(tiff_bps <= 8) gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } //@end COMMON void CLASS jpeg_thumb(); //@out COMMON void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten=0, isix, i, buffer=0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i=0; i < 16; i+=2) raw_image[todo[i]] = (todo[i+1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row,col) = pred[col & 1]) > 4098 && col < width) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[256]; int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c=0; c < 16; c+=2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) + (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } //@end COMMON /* RESTRICTED code starts here */ void CLASS foveon_decoder (unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i=0; i < size; i++) huff[i] = get4(); memset (first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode+2048) { fprintf (stderr,_("%s: decoder table overflow\n"), ifname); longjmp (failure, 2); } if (code) for (i=0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len+1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder (size, code); cur->branch[1] = free_decode; foveon_decoder (size, code+1); } void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf=0, bit=1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width*3) return; buf = (char *) malloc (bwide); merror (buf, "foveon_thumb()"); for (row=0; row < thumb_height; row++) { fread (buf, 1, bwide, ifp); fwrite (buf, 3, thumb_width, ofp); } free (buf); return; } foveon_decoder (256, 0); for (row=0; row < thumb_height; row++) { memset (pred, 0, sizeof pred); if (!bit) get4(); for (bit=col=0; col < thumb_width; col++) FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc (pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { struct decode *dindex; short diff[1024]; unsigned bitbuf=0; int pred[3], row, col, bit=-1, c, i; read_shorts ((ushort *) diff, 1024); if (!load_flags) foveon_decoder (1024, 0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model+2) < 14) get4(); for (col=bit=0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff]; } else FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row*width+col][c] = pred[c]; } } } void CLASS foveon_huff (ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i=0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j=0; j < 256 >> clen; ) huff[code+ ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek (ifp, 8, SEEK_CUR); foveon_huff (huff); roff[0] = 48; FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek (ifp, data_offset+roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row*width+col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } #ifdef DCRAW_VERBOSE else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); #endif } const char * CLASS foveon_camf_param (const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp (block, pos+sget4(pos+12))) continue; cp = pos + sget4(pos+16); num = sget4(cp); dp = pos + sget4(cp+4); while (num--) { cp += 8; if (!strcmp (param, dp+sget4(cp))) return dp+sget4(cp+4); } } return 0; } void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp (name, pos+sget4(pos+12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos+16); type = sget4(cp); if ((ndim = sget4(cp+4)) > 3) break; dp = pos + sget4(cp+8); for (i=ndim; i--; ) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break; mat = (unsigned *) malloc ((size = dsize) * 4); merror (mat, "foveon_camf_matrix()"); for (i=0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i*4); else mat[i] = sget4(dp + i*2) & 0xffff; return mat; } #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name); #endif return 0; } int CLASS foveon_fixed (void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix (dim, name); if (!dp) return 0; memcpy (ptr, dp, size*4); free (dp); return 1; } float CLASS foveon_avg (short *pix, int range[2], float cfilt) { int i; float val, min=FLT_MAX, max=-FLT_MAX, sum=0; for (i=range[0]; i <= range[1]; i++) { sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum/2; return (sum - min - max) / (range[1] - range[0] - 1); } short * CLASS foveon_make_curve (double max, double mul, double filt) { short *curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4*M_PI*max / filt; if (size == UINT_MAX) size--; curve = (short *) calloc (size+1, sizeof *curve); merror (curve, "foveon_make_curve()"); curve[0] = size; for (i=0; i < size; i++) { x = i*filt/max/4; curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5; } return curve; } void CLASS foveon_make_curves (short **curvep, float dq[3], float div[3], float filt) { double mul[3], max=0; int c; FORC3 mul[c] = dq[c]/div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt); } int CLASS foveon_apply_curve (short *curve, int i) { if (abs(i) >= curve[0]) return 0; return i < 0 ? -curve[1-i] : curve[1+i]; } #define image ((short (*)[4]) image) void CLASS foveon_interpolate() { static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 }; short *pix, prev[3], *curve[8], (*shrink)[3]; float cfilt=0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float (*black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p=0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum=0, trsum[3]; char str[128]; const char* cp; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Foveon interpolation...\n")); #endif foveon_load_camf(); foveon_fixed (dscr, 4, "DarkShieldColRange"); foveon_fixed (ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed (satlev, 3, "SaturationLevel"); foveon_fixed (keep, 4, "KeepImageArea"); foveon_fixed (active, 4, "ActiveImageArea"); foveon_fixed (chroma_dq, 3, "ChromaDQ"); foveon_fixed (color_dq, 3, foveon_camf_param ("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param ("IncludeBlocks", "ColumnFilter")) foveon_fixed (&cfilt, 1, "ColumnFilter"); memset (ddft, 0, sizeof ddft); if (!foveon_camf_param ("IncludeBlocks", "DarkDrift") || !foveon_fixed (ddft[1][0], 12, "DarkDrift")) for (i=0; i < 2; i++) { foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c]; FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1); } if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2))) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2); #endif return; } foveon_fixed (cam_xyz, 9, cp); foveon_fixed (correct, 9, foveon_camf_param ("WhiteBalanceCorrections", model2)); memset (last, 0, sizeof last); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x,y) last[(i+x)%3][(c+y)%3] for (i=0; i < 3; i++) FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1); #undef LAST FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583; sprintf (str, "%sRGBNeutral", model2); if (foveon_camf_param ("IncludeBlocks", str)) foveon_fixed (div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20; for (i=0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30; foveon_make_curves (curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves (curve+3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; curve[6] = foveon_make_curve (dsum, dsum, cfilt); curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt); sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain"); if (!sgain) return; sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow); sgx = (width + dim[1]-2) / (dim[1]-1); black = (float (*)[3]) calloc (height, sizeof *black); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); FORC3 black[row][c] = ( foveon_avg (image[row*width]+c, dscr[0], cfilt) + foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3 - ddft[0][c][0] ) / 4 - ddft[0][c][1]; } memcpy (black, black+8, sizeof *black*8); memcpy (black+height-11, black+height-22, 11*sizeof *black); memcpy (last, black, sizeof last); for (row=1; row < height-1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c]; } else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c]; memmove (last, last+1, 2*sizeof last[0]); memcpy (last[2], black[row+1], sizeof last[2]); } FORC3 black[row][c] = (last[0][c] + last[1][c])/2; FORC3 black[0][c] = (black[1][c] + black[3][c])/2; val = 1 - exp(-1/24.0); memcpy (fsum, black, sizeof fsum); for (row=1; row < height; row++) FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row-1][c])*val + black[row-1][c]; memcpy (last[0], black[height-1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--; ) FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c])*val + last[0][c]; memset (total, 0, sizeof total); for (row=2; row < height; row+=4) for (col=2; col < width; col+=4) { FORC3 total[c] += (short) image[row*width+col][c]; total[3]++; } for (row=0; row < height; row++) FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); pix = image[row*width]; memcpy (prev, pix, sizeof prev); frow = row / (height-1.0) * (dim[2]-1); if ((irow = frow) == dim[2]-1) irow--; frow -= irow; for (i=0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[ irow *dim[1]+i][c] * (1-frow) + sgain[(irow+1)*dim[1]+i][c] * frow; for (col=0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5) - black[row][c] ); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14; } FORC3 { for (val=i=0; i < 3; i++) for ( j=0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor ((ipix[c] + floor(val)) * ( sgrow[col/sgx ][c] * (sgx - col%sgx) + sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free (black); free (sgrow); free (sgain); if ((badpix = (unsigned *) foveon_camf_matrix (dim, "BadPixels"))) { for (i=0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20 ) - keep[1]; if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3) continue; memset (fsum, 0, sizeof fsum); for (sum=j=0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short) image[(row+hood[j*2])*width+col+hood[j*2+1]][c]; sum++; } if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum; } free (badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow); merror (smrow[6], "foveon_interpolate()"); for (i=0; i < 5; i++) smrow[i] = smrow[6] + i*width; /* Sharpen the reds against these Gaussian averages */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { smrow[4][col][0] = (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { smred = ( 6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix=image[0]; pix < image[height*width]; pix+=4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c=1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit*2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i*i >> 14); i = i*i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] - ((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { for (total[3]=375, sum=60, c=0; c < 3; c++) { for (total[c]=i=0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve (curve[6], ((j*total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix=image[0]; pix < image[height*width]; pix+=4) { FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]); sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum); FORC3 { for (dsum=i=0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ shrink = (short (*)[3]) calloc ((height/4), (width/4)*sizeof *shrink); merror (shrink, "foveon_interpolate()"); for (row = height/4; row--; ) for (col=0; col < width/4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i=0; i < 4; i++) for (j=0; j < 4; j++) FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c]; FORC3 if (row+2 > height/4) shrink[row*(width/4)+col][c] = ipix[c] >> 4; else shrink[row*(width/4)+col][c] = (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row=0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3 ; col--; ) FORC3 smrow[0][col][c] = ipix[c] = (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col=0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy (smrow[2], smrow[1], sizeof **smrow * width); else for (col=0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col=0; col < (width & ~3); col++) { for (i=j=30, c=0; c < 3; c++) { i += smrow[2][col][c]; j += image[row*width+col][c]; } j = (j << 16) / i; for (sum=c=0; c < 3; c++) { ipix[c] = foveon_apply_curve (curve[c+3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row*width+col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row*width+col][c] = i; } } } free (shrink); free (smrow[6]); for (i=0; i < 8; i++) free (curve[i]); /* Trim off the black border */ active[1] -= keep[1]; active[3] -= 2; i = active[2] - active[0]; for (row=0; row < active[3]-active[1]; row++) memcpy (image[row*i], image[(row+active[1])*width+active[0]], i * sizeof *image); width = i; height = row; } #undef image /* RESTRICTED code ends here */ //@out COMMON void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } //@end COMMON /* @out FILEIO #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end FILEIO */ // @out FILEIO /* Seach from the current directory up to the root looking for a ".badpixels" file, and fix those pixels now. */ void CLASS bad_pixels (const char *cfname) { FILE *fp=NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed=0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2); #endif if (cfname) fp = fopen (cfname, "r"); // @end FILEIO else { for (len=32 ; ; len *= 2) { fname = (char *) malloc (len); if (!fname) return; if (getcwd (fname, len-16)) break; free (fname); if (errno != ERANGE) return; } #if defined(WIN32) || defined(DJGPP) if (fname[1] == ':') memmove (fname, fname+2, len-2); for (cp=fname; *cp; cp++) if (*cp == '\\') *cp = '/'; #endif cp = fname + strlen(fname); if (cp[-1] == '/') cp--; while (*fname == '/') { strcpy (cp, "/.badpixels"); if ((fp = fopen (fname, "r"))) break; if (cp == fname) break; while (*--cp != '/'); } free (fname); } // @out FILEIO if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets (line, 128, fp)) { cp = strchr (line, '#'); if (cp) *cp = 0; if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned) col >= width || (unsigned) row >= height) continue; if (time > timestamp) continue; for (tot=n=0, rad=1; rad < 3 && n==0; rad++) for (r = row-rad; r <= row+rad; r++) for (c = col-rad; c <= col+rad; c++) if ((unsigned) r < height && (unsigned) c < width && (r != row || c != col) && fcol(r,c) == fcol(row,col)) { tot += BAYER2(r,c); n++; } BAYER2(row,col) = tot/n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf (stderr,_("Fixed dead pixels at:")); fprintf (stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc ('\n', stderr); #endif fclose (fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2); #endif } void CLASS subtract (const char *fname) { FILE *fp; int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col; ushort *pixel; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,0,2); #endif if (!(fp = fopen (fname, "rb"))) { #ifdef DCRAW_VERBOSE perror (fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE; #endif return; } if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1; while (!error && nd < 3 && (c = fgetc(fp)) != EOF) { if (c == '#') comment = 1; if (c == '\n') comment = 0; if (comment) continue; if (isdigit(c)) number = 1; if (number) { if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0'; else if (isspace(c)) { number = 0; nd++; } else error = 1; } } if (error || nd < 3) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s is not a valid PGM file!\n"), fname); #endif fclose (fp); return; } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s has the wrong dimensions!\n"), fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM; #endif fclose (fp); return; } pixel = (ushort *) calloc (width, sizeof *pixel); merror (pixel, "subtract()"); for (row=0; row < height; row++) { fread (pixel, 2, width, fp); for (col=0; col < width; col++) BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0); } free (pixel); fclose (fp); memset (cblack, 0, sizeof cblack); black = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,1,2); #endif } //@end FILEIO //@out COMMON static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--; } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } //@end COMMON int CLASS parse_tiff_ifd (int base); //@out COMMON static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char* pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos+7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos+7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy (ccms, pos, l); ccms[l] = '\0'; pos = strtok (ccms, ","); for (l=0; l<4; l++) { num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok (NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif //@end COMMON void CLASS parse_minolta (int base); int CLASS parse_tiff (int base); //@out COMMON int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(),get4()))); aperture = powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } //@end COMMON char * CLASS foveon_gets (int offset, char *str, int len) { int i; fseek (ifp, offset, SEEK_SET); for (i=0; i < len-1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek (ifp, 36, SEEK_SET); flip = get4(); fseek (ifp, -4, SEEK_END); fseek (ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(),get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek (ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek (ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off+28; is_foveon = 1; } fseek (ifp, off+28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len-28) { thumb_offset = off+28; thumb_length = len-28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off+24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off+8; meta_length = len-28; break; case 0x504f5250: /* PROP */ pent = (get4(),get4()); fseek (ifp, 12, SEEK_CUR); off += pent*8 + 24; if ((unsigned) pent > 256) pent=256; for (i=0; i < pent*2; i++) ((int *)poff)[i] = off + get4()*2; for (i=0; i < pent; i++) { foveon_gets (poff[i][0], name, 64); foveon_gets (poff[i][1], value, 64); if (!strcmp (name, "ISO")) iso_speed = atoi(value); if (!strcmp (name, "CAMMANUF")) strcpy (make, value); if (!strcmp (name, "CAMMODEL")) strcpy (model, value); if (!strcmp (name, "WB_DESC")) strcpy (model2, value); if (!strcmp (name, "TIME")) timestamp = atoi(value); if (!strcmp (name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp (name, "APERTURE")) aperture = atof(value); if (!strcmp (name, "FLENGTH")) focal_len = atof(value); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp (name, "CAMSERIAL")) strcpy (imgdata.shootinginfo.BodySerial, value); if (!strcmp (name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp (name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr (value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap (float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp (name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr (value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap (float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp (name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol (value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } #endif } #ifdef LOCALTIME timestamp = mktime (gmtime (&timestamp)); #endif } fseek (ifp, save, SEEK_SET); } } //@out COMMON /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[]={0,0}; FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if(len<1) return; // not needed, b/c sizeof of make/model is 64 string[len-1]=0; if(len<3) return; // also not needed len = strnlen(string,len-1); for(int i=len-1; i>=0; i--) { if(isspace(string[i])) string[i]=0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } //@end COMMON //@out FILEIO #ifndef NO_LCMS void CLASS apply_profile (const char *input, const char *output) { char *prof; cmsHPROFILE hInProfile=0, hOutProfile=0; cmsHTRANSFORM hTransform; FILE *fp; unsigned size; if (strcmp (input, "embed")) hInProfile = cmsOpenProfileFromFile (input, "r"); else if (profile_length) { #ifndef LIBRAW_LIBRARY_BUILD prof = (char *) malloc (profile_length); merror (prof, "apply_profile()"); fseek (ifp, profile_offset, SEEK_SET); fread (prof, 1, profile_length, ifp); hInProfile = cmsOpenProfileFromMem (prof, profile_length); free (prof); #else hInProfile = cmsOpenProfileFromMem (imgdata.color.profile, profile_length); #endif } else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s has no embedded profile.\n"), ifname); #endif } if (!hInProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE; #endif return; } if (!output) hOutProfile = cmsCreate_sRGBProfile(); else if ((fp = fopen (output, "rb"))) { fread (&size, 4, 1, fp); fseek (fp, 0, SEEK_SET); oprof = (unsigned *) malloc (size = ntohl(size)); merror (oprof, "apply_profile()"); fread (oprof, 1, size, fp); fclose (fp); if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) { free (oprof); oprof = 0; } } #ifdef DCRAW_VERBOSE else fprintf (stderr,_("Cannot open file %s!\n"), output); #endif if (!hOutProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE; #endif goto quit; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Applying color profile...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,0,2); #endif hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0); cmsDoTransform (hTransform, image, image, width*height); raw_color = 1; /* Don't use rgb_cam with a profile */ cmsDeleteTransform (hTransform); cmsCloseProfile (hOutProfile); quit: cmsCloseProfile (hInProfile); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,1,2); #endif } #endif //@end FILEIO //@out COMMON void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } //@end COMMON struct tiff_tag { ushort tag, type; int count; union { char c[4]; short s[2]; int i; } val; }; struct tiff_hdr { ushort t_order, magic; int ifd; ushort pad, ntag; struct tiff_tag tag[23]; int nextifd; ushort pad2, nexif; struct tiff_tag exif[4]; ushort pad3, ngps; struct tiff_tag gpst[10]; short bps[4]; int rat[10]; unsigned gps[26]; char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64]; }; //@out COMMON void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); } //@end COMMON int CLASS main (int argc, const char **argv) { int arg, status=0, quality, i, c; int timestamp_only=0, thumbnail_only=0, identify_only=0; int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1; int use_fuji_rotate=1, write_to_stdout=0, read_from_stdin=0; const char *sp, *bpfile=0, *dark_frame=0, *write_ext; char opm, opt, *ofname, *cp; struct utimbuf ut; #ifndef NO_LCMS const char *cam_profile=0, *out_profile=0; #endif #ifndef LOCALTIME putenv ((char *) "TZ=UTC"); #endif #ifdef LOCALEDIR setlocale (LC_CTYPE, ""); setlocale (LC_MESSAGES, ""); bindtextdomain ("dcraw", LOCALEDIR); textdomain ("dcraw"); #endif if (argc == 1) { printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION); printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n")); printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]); puts(_("-v Print verbose messages")); puts(_("-c Write image data to standard output")); puts(_("-e Extract embedded thumbnail image")); puts(_("-i Identify files without decoding them")); puts(_("-i -v Identify files and show metadata")); puts(_("-z Change file dates to camera timestamp")); puts(_("-w Use camera white balance, if possible")); puts(_("-a Average the whole image for white balance")); puts(_("-A <x y w h> Average a grey box for white balance")); puts(_("-r <r g b g> Set custom white balance")); puts(_("+M/-M Use/don't use an embedded color matrix")); puts(_("-C <r b> Correct chromatic aberration")); puts(_("-P <file> Fix the dead pixels listed in this file")); puts(_("-K <file> Subtract dark frame (16-bit raw PGM)")); puts(_("-k <num> Set the darkness level")); puts(_("-S <num> Set the saturation level")); puts(_("-n <num> Set threshold for wavelet denoising")); puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)")); puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)")); puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)")); #ifndef NO_LCMS puts(_("-o <file> Apply output ICC profile from file")); puts(_("-p <file> Apply camera ICC profile from file or \"embed\"")); #endif puts(_("-d Document mode (no color, no interpolation)")); puts(_("-D Document mode without scaling (totally raw)")); puts(_("-j Don't stretch or rotate raw pixels")); puts(_("-W Don't automatically brighten the image")); puts(_("-b <num> Adjust brightness (default = 1.0)")); puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)")); puts(_("-q [0-3] Set the interpolation quality")); puts(_("-h Half-size color image (twice as fast as \"-q 0\")")); puts(_("-f Interpolate RGGB as four colors")); puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G")); puts(_("-s [0..N-1] Select one raw image or \"all\" from each file")); puts(_("-6 Write 16-bit instead of 8-bit")); puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\"")); puts(_("-T Write TIFF instead of PPM")); puts(""); return 1; } argv[argc] = ""; for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) { opt = argv[arg++][1]; if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt))) for (i=0; i < "114111111422"[cp-sp]-'0'; i++) if (!isdigit(argv[arg+i][0])) { fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt); return 1; } switch (opt) { case 'n': threshold = atof(argv[arg++]); break; case 'b': bright = atof(argv[arg++]); break; case 'r': FORC4 user_mul[c] = atof(argv[arg++]); break; case 'C': aber[0] = 1 / atof(argv[arg++]); aber[2] = 1 / atof(argv[arg++]); break; case 'g': gamm[0] = atof(argv[arg++]); gamm[1] = atof(argv[arg++]); if (gamm[0]) gamm[0] = 1/gamm[0]; break; case 'k': user_black = atoi(argv[arg++]); break; case 'S': user_sat = atoi(argv[arg++]); break; case 't': user_flip = atoi(argv[arg++]); break; case 'q': user_qual = atoi(argv[arg++]); break; case 'm': med_passes = atoi(argv[arg++]); break; case 'H': highlight = atoi(argv[arg++]); break; case 's': shot_select = abs(atoi(argv[arg])); multi_out = !strcmp(argv[arg++],"all"); break; case 'o': if (isdigit(argv[arg][0]) && !argv[arg][1]) output_color = atoi(argv[arg++]); #ifndef NO_LCMS else out_profile = argv[arg++]; break; case 'p': cam_profile = argv[arg++]; #endif break; case 'P': bpfile = argv[arg++]; break; case 'K': dark_frame = argv[arg++]; break; case 'z': timestamp_only = 1; break; case 'e': thumbnail_only = 1; break; case 'i': identify_only = 1; break; case 'c': write_to_stdout = 1; break; case 'v': verbose = 1; break; case 'h': half_size = 1; break; case 'f': four_color_rgb = 1; break; case 'A': FORC4 greybox[c] = atoi(argv[arg++]); case 'a': use_auto_wb = 1; break; case 'w': use_camera_wb = 1; break; case 'M': use_camera_matrix = 3 * (opm == '+'); break; case 'I': read_from_stdin = 1; break; case 'E': document_mode++; case 'D': document_mode++; case 'd': document_mode++; case 'j': use_fuji_rotate = 0; break; case 'W': no_auto_bright = 1; break; case 'T': output_tiff = 1; break; case '4': gamm[0] = gamm[1] = no_auto_bright = 1; case '6': output_bps = 16; break; default: fprintf (stderr,_("Unknown option \"-%c\".\n"), opt); return 1; } } if (arg == argc) { fprintf (stderr,_("No files to process.\n")); return 1; } if (write_to_stdout) { if (isatty(1)) { fprintf (stderr,_("Will not write an image to the terminal!\n")); return 1; } #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) if (setmode(1,O_BINARY) < 0) { perror ("setmode()"); return 1; } #endif } for ( ; arg < argc; arg++) { status = 1; raw_image = 0; image = 0; oprof = 0; meta_data = ofname = 0; ofp = stdout; if (setjmp (failure)) { if (fileno(ifp) > 2) fclose(ifp); if (fileno(ofp) > 2) fclose(ofp); status = 1; goto cleanup; } ifname = argv[arg]; if (!(ifp = fopen (ifname, "rb"))) { perror (ifname); continue; } status = (identify(),!is_raw); if (user_flip >= 0) flip = user_flip; switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; } if (timestamp_only) { if ((status = !timestamp)) fprintf (stderr,_("%s has no timestamp.\n"), ifname); else if (identify_only) printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname); else { if (verbose) fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp); ut.actime = ut.modtime = timestamp; utime (ifname, &ut); } goto next; } write_fun = &CLASS write_ppm_tiff; if (thumbnail_only) { if ((status = !thumb_offset)) { fprintf (stderr,_("%s has no thumbnail.\n"), ifname); goto next; } else if (thumb_load_raw) { load_raw = thumb_load_raw; data_offset = thumb_offset; height = thumb_height; width = thumb_width; filters = 0; colors = 3; } else { fseek (ifp, thumb_offset, SEEK_SET); write_fun = write_thumb; goto thumbnail; } } if (load_raw == &CLASS kodak_ycbcr_load_raw) { height += height & 1; width += width & 1; } if (identify_only && verbose && make[0]) { printf (_("\nFilename: %s\n"), ifname); printf (_("Timestamp: %s"), ctime(&timestamp)); printf (_("Camera: %s %s\n"), make, model); if (artist[0]) printf (_("Owner: %s\n"), artist); if (dng_version) { printf (_("DNG Version: ")); for (i=24; i >= 0; i -= 8) printf ("%d%c", dng_version >> i & 255, i ? '.':'\n'); } printf (_("ISO speed: %d\n"), (int) iso_speed); printf (_("Shutter: ")); if (shutter > 0 && shutter < 1) shutter = (printf ("1/"), 1 / shutter); printf (_("%0.1f sec\n"), shutter); printf (_("Aperture: f/%0.1f\n"), aperture); printf (_("Focal length: %0.1f mm\n"), focal_len); printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no")); printf (_("Number of raw images: %d\n"), is_raw); if (pixel_aspect != 1) printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect); if (thumb_offset) printf (_("Thumb size: %4d x %d\n"), thumb_width, thumb_height); printf (_("Full size: %4d x %d\n"), raw_width, raw_height); } else if (!is_raw) fprintf (stderr,_("Cannot decode file %s\n"), ifname); if (!is_raw) goto next; shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1))); iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (identify_only) { if (verbose) { if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (use_fuji_rotate) { if (fuji_width) { fuji_width = (fuji_width - 1 + shrink) >> shrink; iwidth = fuji_width / sqrt(0.5); iheight = (iheight - fuji_width) / sqrt(0.5); } else { if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5; if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5; } } if (flip & 4) SWAP(iheight,iwidth); printf (_("Image size: %4d x %d\n"), width, height); printf (_("Output size: %4d x %d\n"), iwidth, iheight); printf (_("Raw colors: %d"), colors); if (filters) { int fhigh = 2, fwide = 2; if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4; if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8; if (filters == 1) fhigh = fwide = 16; if (filters == 9) fhigh = fwide = 6; printf (_("\nFilter pattern: ")); for (i=0; i < fhigh; i++) for (c = i && putchar('/') && 0; c < fwide; c++) putchar (cdesc[fcol(i,c)]); } printf (_("\nDaylight multipliers:")); FORCC printf (" %f", pre_mul[c]); if (cam_mul[0] > 0) { printf (_("\nCamera multipliers:")); FORC4 printf (" %f", cam_mul[c]); } putchar ('\n'); } else printf (_("%s is a %s %s image.\n"), ifname, make, model); next: fclose(ifp); continue; } if (meta_length) { meta_data = (char *) malloc (meta_length); merror (meta_data, "main()"); } if (filters || colors == 1) { raw_image = (ushort *) calloc ((raw_height+7), raw_width*2); merror (raw_image, "main()"); } else { image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image); merror (image, "main()"); } if (verbose) fprintf (stderr,_("Loading %s %s image from %s ...\n"), make, model, ifname); if (shot_select >= is_raw) fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select); fseeko (ifp, data_offset, SEEK_SET); if (raw_image && read_from_stdin) fread (raw_image, 2, raw_height*raw_width, stdin); else (*load_raw)(); if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (raw_image) { image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image); merror (image, "main()"); crop_masked_pixels(); free (raw_image); } if (zero_is_bad) remove_zeroes(); bad_pixels (bpfile); if (dark_frame) subtract (dark_frame); quality = 2 + !fuji_width; if (user_qual >= 0) quality = user_qual; i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; i = cblack[6]; FORC (cblack[4] * cblack[5]) if (i > cblack[6+c]) i = cblack[6+c]; FORC (cblack[4] * cblack[5]) cblack[6+c] -= i; black += i; if (user_black >= 0) black = user_black; FORC4 cblack[c] += black; if (user_sat > 0) maximum = user_sat; #ifdef COLORCHECK colorcheck(); #endif if (is_foveon) { if (document_mode || load_raw == &CLASS foveon_dp_load_raw) { for (i=0; i < height*width*4; i++) if ((short) image[0][i] < 0) image[0][i] = 0; } else foveon_interpolate(); } else if (document_mode < 2) scale_colors(); pre_interpolate(); if (filters && !document_mode) { if (quality == 0) lin_interpolate(); else if (quality == 1 || colors > 3) vng_interpolate(); else if (quality == 2 && filters > 1000) ppg_interpolate(); else if (filters == 9) xtrans_interpolate (quality*2-3); else ahd_interpolate(); } if (mix_green) for (colors=3, i=0; i < height*width; i++) image[i][1] = (image[i][1] + image[i][3]) >> 1; if (!is_foveon && colors == 3) median_filter(); if (!is_foveon && highlight == 2) blend_highlights(); if (!is_foveon && highlight > 2) recover_highlights(); if (use_fuji_rotate) fuji_rotate(); #ifndef NO_LCMS if (cam_profile) apply_profile (cam_profile, out_profile); #endif convert_to_rgb(); if (use_fuji_rotate) stretch(); thumbnail: if (write_fun == &CLASS jpeg_thumb) write_ext = ".jpg"; else if (output_tiff && write_fun == &CLASS write_ppm_tiff) write_ext = ".tiff"; else write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5; ofname = (char *) malloc (strlen(ifname) + 64); merror (ofname, "main()"); if (write_to_stdout) strcpy (ofname,_("standard output")); else { strcpy (ofname, ifname); if ((cp = strrchr (ofname, '.'))) *cp = 0; if (multi_out) sprintf (ofname+strlen(ofname), "_%0*d", snprintf(0,0,"%d",is_raw-1), shot_select); if (thumbnail_only) strcat (ofname, ".thumb"); strcat (ofname, write_ext); ofp = fopen (ofname, "wb"); if (!ofp) { status = 1; perror (ofname); goto cleanup; } } if (verbose) fprintf (stderr,_("Writing data to %s ...\n"), ofname); (*write_fun)(); fclose(ifp); if (ofp != stdout) fclose(ofp); cleanup: if (meta_data) free (meta_data); if (ofname) free (ofname); if (oprof) free (oprof); if (image) free (image); if (multi_out) { if (++shot_select < is_raw) arg--; else shot_select = 0; } } return status; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_2804_1
crossvul-cpp_data_good_1852_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 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/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(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 IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded pixel % packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t maxpixels) { register const unsigned char *l, *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; l=q+maxpixels; while (((size_t) (p-compressed_pixels) < length) && (q < l)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte> */ count=(ssize_t) (*p++); if (count > 0) byte=(*p++); while ((count >= 0) && (q < l)) { *q++=byte; count--; } } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN 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 ReadSUNImage method is: % % Image *ReadSUNImage(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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); else { if (sun_info.length > (height*bytes_per_line)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const Quantum *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ? 32U : 24U; sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (IsImageMonochrome(image,exception) != MagickFalse) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1852_0
crossvul-cpp_data_bad_3255_0
/* * Routines having to do with the 'struct sk_buff' memory handlers. * * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk> * Florian La Roche <rzsfl@rz.uni-sb.de> * * Fixes: * Alan Cox : Fixed the worst of the load * balancer bugs. * Dave Platt : Interrupt stacking fix. * Richard Kooijman : Timestamp fixes. * Alan Cox : Changed buffer format. * Alan Cox : destructor hook for AF_UNIX etc. * Linus Torvalds : Better skb_clone. * Alan Cox : Added skb_copy. * Alan Cox : Added all the changed routines Linus * only put in the headers * Ray VanTassle : Fixed --skb->lock in free * Alan Cox : skb_copy copy arp field * Andi Kleen : slabified it. * Robert Olsson : Removed skb_head_pool * * NOTE: * The __skb_ routines should be called with interrupts * disabled, or you better be *real* sure that the operation is atomic * with respect to whatever list is being frobbed (e.g. via lock_sock() * or via disabling bottom half handlers, etc). * * 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. */ /* * The functions in this file will not compile correctly with gcc 2.4.x */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/kmemcheck.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/slab.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/sctp.h> #include <linux/netdevice.h> #ifdef CONFIG_NET_CLS_ACT #include <net/pkt_sched.h> #endif #include <linux/string.h> #include <linux/skbuff.h> #include <linux/splice.h> #include <linux/cache.h> #include <linux/rtnetlink.h> #include <linux/init.h> #include <linux/scatterlist.h> #include <linux/errqueue.h> #include <linux/prefetch.h> #include <linux/if_vlan.h> #include <net/protocol.h> #include <net/dst.h> #include <net/sock.h> #include <net/checksum.h> #include <net/ip6_checksum.h> #include <net/xfrm.h> #include <linux/uaccess.h> #include <trace/events/skb.h> #include <linux/highmem.h> #include <linux/capability.h> #include <linux/user_namespace.h> struct kmem_cache *skbuff_head_cache __read_mostly; static struct kmem_cache *skbuff_fclone_cache __read_mostly; int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS; EXPORT_SYMBOL(sysctl_max_skb_frags); /** * skb_panic - private function for out-of-line support * @skb: buffer * @sz: size * @addr: address * @msg: skb_over_panic or skb_under_panic * * Out-of-line support for skb_put() and skb_push(). * Called via the wrapper skb_over_panic() or skb_under_panic(). * Keep out of line to prevent kernel bloat. * __builtin_return_address is not used because it is not always reliable. */ static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr, const char msg[]) { pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n", msg, addr, skb->len, sz, skb->head, skb->data, (unsigned long)skb->tail, (unsigned long)skb->end, skb->dev ? skb->dev->name : "<NULL>"); BUG(); } static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr) { skb_panic(skb, sz, addr, __func__); } static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr) { skb_panic(skb, sz, addr, __func__); } /* * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells * the caller if emergency pfmemalloc reserves are being used. If it is and * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves * may be used. Otherwise, the packet data may be discarded until enough * memory is free */ #define kmalloc_reserve(size, gfp, node, pfmemalloc) \ __kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc) static void *__kmalloc_reserve(size_t size, gfp_t flags, int node, unsigned long ip, bool *pfmemalloc) { void *obj; bool ret_pfmemalloc = false; /* * Try a regular allocation, when that fails and we're not entitled * to the reserves, fail. */ obj = kmalloc_node_track_caller(size, flags | __GFP_NOMEMALLOC | __GFP_NOWARN, node); if (obj || !(gfp_pfmemalloc_allowed(flags))) goto out; /* Try again but now we are using pfmemalloc reserves */ ret_pfmemalloc = true; obj = kmalloc_node_track_caller(size, flags, node); out: if (pfmemalloc) *pfmemalloc = ret_pfmemalloc; return obj; } /* Allocate a new skbuff. We do this ourselves so we can fill in a few * 'private' fields and also do memory statistics to find all the * [BEEP] leaks. * */ struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node) { struct sk_buff *skb; /* Get the HEAD */ skb = kmem_cache_alloc_node(skbuff_head_cache, gfp_mask & ~__GFP_DMA, node); if (!skb) goto out; /* * Only clear those fields we need to clear, not those that we will * actually initialise below. Hence, don't put any more fields after * the tail pointer in struct sk_buff! */ memset(skb, 0, offsetof(struct sk_buff, tail)); skb->head = NULL; skb->truesize = sizeof(struct sk_buff); atomic_set(&skb->users, 1); skb->mac_header = (typeof(skb->mac_header))~0U; out: return skb; } /** * __alloc_skb - allocate a network buffer * @size: size to allocate * @gfp_mask: allocation mask * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache * instead of head cache and allocate a cloned (child) skb. * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for * allocations in case the data is required for writeback * @node: numa node to allocate memory on * * Allocate a new &sk_buff. The returned buffer has no headroom and a * tail room of at least size bytes. The object has a reference count * of one. The return is the buffer. On a failure the return is %NULL. * * Buffers may only be allocated from interrupts using a @gfp_mask of * %GFP_ATOMIC. */ struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask, int flags, int node) { struct kmem_cache *cache; struct skb_shared_info *shinfo; struct sk_buff *skb; u8 *data; bool pfmemalloc; cache = (flags & SKB_ALLOC_FCLONE) ? skbuff_fclone_cache : skbuff_head_cache; if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX)) gfp_mask |= __GFP_MEMALLOC; /* Get the HEAD */ skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node); if (!skb) goto out; prefetchw(skb); /* We do our best to align skb_shared_info on a separate cache * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives * aligned memory blocks, unless SLUB/SLAB debug is enabled. * Both skb->head and skb_shared_info are cache line aligned. */ size = SKB_DATA_ALIGN(size); size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc); if (!data) goto nodata; /* kmalloc(size) might give us more room than requested. * Put skb_shared_info exactly at the end of allocated zone, * to allow max possible filling before reallocation. */ size = SKB_WITH_OVERHEAD(ksize(data)); prefetchw(data + size); /* * Only clear those fields we need to clear, not those that we will * actually initialise below. Hence, don't put any more fields after * the tail pointer in struct sk_buff! */ memset(skb, 0, offsetof(struct sk_buff, tail)); /* Account for allocated memory : skb + skb->head */ skb->truesize = SKB_TRUESIZE(size); skb->pfmemalloc = pfmemalloc; atomic_set(&skb->users, 1); skb->head = data; skb->data = data; skb_reset_tail_pointer(skb); skb->end = skb->tail + size; skb->mac_header = (typeof(skb->mac_header))~0U; skb->transport_header = (typeof(skb->transport_header))~0U; /* make sure we initialize shinfo sequentially */ shinfo = skb_shinfo(skb); memset(shinfo, 0, offsetof(struct skb_shared_info, dataref)); atomic_set(&shinfo->dataref, 1); kmemcheck_annotate_variable(shinfo->destructor_arg); if (flags & SKB_ALLOC_FCLONE) { struct sk_buff_fclones *fclones; fclones = container_of(skb, struct sk_buff_fclones, skb1); kmemcheck_annotate_bitfield(&fclones->skb2, flags1); skb->fclone = SKB_FCLONE_ORIG; atomic_set(&fclones->fclone_ref, 1); fclones->skb2.fclone = SKB_FCLONE_CLONE; } out: return skb; nodata: kmem_cache_free(cache, skb); skb = NULL; goto out; } EXPORT_SYMBOL(__alloc_skb); /** * __build_skb - build a network buffer * @data: data buffer provided by caller * @frag_size: size of data, or 0 if head was kmalloced * * Allocate a new &sk_buff. Caller provides space holding head and * skb_shared_info. @data must have been allocated by kmalloc() only if * @frag_size is 0, otherwise data should come from the page allocator * or vmalloc() * The return is the new skb buffer. * On a failure the return is %NULL, and @data is not freed. * Notes : * Before IO, driver allocates only data buffer where NIC put incoming frame * Driver should add room at head (NET_SKB_PAD) and * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info)) * After IO, driver calls build_skb(), to allocate sk_buff and populate it * before giving packet to stack. * RX rings only contains data buffers, not full skbs. */ struct sk_buff *__build_skb(void *data, unsigned int frag_size) { struct skb_shared_info *shinfo; struct sk_buff *skb; unsigned int size = frag_size ? : ksize(data); skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC); if (!skb) return NULL; size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); memset(skb, 0, offsetof(struct sk_buff, tail)); skb->truesize = SKB_TRUESIZE(size); atomic_set(&skb->users, 1); skb->head = data; skb->data = data; skb_reset_tail_pointer(skb); skb->end = skb->tail + size; skb->mac_header = (typeof(skb->mac_header))~0U; skb->transport_header = (typeof(skb->transport_header))~0U; /* make sure we initialize shinfo sequentially */ shinfo = skb_shinfo(skb); memset(shinfo, 0, offsetof(struct skb_shared_info, dataref)); atomic_set(&shinfo->dataref, 1); kmemcheck_annotate_variable(shinfo->destructor_arg); return skb; } /* build_skb() is wrapper over __build_skb(), that specifically * takes care of skb->head and skb->pfmemalloc * This means that if @frag_size is not zero, then @data must be backed * by a page fragment, not kmalloc() or vmalloc() */ struct sk_buff *build_skb(void *data, unsigned int frag_size) { struct sk_buff *skb = __build_skb(data, frag_size); if (skb && frag_size) { skb->head_frag = 1; if (page_is_pfmemalloc(virt_to_head_page(data))) skb->pfmemalloc = 1; } return skb; } EXPORT_SYMBOL(build_skb); #define NAPI_SKB_CACHE_SIZE 64 struct napi_alloc_cache { struct page_frag_cache page; unsigned int skb_count; void *skb_cache[NAPI_SKB_CACHE_SIZE]; }; static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache); static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache); static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask) { struct page_frag_cache *nc; unsigned long flags; void *data; local_irq_save(flags); nc = this_cpu_ptr(&netdev_alloc_cache); data = page_frag_alloc(nc, fragsz, gfp_mask); local_irq_restore(flags); return data; } /** * netdev_alloc_frag - allocate a page fragment * @fragsz: fragment size * * Allocates a frag from a page for receive buffer. * Uses GFP_ATOMIC allocations. */ void *netdev_alloc_frag(unsigned int fragsz) { return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD); } EXPORT_SYMBOL(netdev_alloc_frag); static void *__napi_alloc_frag(unsigned int fragsz, gfp_t gfp_mask) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); return page_frag_alloc(&nc->page, fragsz, gfp_mask); } void *napi_alloc_frag(unsigned int fragsz) { return __napi_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD); } EXPORT_SYMBOL(napi_alloc_frag); /** * __netdev_alloc_skb - allocate an skbuff for rx on a specific device * @dev: network device to receive on * @len: length to allocate * @gfp_mask: get_free_pages mask, passed to alloc_skb * * Allocate a new &sk_buff and assign it a usage count of one. The * buffer has NET_SKB_PAD headroom built in. Users should allocate * the headroom they think they need without accounting for the * built in space. The built in space is used for optimisations. * * %NULL is returned if there is no free memory. */ struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len, gfp_t gfp_mask) { struct page_frag_cache *nc; unsigned long flags; struct sk_buff *skb; bool pfmemalloc; void *data; len += NET_SKB_PAD; if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) || (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) { skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE); if (!skb) goto skb_fail; goto skb_success; } len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); len = SKB_DATA_ALIGN(len); if (sk_memalloc_socks()) gfp_mask |= __GFP_MEMALLOC; local_irq_save(flags); nc = this_cpu_ptr(&netdev_alloc_cache); data = page_frag_alloc(nc, len, gfp_mask); pfmemalloc = nc->pfmemalloc; local_irq_restore(flags); if (unlikely(!data)) return NULL; skb = __build_skb(data, len); if (unlikely(!skb)) { skb_free_frag(data); return NULL; } /* use OR instead of assignment to avoid clearing of bits in mask */ if (pfmemalloc) skb->pfmemalloc = 1; skb->head_frag = 1; skb_success: skb_reserve(skb, NET_SKB_PAD); skb->dev = dev; skb_fail: return skb; } EXPORT_SYMBOL(__netdev_alloc_skb); /** * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance * @napi: napi instance this buffer was allocated for * @len: length to allocate * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages * * Allocate a new sk_buff for use in NAPI receive. This buffer will * attempt to allocate the head from a special reserved region used * only for NAPI Rx allocation. By doing this we can save several * CPU cycles by avoiding having to disable and re-enable IRQs. * * %NULL is returned if there is no free memory. */ struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len, gfp_t gfp_mask) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); struct sk_buff *skb; void *data; len += NET_SKB_PAD + NET_IP_ALIGN; if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) || (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) { skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE); if (!skb) goto skb_fail; goto skb_success; } len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); len = SKB_DATA_ALIGN(len); if (sk_memalloc_socks()) gfp_mask |= __GFP_MEMALLOC; data = page_frag_alloc(&nc->page, len, gfp_mask); if (unlikely(!data)) return NULL; skb = __build_skb(data, len); if (unlikely(!skb)) { skb_free_frag(data); return NULL; } /* use OR instead of assignment to avoid clearing of bits in mask */ if (nc->page.pfmemalloc) skb->pfmemalloc = 1; skb->head_frag = 1; skb_success: skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN); skb->dev = napi->dev; skb_fail: return skb; } EXPORT_SYMBOL(__napi_alloc_skb); void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off, int size, unsigned int truesize) { skb_fill_page_desc(skb, i, page, off, size); skb->len += size; skb->data_len += size; skb->truesize += truesize; } EXPORT_SYMBOL(skb_add_rx_frag); void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size, unsigned int truesize) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; skb_frag_size_add(frag, size); skb->len += size; skb->data_len += size; skb->truesize += truesize; } EXPORT_SYMBOL(skb_coalesce_rx_frag); static void skb_drop_list(struct sk_buff **listp) { kfree_skb_list(*listp); *listp = NULL; } static inline void skb_drop_fraglist(struct sk_buff *skb) { skb_drop_list(&skb_shinfo(skb)->frag_list); } static void skb_clone_fraglist(struct sk_buff *skb) { struct sk_buff *list; skb_walk_frags(skb, list) skb_get(list); } static void skb_free_head(struct sk_buff *skb) { unsigned char *head = skb->head; if (skb->head_frag) skb_free_frag(head); else kfree(head); } static void skb_release_data(struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int i; if (skb->cloned && atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1, &shinfo->dataref)) return; for (i = 0; i < shinfo->nr_frags; i++) __skb_frag_unref(&shinfo->frags[i]); /* * If skb buf is from userspace, we need to notify the caller * the lower device DMA has done; */ if (shinfo->tx_flags & SKBTX_DEV_ZEROCOPY) { struct ubuf_info *uarg; uarg = shinfo->destructor_arg; if (uarg->callback) uarg->callback(uarg, true); } if (shinfo->frag_list) kfree_skb_list(shinfo->frag_list); skb_free_head(skb); } /* * Free an skbuff by memory without cleaning the state. */ static void kfree_skbmem(struct sk_buff *skb) { struct sk_buff_fclones *fclones; switch (skb->fclone) { case SKB_FCLONE_UNAVAILABLE: kmem_cache_free(skbuff_head_cache, skb); return; case SKB_FCLONE_ORIG: fclones = container_of(skb, struct sk_buff_fclones, skb1); /* We usually free the clone (TX completion) before original skb * This test would have no chance to be true for the clone, * while here, branch prediction will be good. */ if (atomic_read(&fclones->fclone_ref) == 1) goto fastpath; break; default: /* SKB_FCLONE_CLONE */ fclones = container_of(skb, struct sk_buff_fclones, skb2); break; } if (!atomic_dec_and_test(&fclones->fclone_ref)) return; fastpath: kmem_cache_free(skbuff_fclone_cache, fclones); } static void skb_release_head_state(struct sk_buff *skb) { skb_dst_drop(skb); #ifdef CONFIG_XFRM secpath_put(skb->sp); #endif if (skb->destructor) { WARN_ON(in_irq()); skb->destructor(skb); } #if IS_ENABLED(CONFIG_NF_CONNTRACK) nf_conntrack_put(skb_nfct(skb)); #endif #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER) nf_bridge_put(skb->nf_bridge); #endif } /* Free everything but the sk_buff shell. */ static void skb_release_all(struct sk_buff *skb) { skb_release_head_state(skb); if (likely(skb->head)) skb_release_data(skb); } /** * __kfree_skb - private function * @skb: buffer * * Free an sk_buff. Release anything attached to the buffer. * Clean the state. This is an internal helper function. Users should * always call kfree_skb */ void __kfree_skb(struct sk_buff *skb) { skb_release_all(skb); kfree_skbmem(skb); } EXPORT_SYMBOL(__kfree_skb); /** * kfree_skb - free an sk_buff * @skb: buffer to free * * Drop a reference to the buffer and free it if the usage count has * hit zero. */ void kfree_skb(struct sk_buff *skb) { if (unlikely(!skb)) return; if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; trace_kfree_skb(skb, __builtin_return_address(0)); __kfree_skb(skb); } EXPORT_SYMBOL(kfree_skb); void kfree_skb_list(struct sk_buff *segs) { while (segs) { struct sk_buff *next = segs->next; kfree_skb(segs); segs = next; } } EXPORT_SYMBOL(kfree_skb_list); /** * skb_tx_error - report an sk_buff xmit error * @skb: buffer that triggered an error * * Report xmit error if a device callback is tracking this skb. * skb must be freed afterwards. */ void skb_tx_error(struct sk_buff *skb) { if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) { struct ubuf_info *uarg; uarg = skb_shinfo(skb)->destructor_arg; if (uarg->callback) uarg->callback(uarg, false); skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY; } } EXPORT_SYMBOL(skb_tx_error); /** * consume_skb - free an skbuff * @skb: buffer to free * * Drop a ref to the buffer and free it if the usage count has hit zero * Functions identically to kfree_skb, but kfree_skb assumes that the frame * is being dropped after a failure and notes that */ void consume_skb(struct sk_buff *skb) { if (unlikely(!skb)) return; if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; trace_consume_skb(skb); __kfree_skb(skb); } EXPORT_SYMBOL(consume_skb); void __kfree_skb_flush(void) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); /* flush skb_cache if containing objects */ if (nc->skb_count) { kmem_cache_free_bulk(skbuff_head_cache, nc->skb_count, nc->skb_cache); nc->skb_count = 0; } } static inline void _kfree_skb_defer(struct sk_buff *skb) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); /* drop skb->head and call any destructors for packet */ skb_release_all(skb); /* record skb to CPU local list */ nc->skb_cache[nc->skb_count++] = skb; #ifdef CONFIG_SLUB /* SLUB writes into objects when freeing */ prefetchw(skb); #endif /* flush skb_cache if it is filled */ if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) { kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_SIZE, nc->skb_cache); nc->skb_count = 0; } } void __kfree_skb_defer(struct sk_buff *skb) { _kfree_skb_defer(skb); } void napi_consume_skb(struct sk_buff *skb, int budget) { if (unlikely(!skb)) return; /* Zero budget indicate non-NAPI context called us, like netpoll */ if (unlikely(!budget)) { dev_consume_skb_any(skb); return; } if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; /* if reaching here SKB is ready to free */ trace_consume_skb(skb); /* if SKB is a clone, don't handle this case */ if (skb->fclone != SKB_FCLONE_UNAVAILABLE) { __kfree_skb(skb); return; } _kfree_skb_defer(skb); } EXPORT_SYMBOL(napi_consume_skb); /* Make sure a field is enclosed inside headers_start/headers_end section */ #define CHECK_SKB_FIELD(field) \ BUILD_BUG_ON(offsetof(struct sk_buff, field) < \ offsetof(struct sk_buff, headers_start)); \ BUILD_BUG_ON(offsetof(struct sk_buff, field) > \ offsetof(struct sk_buff, headers_end)); \ static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old) { new->tstamp = old->tstamp; /* We do not copy old->sk */ new->dev = old->dev; memcpy(new->cb, old->cb, sizeof(old->cb)); skb_dst_copy(new, old); #ifdef CONFIG_XFRM new->sp = secpath_get(old->sp); #endif __nf_copy(new, old, false); /* Note : this field could be in headers_start/headers_end section * It is not yet because we do not want to have a 16 bit hole */ new->queue_mapping = old->queue_mapping; memcpy(&new->headers_start, &old->headers_start, offsetof(struct sk_buff, headers_end) - offsetof(struct sk_buff, headers_start)); CHECK_SKB_FIELD(protocol); CHECK_SKB_FIELD(csum); CHECK_SKB_FIELD(hash); CHECK_SKB_FIELD(priority); CHECK_SKB_FIELD(skb_iif); CHECK_SKB_FIELD(vlan_proto); CHECK_SKB_FIELD(vlan_tci); CHECK_SKB_FIELD(transport_header); CHECK_SKB_FIELD(network_header); CHECK_SKB_FIELD(mac_header); CHECK_SKB_FIELD(inner_protocol); CHECK_SKB_FIELD(inner_transport_header); CHECK_SKB_FIELD(inner_network_header); CHECK_SKB_FIELD(inner_mac_header); CHECK_SKB_FIELD(mark); #ifdef CONFIG_NETWORK_SECMARK CHECK_SKB_FIELD(secmark); #endif #ifdef CONFIG_NET_RX_BUSY_POLL CHECK_SKB_FIELD(napi_id); #endif #ifdef CONFIG_XPS CHECK_SKB_FIELD(sender_cpu); #endif #ifdef CONFIG_NET_SCHED CHECK_SKB_FIELD(tc_index); #endif } /* * You should not add any new code to this function. Add it to * __copy_skb_header above instead. */ static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb) { #define C(x) n->x = skb->x n->next = n->prev = NULL; n->sk = NULL; __copy_skb_header(n, skb); C(len); C(data_len); C(mac_len); n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len; n->cloned = 1; n->nohdr = 0; n->destructor = NULL; C(tail); C(end); C(head); C(head_frag); C(data); C(truesize); atomic_set(&n->users, 1); atomic_inc(&(skb_shinfo(skb)->dataref)); skb->cloned = 1; return n; #undef C } /** * skb_morph - morph one skb into another * @dst: the skb to receive the contents * @src: the skb to supply the contents * * This is identical to skb_clone except that the target skb is * supplied by the user. * * The target skb is returned upon exit. */ struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src) { skb_release_all(dst); return __skb_clone(dst, src); } EXPORT_SYMBOL_GPL(skb_morph); /** * skb_copy_ubufs - copy userspace skb frags buffers to kernel * @skb: the skb to modify * @gfp_mask: allocation priority * * This must be called on SKBTX_DEV_ZEROCOPY skb. * It will copy all frags into kernel and drop the reference * to userspace pages. * * If this function is called from an interrupt gfp_mask() must be * %GFP_ATOMIC. * * Returns 0 on success or a negative error code on failure * to allocate kernel memory to copy to. */ int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask) { int i; int num_frags = skb_shinfo(skb)->nr_frags; struct page *page, *head = NULL; struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg; for (i = 0; i < num_frags; i++) { u8 *vaddr; skb_frag_t *f = &skb_shinfo(skb)->frags[i]; page = alloc_page(gfp_mask); if (!page) { while (head) { struct page *next = (struct page *)page_private(head); put_page(head); head = next; } return -ENOMEM; } vaddr = kmap_atomic(skb_frag_page(f)); memcpy(page_address(page), vaddr + f->page_offset, skb_frag_size(f)); kunmap_atomic(vaddr); set_page_private(page, (unsigned long)head); head = page; } /* skb frags release userspace buffers */ for (i = 0; i < num_frags; i++) skb_frag_unref(skb, i); uarg->callback(uarg, false); /* skb frags point to kernel buffers */ for (i = num_frags - 1; i >= 0; i--) { __skb_fill_page_desc(skb, i, head, 0, skb_shinfo(skb)->frags[i].size); head = (struct page *)page_private(head); } skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY; return 0; } EXPORT_SYMBOL_GPL(skb_copy_ubufs); /** * skb_clone - duplicate an sk_buff * @skb: buffer to clone * @gfp_mask: allocation priority * * Duplicate an &sk_buff. The new one is not owned by a socket. Both * copies share the same packet data but not structure. The new * buffer has a reference count of 1. If the allocation fails the * function returns %NULL otherwise the new buffer is returned. * * If this function is called from an interrupt gfp_mask() must be * %GFP_ATOMIC. */ struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask) { struct sk_buff_fclones *fclones = container_of(skb, struct sk_buff_fclones, skb1); struct sk_buff *n; if (skb_orphan_frags(skb, gfp_mask)) return NULL; if (skb->fclone == SKB_FCLONE_ORIG && atomic_read(&fclones->fclone_ref) == 1) { n = &fclones->skb2; atomic_set(&fclones->fclone_ref, 2); } else { if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; n = kmem_cache_alloc(skbuff_head_cache, gfp_mask); if (!n) return NULL; kmemcheck_annotate_bitfield(n, flags1); n->fclone = SKB_FCLONE_UNAVAILABLE; } return __skb_clone(n, skb); } EXPORT_SYMBOL(skb_clone); static void skb_headers_offset_update(struct sk_buff *skb, int off) { /* Only adjust this if it actually is csum_start rather than csum */ if (skb->ip_summed == CHECKSUM_PARTIAL) skb->csum_start += off; /* {transport,network,mac}_header and tail are relative to skb->head */ skb->transport_header += off; skb->network_header += off; if (skb_mac_header_was_set(skb)) skb->mac_header += off; skb->inner_transport_header += off; skb->inner_network_header += off; skb->inner_mac_header += off; } static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old) { __copy_skb_header(new, old); skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size; skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs; skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type; } static inline int skb_alloc_rx_flag(const struct sk_buff *skb) { if (skb_pfmemalloc(skb)) return SKB_ALLOC_RX; return 0; } /** * skb_copy - create private copy of an sk_buff * @skb: buffer to copy * @gfp_mask: allocation priority * * Make a copy of both an &sk_buff and its data. This is used when the * caller wishes to modify the data and needs a private copy of the * data to alter. Returns %NULL on failure or the pointer to the buffer * on success. The returned buffer has a reference count of 1. * * As by-product this function converts non-linear &sk_buff to linear * one, so that &sk_buff becomes completely private and caller is allowed * to modify all the data of returned buffer. This means that this * function is not recommended for use in circumstances when only * header is going to be modified. Use pskb_copy() instead. */ struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask) { int headerlen = skb_headroom(skb); unsigned int size = skb_end_offset(skb) + skb->data_len; struct sk_buff *n = __alloc_skb(size, gfp_mask, skb_alloc_rx_flag(skb), NUMA_NO_NODE); if (!n) return NULL; /* Set the data pointer */ skb_reserve(n, headerlen); /* Set the tail pointer and length */ skb_put(n, skb->len); if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len)) BUG(); copy_skb_header(n, skb); return n; } EXPORT_SYMBOL(skb_copy); /** * __pskb_copy_fclone - create copy of an sk_buff with private head. * @skb: buffer to copy * @headroom: headroom of new skb * @gfp_mask: allocation priority * @fclone: if true allocate the copy of the skb from the fclone * cache instead of the head cache; it is recommended to set this * to true for the cases where the copy will likely be cloned * * Make a copy of both an &sk_buff and part of its data, located * in header. Fragmented data remain shared. This is used when * the caller wishes to modify only header of &sk_buff and needs * private copy of the header to alter. Returns %NULL on failure * or the pointer to the buffer on success. * The returned buffer has a reference count of 1. */ struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom, gfp_t gfp_mask, bool fclone) { unsigned int size = skb_headlen(skb) + headroom; int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0); struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE); if (!n) goto out; /* Set the data pointer */ skb_reserve(n, headroom); /* Set the tail pointer and length */ skb_put(n, skb_headlen(skb)); /* Copy the bytes */ skb_copy_from_linear_data(skb, n->data, n->len); n->truesize += skb->data_len; n->data_len = skb->data_len; n->len = skb->len; if (skb_shinfo(skb)->nr_frags) { int i; if (skb_orphan_frags(skb, gfp_mask)) { kfree_skb(n); n = NULL; goto out; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i]; skb_frag_ref(skb, i); } skb_shinfo(n)->nr_frags = i; } if (skb_has_frag_list(skb)) { skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list; skb_clone_fraglist(n); } copy_skb_header(n, skb); out: return n; } EXPORT_SYMBOL(__pskb_copy_fclone); /** * pskb_expand_head - reallocate header of &sk_buff * @skb: buffer to reallocate * @nhead: room to add at head * @ntail: room to add at tail * @gfp_mask: allocation priority * * Expands (or creates identical copy, if @nhead and @ntail are zero) * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have * reference count of 1. Returns zero in the case of success or error, * if expansion failed. In the last case, &sk_buff is not changed. * * All the pointers pointing into skb header may change and must be * reloaded after call to this function. */ int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail, gfp_t gfp_mask) { int i, osize = skb_end_offset(skb); int size = osize + nhead + ntail; long off; u8 *data; BUG_ON(nhead < 0); if (skb_shared(skb)) BUG(); size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) goto nodata; size = SKB_WITH_OVERHEAD(ksize(data)); /* Copy only real data... and, alas, header. This should be * optimized for the cases when header is void. */ memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head); memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); /* * if shinfo is shared we must drop the old head gracefully, but if it * is not we can just drop the old head and let the existing refcount * be since all we did is relocate the values */ if (skb_cloned(skb)) { /* copy this zero copy skb frags */ if (skb_orphan_frags(skb, gfp_mask)) goto nofrags; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_frag_ref(skb, i); if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); skb_release_data(skb); } else { skb_free_head(skb); } off = (data + nhead) - skb->head; skb->head = data; skb->head_frag = 0; skb->data += off; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; off = nhead; #else skb->end = skb->head + size; #endif skb->tail += off; skb_headers_offset_update(skb, nhead); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; atomic_set(&skb_shinfo(skb)->dataref, 1); /* It is not generally safe to change skb->truesize. * For the moment, we really care of rx path, or * when skb is orphaned (not attached to a socket). */ if (!skb->sk || skb->destructor == sock_edemux) skb->truesize += size - osize; return 0; nofrags: kfree(data); nodata: return -ENOMEM; } EXPORT_SYMBOL(pskb_expand_head); /* Make private copy of skb with writable head and some headroom */ struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom) { struct sk_buff *skb2; int delta = headroom - skb_headroom(skb); if (delta <= 0) skb2 = pskb_copy(skb, GFP_ATOMIC); else { skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0, GFP_ATOMIC)) { kfree_skb(skb2); skb2 = NULL; } } return skb2; } EXPORT_SYMBOL(skb_realloc_headroom); /** * skb_copy_expand - copy and expand sk_buff * @skb: buffer to copy * @newheadroom: new free bytes at head * @newtailroom: new free bytes at tail * @gfp_mask: allocation priority * * Make a copy of both an &sk_buff and its data and while doing so * allocate additional space. * * This is used when the caller wishes to modify the data and needs a * private copy of the data to alter as well as more space for new fields. * Returns %NULL on failure or the pointer to the buffer * on success. The returned buffer has a reference count of 1. * * You must pass %GFP_ATOMIC as the allocation priority if this function * is called from an interrupt. */ struct sk_buff *skb_copy_expand(const struct sk_buff *skb, int newheadroom, int newtailroom, gfp_t gfp_mask) { /* * Allocate the copy buffer */ struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom, gfp_mask, skb_alloc_rx_flag(skb), NUMA_NO_NODE); int oldheadroom = skb_headroom(skb); int head_copy_len, head_copy_off; if (!n) return NULL; skb_reserve(n, newheadroom); /* Set the tail pointer and length */ skb_put(n, skb->len); head_copy_len = oldheadroom; head_copy_off = 0; if (newheadroom <= head_copy_len) head_copy_len = newheadroom; else head_copy_off = newheadroom - head_copy_len; /* Copy the linear header and data. */ if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off, skb->len + head_copy_len)) BUG(); copy_skb_header(n, skb); skb_headers_offset_update(n, newheadroom - oldheadroom); return n; } EXPORT_SYMBOL(skb_copy_expand); /** * skb_pad - zero pad the tail of an skb * @skb: buffer to pad * @pad: space to pad * * Ensure that a buffer is followed by a padding area that is zero * filled. Used by network drivers which may DMA or transfer data * beyond the buffer end onto the wire. * * May return error in out of memory cases. The skb is freed on error. */ int skb_pad(struct sk_buff *skb, int pad) { int err; int ntail; /* If the skbuff is non linear tailroom is always zero.. */ if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) { memset(skb->data+skb->len, 0, pad); return 0; } ntail = skb->data_len + pad - (skb->end - skb->tail); if (likely(skb_cloned(skb) || ntail > 0)) { err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC); if (unlikely(err)) goto free_skb; } /* FIXME: The use of this function with non-linear skb's really needs * to be audited. */ err = skb_linearize(skb); if (unlikely(err)) goto free_skb; memset(skb->data + skb->len, 0, pad); return 0; free_skb: kfree_skb(skb); return err; } EXPORT_SYMBOL(skb_pad); /** * pskb_put - add data to the tail of a potentially fragmented buffer * @skb: start of the buffer to use * @tail: tail fragment of the buffer to use * @len: amount of data to add * * This function extends the used data area of the potentially * fragmented buffer. @tail must be the last fragment of @skb -- or * @skb itself. If this would exceed the total buffer size the kernel * will panic. A pointer to the first byte of the extra data is * returned. */ unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len) { if (tail != skb) { skb->data_len += len; skb->len += len; } return skb_put(tail, len); } EXPORT_SYMBOL_GPL(pskb_put); /** * skb_put - add data to a buffer * @skb: buffer to use * @len: amount of data to add * * This function extends the used data area of the buffer. If this would * exceed the total buffer size the kernel will panic. A pointer to the * first byte of the extra data is returned. */ unsigned char *skb_put(struct sk_buff *skb, unsigned int len) { unsigned char *tmp = skb_tail_pointer(skb); SKB_LINEAR_ASSERT(skb); skb->tail += len; skb->len += len; if (unlikely(skb->tail > skb->end)) skb_over_panic(skb, len, __builtin_return_address(0)); return tmp; } EXPORT_SYMBOL(skb_put); /** * skb_push - add data to the start of a buffer * @skb: buffer to use * @len: amount of data to add * * This function extends the used data area of the buffer at the buffer * start. If this would exceed the total buffer headroom the kernel will * panic. A pointer to the first byte of the extra data is returned. */ unsigned char *skb_push(struct sk_buff *skb, unsigned int len) { skb->data -= len; skb->len += len; if (unlikely(skb->data<skb->head)) skb_under_panic(skb, len, __builtin_return_address(0)); return skb->data; } EXPORT_SYMBOL(skb_push); /** * skb_pull - remove data from the start of a buffer * @skb: buffer to use * @len: amount of data to remove * * This function removes data from the start of a buffer, returning * the memory to the headroom. A pointer to the next data in the buffer * is returned. Once the data has been pulled future pushes will overwrite * the old data. */ unsigned char *skb_pull(struct sk_buff *skb, unsigned int len) { return skb_pull_inline(skb, len); } EXPORT_SYMBOL(skb_pull); /** * skb_trim - remove end from a buffer * @skb: buffer to alter * @len: new length * * Cut the length of a buffer down by removing data from the tail. If * the buffer is already under the length specified it is not modified. * The skb must be linear. */ void skb_trim(struct sk_buff *skb, unsigned int len) { if (skb->len > len) __skb_trim(skb, len); } EXPORT_SYMBOL(skb_trim); /* Trims skb to length len. It can change skb pointers. */ int ___pskb_trim(struct sk_buff *skb, unsigned int len) { struct sk_buff **fragp; struct sk_buff *frag; int offset = skb_headlen(skb); int nfrags = skb_shinfo(skb)->nr_frags; int i; int err; if (skb_cloned(skb) && unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))) return err; i = 0; if (offset >= len) goto drop_pages; for (; i < nfrags; i++) { int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]); if (end < len) { offset = end; continue; } skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset); drop_pages: skb_shinfo(skb)->nr_frags = i; for (; i < nfrags; i++) skb_frag_unref(skb, i); if (skb_has_frag_list(skb)) skb_drop_fraglist(skb); goto done; } for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp); fragp = &frag->next) { int end = offset + frag->len; if (skb_shared(frag)) { struct sk_buff *nfrag; nfrag = skb_clone(frag, GFP_ATOMIC); if (unlikely(!nfrag)) return -ENOMEM; nfrag->next = frag->next; consume_skb(frag); frag = nfrag; *fragp = frag; } if (end < len) { offset = end; continue; } if (end > len && unlikely((err = pskb_trim(frag, len - offset)))) return err; if (frag->next) skb_drop_list(&frag->next); break; } done: if (len > skb_headlen(skb)) { skb->data_len -= skb->len - len; skb->len = len; } else { skb->len = len; skb->data_len = 0; skb_set_tail_pointer(skb, len); } return 0; } EXPORT_SYMBOL(___pskb_trim); /** * __pskb_pull_tail - advance tail of skb header * @skb: buffer to reallocate * @delta: number of bytes to advance tail * * The function makes a sense only on a fragmented &sk_buff, * it expands header moving its tail forward and copying necessary * data from fragmented part. * * &sk_buff MUST have reference count of 1. * * Returns %NULL (and &sk_buff does not change) if pull failed * or value of new tail of skb in the case of success. * * All the pointers pointing into skb header may change and must be * reloaded after call to this function. */ /* Moves tail of skb head forward, copying data from fragmented part, * when it is necessary. * 1. It may fail due to malloc failure. * 2. It may change skb pointers. * * It is pretty complicated. Luckily, it is called only in exceptional cases. */ unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta) { /* If skb has not enough free space at tail, get new one * plus 128 bytes for future expansions. If we have enough * room at tail, reallocate without expansion only if skb is cloned. */ int i, k, eat = (skb->tail + delta) - skb->end; if (eat > 0 || skb_cloned(skb)) { if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0, GFP_ATOMIC)) return NULL; } if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta)) BUG(); /* Optimization: no fragments, no reasons to preestimate * size of pulled pages. Superb. */ if (!skb_has_frag_list(skb)) goto pull_pages; /* Estimate size of pulled pages. */ eat = delta; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (size >= eat) goto pull_pages; eat -= size; } /* If we need update frag list, we are in troubles. * Certainly, it possible to add an offset to skb data, * but taking into account that pulling is expected to * be very rare operation, it is worth to fight against * further bloating skb head and crucify ourselves here instead. * Pure masohism, indeed. 8)8) */ if (eat) { struct sk_buff *list = skb_shinfo(skb)->frag_list; struct sk_buff *clone = NULL; struct sk_buff *insp = NULL; do { BUG_ON(!list); if (list->len <= eat) { /* Eaten as whole. */ eat -= list->len; list = list->next; insp = list; } else { /* Eaten partially. */ if (skb_shared(list)) { /* Sucks! We need to fork list. :-( */ clone = skb_clone(list, GFP_ATOMIC); if (!clone) return NULL; insp = list->next; list = clone; } else { /* This may be pulled without * problems. */ insp = list; } if (!pskb_pull(list, eat)) { kfree_skb(clone); return NULL; } break; } } while (eat); /* Free pulled out fragments. */ while ((list = skb_shinfo(skb)->frag_list) != insp) { skb_shinfo(skb)->frag_list = list->next; kfree_skb(list); } /* And insert new clone at head. */ if (clone) { clone->next = list; skb_shinfo(skb)->frag_list = clone; } } /* Success! Now we may commit changes to skb data. */ pull_pages: eat = delta; k = 0; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (size <= eat) { skb_frag_unref(skb, i); eat -= size; } else { skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i]; if (eat) { skb_shinfo(skb)->frags[k].page_offset += eat; skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat); eat = 0; } k++; } } skb_shinfo(skb)->nr_frags = k; skb->tail += delta; skb->data_len -= delta; return skb_tail_pointer(skb); } EXPORT_SYMBOL(__pskb_pull_tail); /** * skb_copy_bits - copy bits from skb to kernel buffer * @skb: source skb * @offset: offset in source * @to: destination buffer * @len: number of bytes to copy * * Copy the specified number of bytes from the source skb to the * destination buffer. * * CAUTION ! : * If its prototype is ever changed, * check arch/{*}/net/{*}.S files, * since it is called from BPF assembly code. */ int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len) { int start = skb_headlen(skb); struct sk_buff *frag_iter; int i, copy; if (offset > (int)skb->len - len) goto fault; /* Copy header. */ if ((copy = start - offset) > 0) { if (copy > len) copy = len; skb_copy_from_linear_data_offset(skb, offset, to, copy); if ((len -= copy) == 0) return 0; offset += copy; to += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; skb_frag_t *f = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(f); if ((copy = end - offset) > 0) { u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(f)); memcpy(to, vaddr + f->page_offset + offset - start, copy); kunmap_atomic(vaddr); if ((len -= copy) == 0) return 0; offset += copy; to += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_copy_bits(frag_iter, offset - start, to, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; to += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_bits); /* * Callback from splice_to_pipe(), if we need to release some pages * at the end of the spd in case we error'ed out in filling the pipe. */ static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i) { put_page(spd->pages[i]); } static struct page *linear_to_page(struct page *page, unsigned int *len, unsigned int *offset, struct sock *sk) { struct page_frag *pfrag = sk_page_frag(sk); if (!sk_page_frag_refill(sk, pfrag)) return NULL; *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset); memcpy(page_address(pfrag->page) + pfrag->offset, page_address(page) + *offset, *len); *offset = pfrag->offset; pfrag->offset += *len; return pfrag->page; } static bool spd_can_coalesce(const struct splice_pipe_desc *spd, struct page *page, unsigned int offset) { return spd->nr_pages && spd->pages[spd->nr_pages - 1] == page && (spd->partial[spd->nr_pages - 1].offset + spd->partial[spd->nr_pages - 1].len == offset); } /* * Fill page/offset/length into spd, if it can hold more pages. */ static bool spd_fill_page(struct splice_pipe_desc *spd, struct pipe_inode_info *pipe, struct page *page, unsigned int *len, unsigned int offset, bool linear, struct sock *sk) { if (unlikely(spd->nr_pages == MAX_SKB_FRAGS)) return true; if (linear) { page = linear_to_page(page, len, &offset, sk); if (!page) return true; } if (spd_can_coalesce(spd, page, offset)) { spd->partial[spd->nr_pages - 1].len += *len; return false; } get_page(page); spd->pages[spd->nr_pages] = page; spd->partial[spd->nr_pages].len = *len; spd->partial[spd->nr_pages].offset = offset; spd->nr_pages++; return false; } static bool __splice_segment(struct page *page, unsigned int poff, unsigned int plen, unsigned int *off, unsigned int *len, struct splice_pipe_desc *spd, bool linear, struct sock *sk, struct pipe_inode_info *pipe) { if (!*len) return true; /* skip this segment if already processed */ if (*off >= plen) { *off -= plen; return false; } /* ignore any bits we already processed */ poff += *off; plen -= *off; *off = 0; do { unsigned int flen = min(*len, plen); if (spd_fill_page(spd, pipe, page, &flen, poff, linear, sk)) return true; poff += flen; plen -= flen; *len -= flen; } while (*len && plen); return false; } /* * Map linear and fragment data from the skb to spd. It reports true if the * pipe is full or if we already spliced the requested length. */ static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe, unsigned int *offset, unsigned int *len, struct splice_pipe_desc *spd, struct sock *sk) { int seg; struct sk_buff *iter; /* map the linear part : * If skb->head_frag is set, this 'linear' part is backed by a * fragment, and if the head is not shared with any clones then * we can avoid a copy since we own the head portion of this page. */ if (__splice_segment(virt_to_page(skb->data), (unsigned long) skb->data & (PAGE_SIZE - 1), skb_headlen(skb), offset, len, spd, skb_head_is_locked(skb), sk, pipe)) return true; /* * then map the fragments */ for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) { const skb_frag_t *f = &skb_shinfo(skb)->frags[seg]; if (__splice_segment(skb_frag_page(f), f->page_offset, skb_frag_size(f), offset, len, spd, false, sk, pipe)) return true; } skb_walk_frags(skb, iter) { if (*offset >= iter->len) { *offset -= iter->len; continue; } /* __skb_splice_bits() only fails if the output has no room * left, so no point in going over the frag_list for the error * case. */ if (__skb_splice_bits(iter, pipe, offset, len, spd, sk)) return true; } return false; } /* * Map data from the skb to a pipe. Should handle both the linear part, * the fragments, and the frag list. */ int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset, struct pipe_inode_info *pipe, unsigned int tlen, unsigned int flags) { struct partial_page partial[MAX_SKB_FRAGS]; struct page *pages[MAX_SKB_FRAGS]; struct splice_pipe_desc spd = { .pages = pages, .partial = partial, .nr_pages_max = MAX_SKB_FRAGS, .flags = flags, .ops = &nosteal_pipe_buf_ops, .spd_release = sock_spd_release, }; int ret = 0; __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk); if (spd.nr_pages) ret = splice_to_pipe(pipe, &spd); return ret; } EXPORT_SYMBOL_GPL(skb_splice_bits); /** * skb_store_bits - store bits from kernel buffer to skb * @skb: destination buffer * @offset: offset in destination * @from: source buffer * @len: number of bytes to copy * * Copy the specified number of bytes from the source buffer to the * destination skb. This function handles all the messy bits of * traversing fragment lists and such. */ int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len) { int start = skb_headlen(skb); struct sk_buff *frag_iter; int i, copy; if (offset > (int)skb->len - len) goto fault; if ((copy = start - offset) > 0) { if (copy > len) copy = len; skb_copy_to_linear_data_offset(skb, offset, from, copy); if ((len -= copy) == 0) return 0; offset += copy; from += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; int end; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); memcpy(vaddr + frag->page_offset + offset - start, from, copy); kunmap_atomic(vaddr); if ((len -= copy) == 0) return 0; offset += copy; from += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_store_bits(frag_iter, offset - start, from, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; from += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_store_bits); /* Checksum skb data. */ __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len, __wsum csum, const struct skb_checksum_ops *ops) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int pos = 0; /* Checksum header. */ if (copy > 0) { if (copy > len) copy = len; csum = ops->update(skb->data + offset, copy, csum); if ((len -= copy) == 0) return csum; offset += copy; pos = copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { __wsum csum2; u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); csum2 = ops->update(vaddr + frag->page_offset + offset - start, copy, 0); kunmap_atomic(vaddr); csum = ops->combine(csum, csum2, pos, copy); if (!(len -= copy)) return csum; offset += copy; pos += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { __wsum csum2; if (copy > len) copy = len; csum2 = __skb_checksum(frag_iter, offset - start, copy, 0, ops); csum = ops->combine(csum, csum2, pos, copy); if ((len -= copy) == 0) return csum; offset += copy; pos += copy; } start = end; } BUG_ON(len); return csum; } EXPORT_SYMBOL(__skb_checksum); __wsum skb_checksum(const struct sk_buff *skb, int offset, int len, __wsum csum) { const struct skb_checksum_ops ops = { .update = csum_partial_ext, .combine = csum_block_add_ext, }; return __skb_checksum(skb, offset, len, csum, &ops); } EXPORT_SYMBOL(skb_checksum); /* Both of above in one bottle. */ __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset, u8 *to, int len, __wsum csum) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int pos = 0; /* Copy header. */ if (copy > 0) { if (copy > len) copy = len; csum = csum_partial_copy_nocheck(skb->data + offset, to, copy, csum); if ((len -= copy) == 0) return csum; offset += copy; to += copy; pos = copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; WARN_ON(start > offset + len); end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]); if ((copy = end - offset) > 0) { __wsum csum2; u8 *vaddr; skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); csum2 = csum_partial_copy_nocheck(vaddr + frag->page_offset + offset - start, to, copy, 0); kunmap_atomic(vaddr); csum = csum_block_add(csum, csum2, pos); if (!(len -= copy)) return csum; offset += copy; to += copy; pos += copy; } start = end; } skb_walk_frags(skb, frag_iter) { __wsum csum2; int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; csum2 = skb_copy_and_csum_bits(frag_iter, offset - start, to, copy, 0); csum = csum_block_add(csum, csum2, pos); if ((len -= copy) == 0) return csum; offset += copy; to += copy; pos += copy; } start = end; } BUG_ON(len); return csum; } EXPORT_SYMBOL(skb_copy_and_csum_bits); /** * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy() * @from: source buffer * * Calculates the amount of linear headroom needed in the 'to' skb passed * into skb_zerocopy(). */ unsigned int skb_zerocopy_headlen(const struct sk_buff *from) { unsigned int hlen = 0; if (!from->head_frag || skb_headlen(from) < L1_CACHE_BYTES || skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) hlen = skb_headlen(from); if (skb_has_frag_list(from)) hlen = from->len; return hlen; } EXPORT_SYMBOL_GPL(skb_zerocopy_headlen); /** * skb_zerocopy - Zero copy skb to skb * @to: destination buffer * @from: source buffer * @len: number of bytes to copy from source buffer * @hlen: size of linear headroom in destination buffer * * Copies up to `len` bytes from `from` to `to` by creating references * to the frags in the source buffer. * * The `hlen` as calculated by skb_zerocopy_headlen() specifies the * headroom in the `to` buffer. * * Return value: * 0: everything is OK * -ENOMEM: couldn't orphan frags of @from due to lack of memory * -EFAULT: skb_copy_bits() found some problem with skb geometry */ int skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen) { int i, j = 0; int plen = 0; /* length of skb->head fragment */ int ret; struct page *page; unsigned int offset; BUG_ON(!from->head_frag && !hlen); /* dont bother with small payloads */ if (len <= skb_tailroom(to)) return skb_copy_bits(from, 0, skb_put(to, len), len); if (hlen) { ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen); if (unlikely(ret)) return ret; len -= hlen; } else { plen = min_t(int, skb_headlen(from), len); if (plen) { page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); __skb_fill_page_desc(to, 0, page, offset, plen); get_page(page); j = 1; len -= plen; } } to->truesize += len + plen; to->len += len + plen; to->data_len += len + plen; if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) { skb_tx_error(from); return -ENOMEM; } for (i = 0; i < skb_shinfo(from)->nr_frags; i++) { if (!len) break; skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i]; skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len); len -= skb_shinfo(to)->frags[j].size; skb_frag_ref(to, j); j++; } skb_shinfo(to)->nr_frags = j; return 0; } EXPORT_SYMBOL_GPL(skb_zerocopy); void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to) { __wsum csum; long csstart; if (skb->ip_summed == CHECKSUM_PARTIAL) csstart = skb_checksum_start_offset(skb); else csstart = skb_headlen(skb); BUG_ON(csstart > skb_headlen(skb)); skb_copy_from_linear_data(skb, to, csstart); csum = 0; if (csstart != skb->len) csum = skb_copy_and_csum_bits(skb, csstart, to + csstart, skb->len - csstart, 0); if (skb->ip_summed == CHECKSUM_PARTIAL) { long csstuff = csstart + skb->csum_offset; *((__sum16 *)(to + csstuff)) = csum_fold(csum); } } EXPORT_SYMBOL(skb_copy_and_csum_dev); /** * skb_dequeue - remove from the head of the queue * @list: list to dequeue from * * Remove the head of the list. The list lock is taken so the function * may be used safely with other locking list functions. The head item is * returned or %NULL if the list is empty. */ struct sk_buff *skb_dequeue(struct sk_buff_head *list) { unsigned long flags; struct sk_buff *result; spin_lock_irqsave(&list->lock, flags); result = __skb_dequeue(list); spin_unlock_irqrestore(&list->lock, flags); return result; } EXPORT_SYMBOL(skb_dequeue); /** * skb_dequeue_tail - remove from the tail of the queue * @list: list to dequeue from * * Remove the tail of the list. The list lock is taken so the function * may be used safely with other locking list functions. The tail item is * returned or %NULL if the list is empty. */ struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list) { unsigned long flags; struct sk_buff *result; spin_lock_irqsave(&list->lock, flags); result = __skb_dequeue_tail(list); spin_unlock_irqrestore(&list->lock, flags); return result; } EXPORT_SYMBOL(skb_dequeue_tail); /** * skb_queue_purge - empty a list * @list: list to empty * * Delete all buffers on an &sk_buff list. Each buffer is removed from * the list and one reference dropped. This function takes the list * lock and is atomic with respect to other list locking functions. */ void skb_queue_purge(struct sk_buff_head *list) { struct sk_buff *skb; while ((skb = skb_dequeue(list)) != NULL) kfree_skb(skb); } EXPORT_SYMBOL(skb_queue_purge); /** * skb_rbtree_purge - empty a skb rbtree * @root: root of the rbtree to empty * * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from * the list and one reference dropped. This function does not take * any lock. Synchronization should be handled by the caller (e.g., TCP * out-of-order queue is protected by the socket lock). */ void skb_rbtree_purge(struct rb_root *root) { struct sk_buff *skb, *next; rbtree_postorder_for_each_entry_safe(skb, next, root, rbnode) kfree_skb(skb); *root = RB_ROOT; } /** * skb_queue_head - queue a buffer at the list head * @list: list to use * @newsk: buffer to queue * * Queue a buffer at the start of the list. This function takes the * list lock and can be used safely with other locking &sk_buff functions * safely. * * A buffer cannot be placed on two lists at the same time. */ void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_head(list, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_queue_head); /** * skb_queue_tail - queue a buffer at the list tail * @list: list to use * @newsk: buffer to queue * * Queue a buffer at the tail of the list. This function takes the * list lock and can be used safely with other locking &sk_buff functions * safely. * * A buffer cannot be placed on two lists at the same time. */ void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_tail(list, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_queue_tail); /** * skb_unlink - remove a buffer from a list * @skb: buffer to remove * @list: list to use * * Remove a packet from a list. The list locks are taken and this * function is atomic with respect to other list locked calls * * You must know what list the SKB is on. */ void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_unlink(skb, list); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_unlink); /** * skb_append - append a buffer * @old: buffer to insert after * @newsk: buffer to insert * @list: list to use * * Place a packet after a given packet in a list. The list locks are taken * and this function is atomic with respect to other list locked calls. * A buffer cannot be placed on two lists at the same time. */ void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_after(list, old, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_append); /** * skb_insert - insert a buffer * @old: buffer to insert before * @newsk: buffer to insert * @list: list to use * * Place a packet before a given packet in a list. The list locks are * taken and this function is atomic with respect to other list locked * calls. * * A buffer cannot be placed on two lists at the same time. */ void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_insert(newsk, old->prev, old, list); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_insert); static inline void skb_split_inside_header(struct sk_buff *skb, struct sk_buff* skb1, const u32 len, const int pos) { int i; skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len), pos - len); /* And move data appendix as is. */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i]; skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags; skb_shinfo(skb)->nr_frags = 0; skb1->data_len = skb->data_len; skb1->len += skb1->data_len; skb->data_len = 0; skb->len = len; skb_set_tail_pointer(skb, len); } static inline void skb_split_no_header(struct sk_buff *skb, struct sk_buff* skb1, const u32 len, int pos) { int i, k = 0; const int nfrags = skb_shinfo(skb)->nr_frags; skb_shinfo(skb)->nr_frags = 0; skb1->len = skb1->data_len = skb->len - len; skb->len = len; skb->data_len = len - pos; for (i = 0; i < nfrags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (pos + size > len) { skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i]; if (pos < len) { /* Split frag. * We have two variants in this case: * 1. Move all the frag to the second * part, if it is possible. F.e. * this approach is mandatory for TUX, * where splitting is expensive. * 2. Split is accurately. We make this. */ skb_frag_ref(skb, i); skb_shinfo(skb1)->frags[0].page_offset += len - pos; skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos); skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos); skb_shinfo(skb)->nr_frags++; } k++; } else skb_shinfo(skb)->nr_frags++; pos += size; } skb_shinfo(skb1)->nr_frags = k; } /** * skb_split - Split fragmented skb to two parts at length len. * @skb: the buffer to split * @skb1: the buffer to receive the second part * @len: new length for skb */ void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len) { int pos = skb_headlen(skb); skb_shinfo(skb1)->tx_flags = skb_shinfo(skb)->tx_flags & SKBTX_SHARED_FRAG; if (len < pos) /* Split line is inside header. */ skb_split_inside_header(skb, skb1, len, pos); else /* Second chunk has no header, nothing to copy. */ skb_split_no_header(skb, skb1, len, pos); } EXPORT_SYMBOL(skb_split); /* Shifting from/to a cloned skb is a no-go. * * Caller cannot keep skb_shinfo related pointers past calling here! */ static int skb_prepare_for_shift(struct sk_buff *skb) { return skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC); } /** * skb_shift - Shifts paged data partially from skb to another * @tgt: buffer into which tail data gets added * @skb: buffer from which the paged data comes from * @shiftlen: shift up to this many bytes * * Attempts to shift up to shiftlen worth of bytes, which may be less than * the length of the skb, from skb to tgt. Returns number bytes shifted. * It's up to caller to free skb if everything was shifted. * * If @tgt runs out of frags, the whole operation is aborted. * * Skb cannot include anything else but paged data while tgt is allowed * to have non-paged data as well. * * TODO: full sized shift could be optimized but that would need * specialized skb free'er to handle frags without up-to-date nr_frags. */ int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen) { int from, to, merge, todo; struct skb_frag_struct *fragfrom, *fragto; BUG_ON(shiftlen > skb->len); if (skb_headlen(skb)) return 0; todo = shiftlen; from = 0; to = skb_shinfo(tgt)->nr_frags; fragfrom = &skb_shinfo(skb)->frags[from]; /* Actual merge is delayed until the point when we know we can * commit all, so that we don't have to undo partial changes */ if (!to || !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom), fragfrom->page_offset)) { merge = -1; } else { merge = to - 1; todo -= skb_frag_size(fragfrom); if (todo < 0) { if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; /* All previous frag pointers might be stale! */ fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, shiftlen); skb_frag_size_sub(fragfrom, shiftlen); fragfrom->page_offset += shiftlen; goto onlymerged; } from++; } /* Skip full, not-fitting skb to avoid expensive operations */ if ((shiftlen == skb->len) && (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to)) return 0; if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) { if (to == MAX_SKB_FRAGS) return 0; fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[to]; if (todo >= skb_frag_size(fragfrom)) { *fragto = *fragfrom; todo -= skb_frag_size(fragfrom); from++; to++; } else { __skb_frag_ref(fragfrom); fragto->page = fragfrom->page; fragto->page_offset = fragfrom->page_offset; skb_frag_size_set(fragto, todo); fragfrom->page_offset += todo; skb_frag_size_sub(fragfrom, todo); todo = 0; to++; break; } } /* Ready to "commit" this state change to tgt */ skb_shinfo(tgt)->nr_frags = to; if (merge >= 0) { fragfrom = &skb_shinfo(skb)->frags[0]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, skb_frag_size(fragfrom)); __skb_frag_unref(fragfrom); } /* Reposition in the original skb */ to = 0; while (from < skb_shinfo(skb)->nr_frags) skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++]; skb_shinfo(skb)->nr_frags = to; BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags); onlymerged: /* Most likely the tgt won't ever need its checksum anymore, skb on * the other hand might need it if it needs to be resent */ tgt->ip_summed = CHECKSUM_PARTIAL; skb->ip_summed = CHECKSUM_PARTIAL; /* Yak, is it really working this way? Some helper please? */ skb->len -= shiftlen; skb->data_len -= shiftlen; skb->truesize -= shiftlen; tgt->len += shiftlen; tgt->data_len += shiftlen; tgt->truesize += shiftlen; return shiftlen; } /** * skb_prepare_seq_read - Prepare a sequential read of skb data * @skb: the buffer to read * @from: lower offset of data to be read * @to: upper offset of data to be read * @st: state variable * * Initializes the specified state variable. Must be called before * invoking skb_seq_read() for the first time. */ void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from, unsigned int to, struct skb_seq_state *st) { st->lower_offset = from; st->upper_offset = to; st->root_skb = st->cur_skb = skb; st->frag_idx = st->stepped_offset = 0; st->frag_data = NULL; } EXPORT_SYMBOL(skb_prepare_seq_read); /** * skb_seq_read - Sequentially read skb data * @consumed: number of bytes consumed by the caller so far * @data: destination pointer for data to be returned * @st: state variable * * Reads a block of skb data at @consumed relative to the * lower offset specified to skb_prepare_seq_read(). Assigns * the head of the data block to @data and returns the length * of the block or 0 if the end of the skb data or the upper * offset has been reached. * * The caller is not required to consume all of the data * returned, i.e. @consumed is typically set to the number * of bytes already consumed and the next call to * skb_seq_read() will return the remaining part of the block. * * Note 1: The size of each block of data returned can be arbitrary, * this limitation is the cost for zerocopy sequential * reads of potentially non linear data. * * Note 2: Fragment lists within fragments are not implemented * at the moment, state->root_skb could be replaced with * a stack for this purpose. */ unsigned int skb_seq_read(unsigned int consumed, const u8 **data, struct skb_seq_state *st) { unsigned int block_limit, abs_offset = consumed + st->lower_offset; skb_frag_t *frag; if (unlikely(abs_offset >= st->upper_offset)) { if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } return 0; } next_skb: block_limit = skb_headlen(st->cur_skb) + st->stepped_offset; if (abs_offset < block_limit && !st->frag_data) { *data = st->cur_skb->data + (abs_offset - st->stepped_offset); return block_limit - abs_offset; } if (st->frag_idx == 0 && !st->frag_data) st->stepped_offset += skb_headlen(st->cur_skb); while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) { frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx]; block_limit = skb_frag_size(frag) + st->stepped_offset; if (abs_offset < block_limit) { if (!st->frag_data) st->frag_data = kmap_atomic(skb_frag_page(frag)); *data = (u8 *) st->frag_data + frag->page_offset + (abs_offset - st->stepped_offset); return block_limit - abs_offset; } if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } st->frag_idx++; st->stepped_offset += skb_frag_size(frag); } if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) { st->cur_skb = skb_shinfo(st->root_skb)->frag_list; st->frag_idx = 0; goto next_skb; } else if (st->cur_skb->next) { st->cur_skb = st->cur_skb->next; st->frag_idx = 0; goto next_skb; } return 0; } EXPORT_SYMBOL(skb_seq_read); /** * skb_abort_seq_read - Abort a sequential read of skb data * @st: state variable * * Must be called if skb_seq_read() was not called until it * returned 0. */ void skb_abort_seq_read(struct skb_seq_state *st) { if (st->frag_data) kunmap_atomic(st->frag_data); } EXPORT_SYMBOL(skb_abort_seq_read); #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb)) static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text, struct ts_config *conf, struct ts_state *state) { return skb_seq_read(offset, text, TS_SKB_CB(state)); } static void skb_ts_finish(struct ts_config *conf, struct ts_state *state) { skb_abort_seq_read(TS_SKB_CB(state)); } /** * skb_find_text - Find a text pattern in skb data * @skb: the buffer to look in * @from: search offset * @to: search limit * @config: textsearch configuration * * Finds a pattern in the skb data according to the specified * textsearch configuration. Use textsearch_next() to retrieve * subsequent occurrences of the pattern. Returns the offset * to the first occurrence or UINT_MAX if no match was found. */ unsigned int skb_find_text(struct sk_buff *skb, unsigned int from, unsigned int to, struct ts_config *config) { struct ts_state state; unsigned int ret; config->get_next_block = skb_ts_get_next_block; config->finish = skb_ts_finish; skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state)); ret = textsearch_find(config, &state); return (ret <= to - from ? ret : UINT_MAX); } EXPORT_SYMBOL(skb_find_text); /** * skb_append_datato_frags - append the user data to a skb * @sk: sock structure * @skb: skb structure to be appended with user data. * @getfrag: call back function to be used for getting the user data * @from: pointer to user message iov * @length: length of the iov message * * Description: This procedure append the user data in the fragment part * of the skb if any page alloc fails user this procedure returns -ENOMEM */ int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb, int (*getfrag)(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length) { int frg_cnt = skb_shinfo(skb)->nr_frags; int copy; int offset = 0; int ret; struct page_frag *pfrag = &current->task_frag; do { /* Return error if we don't have space for new frag */ if (frg_cnt >= MAX_SKB_FRAGS) return -EMSGSIZE; if (!sk_page_frag_refill(sk, pfrag)) return -ENOMEM; /* copy the user data to page */ copy = min_t(int, length, pfrag->size - pfrag->offset); ret = getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, 0, skb); if (ret < 0) return -EFAULT; /* copy was successful so update the size parameters */ skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset, copy); frg_cnt++; pfrag->offset += copy; get_page(pfrag->page); skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); skb->len += copy; skb->data_len += copy; offset += copy; length -= copy; } while (length > 0); return 0; } EXPORT_SYMBOL(skb_append_datato_frags); int skb_append_pagefrags(struct sk_buff *skb, struct page *page, int offset, size_t size) { int i = skb_shinfo(skb)->nr_frags; if (skb_can_coalesce(skb, i, page, offset)) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size); } else if (i < MAX_SKB_FRAGS) { get_page(page); skb_fill_page_desc(skb, i, page, offset, size); } else { return -EMSGSIZE; } return 0; } EXPORT_SYMBOL_GPL(skb_append_pagefrags); /** * skb_pull_rcsum - pull skb and update receive checksum * @skb: buffer to update * @len: length of data pulled * * This function performs an skb_pull on the packet and updates * the CHECKSUM_COMPLETE checksum. It should be used on * receive path processing instead of skb_pull unless you know * that the checksum difference is zero (e.g., a valid IP header) * or you are setting ip_summed to CHECKSUM_NONE. */ unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len) { unsigned char *data = skb->data; BUG_ON(len > skb->len); __skb_pull(skb, len); skb_postpull_rcsum(skb, data, len); return skb->data; } EXPORT_SYMBOL_GPL(skb_pull_rcsum); /** * skb_segment - Perform protocol segmentation on skb. * @head_skb: buffer to segment * @features: features for the output path (see dev->features) * * This function performs segmentation on the given skb. It returns * a pointer to the first in a list of new skbs for the segments. * In case of error it returns ERR_PTR(err). */ struct sk_buff *skb_segment(struct sk_buff *head_skb, netdev_features_t features) { struct sk_buff *segs = NULL; struct sk_buff *tail = NULL; struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; skb_frag_t *frag = skb_shinfo(head_skb)->frags; unsigned int mss = skb_shinfo(head_skb)->gso_size; unsigned int doffset = head_skb->data - skb_mac_header(head_skb); struct sk_buff *frag_skb = head_skb; unsigned int offset = doffset; unsigned int tnl_hlen = skb_tnl_header_len(head_skb); unsigned int partial_segs = 0; unsigned int headroom; unsigned int len = head_skb->len; __be16 proto; bool csum, sg; int nfrags = skb_shinfo(head_skb)->nr_frags; int err = -ENOMEM; int i = 0; int pos; int dummy; __skb_push(head_skb, doffset); proto = skb_network_protocol(head_skb, &dummy); if (unlikely(!proto)) return ERR_PTR(-EINVAL); sg = !!(features & NETIF_F_SG); csum = !!can_checksum_protocol(features, proto); if (sg && csum && (mss != GSO_BY_FRAGS)) { if (!(features & NETIF_F_GSO_PARTIAL)) { struct sk_buff *iter; if (!list_skb || !net_gso_ok(features, skb_shinfo(head_skb)->gso_type)) goto normal; /* Split the buffer at the frag_list pointer. * This is based on the assumption that all * buffers in the chain excluding the last * containing the same amount of data. */ skb_walk_frags(head_skb, iter) { if (skb_headlen(iter)) goto normal; len -= iter->len; } } /* GSO partial only requires that we trim off any excess that * doesn't fit into an MSS sized block, so take care of that * now. */ partial_segs = len / mss; if (partial_segs > 1) mss *= partial_segs; else partial_segs = 0; } normal: headroom = skb_headroom(head_skb); pos = skb_headlen(head_skb); do { struct sk_buff *nskb; skb_frag_t *nskb_frag; int hsize; int size; if (unlikely(mss == GSO_BY_FRAGS)) { len = list_skb->len; } else { len = head_skb->len - offset; if (len > mss) len = mss; } hsize = skb_headlen(head_skb) - offset; if (hsize < 0) hsize = 0; if (hsize > len || !sg) hsize = len; if (!hsize && i >= nfrags && skb_headlen(list_skb) && (skb_headlen(list_skb) == len || sg)) { BUG_ON(skb_headlen(list_skb) > len); i = 0; nfrags = skb_shinfo(list_skb)->nr_frags; frag = skb_shinfo(list_skb)->frags; frag_skb = list_skb; pos += skb_headlen(list_skb); while (pos < offset + len) { BUG_ON(i >= nfrags); size = skb_frag_size(frag); if (pos + size > offset + len) break; i++; pos += size; frag++; } nskb = skb_clone(list_skb, GFP_ATOMIC); list_skb = list_skb->next; if (unlikely(!nskb)) goto err; if (unlikely(pskb_trim(nskb, len))) { kfree_skb(nskb); goto err; } hsize = skb_end_offset(nskb); if (skb_cow_head(nskb, doffset + headroom)) { kfree_skb(nskb); goto err; } nskb->truesize += skb_end_offset(nskb) - hsize; skb_release_head_state(nskb); __skb_push(nskb, doffset); } else { nskb = __alloc_skb(hsize + doffset + headroom, GFP_ATOMIC, skb_alloc_rx_flag(head_skb), NUMA_NO_NODE); if (unlikely(!nskb)) goto err; skb_reserve(nskb, headroom); __skb_put(nskb, doffset); } if (segs) tail->next = nskb; else segs = nskb; tail = nskb; __copy_skb_header(nskb, head_skb); skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); skb_reset_mac_len(nskb); skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, nskb->data - tnl_hlen, doffset + tnl_hlen); if (nskb->len == len + doffset) goto perform_csum_check; if (!sg) { if (!nskb->remcsum_offload) nskb->ip_summed = CHECKSUM_NONE; SKB_GSO_CB(nskb)->csum = skb_copy_and_csum_bits(head_skb, offset, skb_put(nskb, len), len, 0); SKB_GSO_CB(nskb)->csum_start = skb_headroom(nskb) + doffset; continue; } nskb_frag = skb_shinfo(nskb)->frags; skb_copy_from_linear_data_offset(head_skb, offset, skb_put(nskb, hsize), hsize); skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & SKBTX_SHARED_FRAG; while (pos < offset + len) { if (i >= nfrags) { BUG_ON(skb_headlen(list_skb)); i = 0; nfrags = skb_shinfo(list_skb)->nr_frags; frag = skb_shinfo(list_skb)->frags; frag_skb = list_skb; BUG_ON(!nfrags); list_skb = list_skb->next; } if (unlikely(skb_shinfo(nskb)->nr_frags >= MAX_SKB_FRAGS)) { net_warn_ratelimited( "skb_segment: too many frags: %u %u\n", pos, mss); goto err; } if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC))) goto err; *nskb_frag = *frag; __skb_frag_ref(nskb_frag); size = skb_frag_size(nskb_frag); if (pos < offset) { nskb_frag->page_offset += offset - pos; skb_frag_size_sub(nskb_frag, offset - pos); } skb_shinfo(nskb)->nr_frags++; if (pos + size <= offset + len) { i++; frag++; pos += size; } else { skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); goto skip_fraglist; } nskb_frag++; } skip_fraglist: nskb->data_len = len - hsize; nskb->len += nskb->data_len; nskb->truesize += nskb->data_len; perform_csum_check: if (!csum) { if (skb_has_shared_frag(nskb)) { err = __skb_linearize(nskb); if (err) goto err; } if (!nskb->remcsum_offload) nskb->ip_summed = CHECKSUM_NONE; SKB_GSO_CB(nskb)->csum = skb_checksum(nskb, doffset, nskb->len - doffset, 0); SKB_GSO_CB(nskb)->csum_start = skb_headroom(nskb) + doffset; } } while ((offset += len) < head_skb->len); /* Some callers want to get the end of the list. * Put it in segs->prev to avoid walking the list. * (see validate_xmit_skb_list() for example) */ segs->prev = tail; if (partial_segs) { struct sk_buff *iter; int type = skb_shinfo(head_skb)->gso_type; unsigned short gso_size = skb_shinfo(head_skb)->gso_size; /* Update type to add partial and then remove dodgy if set */ type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL; type &= ~SKB_GSO_DODGY; /* Update GSO info and prepare to start updating headers on * our way back down the stack of protocols. */ for (iter = segs; iter; iter = iter->next) { skb_shinfo(iter)->gso_size = gso_size; skb_shinfo(iter)->gso_segs = partial_segs; skb_shinfo(iter)->gso_type = type; SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset; } if (tail->len - doffset <= gso_size) skb_shinfo(tail)->gso_size = 0; else if (tail != segs) skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size); } /* Following permits correct backpressure, for protocols * using skb_set_owner_w(). * Idea is to tranfert ownership from head_skb to last segment. */ if (head_skb->destructor == sock_wfree) { swap(tail->truesize, head_skb->truesize); swap(tail->destructor, head_skb->destructor); swap(tail->sk, head_skb->sk); } return segs; err: kfree_skb_list(segs); return ERR_PTR(err); } EXPORT_SYMBOL_GPL(skb_segment); int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb) { struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb); unsigned int offset = skb_gro_offset(skb); unsigned int headlen = skb_headlen(skb); unsigned int len = skb_gro_len(skb); struct sk_buff *lp, *p = *head; unsigned int delta_truesize; if (unlikely(p->len + len >= 65536)) return -E2BIG; lp = NAPI_GRO_CB(p)->last; pinfo = skb_shinfo(lp); if (headlen <= offset) { skb_frag_t *frag; skb_frag_t *frag2; int i = skbinfo->nr_frags; int nr_frags = pinfo->nr_frags + i; if (nr_frags > MAX_SKB_FRAGS) goto merge; offset -= headlen; pinfo->nr_frags = nr_frags; skbinfo->nr_frags = 0; frag = pinfo->frags + nr_frags; frag2 = skbinfo->frags + i; do { *--frag = *--frag2; } while (--i); frag->page_offset += offset; skb_frag_size_sub(frag, offset); /* all fragments truesize : remove (head size + sk_buff) */ delta_truesize = skb->truesize - SKB_TRUESIZE(skb_end_offset(skb)); skb->truesize -= skb->data_len; skb->len -= skb->data_len; skb->data_len = 0; NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE; goto done; } else if (skb->head_frag) { int nr_frags = pinfo->nr_frags; skb_frag_t *frag = pinfo->frags + nr_frags; struct page *page = virt_to_head_page(skb->head); unsigned int first_size = headlen - offset; unsigned int first_offset; if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS) goto merge; first_offset = skb->data - (unsigned char *)page_address(page) + offset; pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags; frag->page.p = page; frag->page_offset = first_offset; skb_frag_size_set(frag, first_size); memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags); /* We dont need to clear skbinfo->nr_frags here */ delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff)); NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD; goto done; } merge: delta_truesize = skb->truesize; if (offset > headlen) { unsigned int eat = offset - headlen; skbinfo->frags[0].page_offset += eat; skb_frag_size_sub(&skbinfo->frags[0], eat); skb->data_len -= eat; skb->len -= eat; offset = headlen; } __skb_pull(skb, offset); if (NAPI_GRO_CB(p)->last == p) skb_shinfo(p)->frag_list = skb; else NAPI_GRO_CB(p)->last->next = skb; NAPI_GRO_CB(p)->last = skb; __skb_header_release(skb); lp = p; done: NAPI_GRO_CB(p)->count++; p->data_len += len; p->truesize += delta_truesize; p->len += len; if (lp != p) { lp->data_len += len; lp->truesize += delta_truesize; lp->len += len; } NAPI_GRO_CB(skb)->same_flow = 1; return 0; } EXPORT_SYMBOL_GPL(skb_gro_receive); void __init skb_init(void) { skbuff_head_cache = kmem_cache_create("skbuff_head_cache", sizeof(struct sk_buff), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache", sizeof(struct sk_buff_fclones), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } /** * skb_to_sgvec - Fill a scatter-gather list from a socket buffer * @skb: Socket buffer containing the buffers to be mapped * @sg: The scatter-gather list to map into * @offset: The offset into the buffer's contents to start mapping * @len: Length of buffer space to be mapped * * Fill the specified scatter-gather list with mappings/pointers into a * region of the buffer space attached to a socket buffer. */ static int __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int elt = 0; if (copy > 0) { if (copy > len) copy = len; sg_set_buf(sg, skb->data + offset, copy); elt++; if ((len -= copy) == 0) return elt; offset += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; WARN_ON(start > offset + len); end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]); if ((copy = end - offset) > 0) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (copy > len) copy = len; sg_set_page(&sg[elt], skb_frag_page(frag), copy, frag->page_offset+offset-start); elt++; if (!(len -= copy)) return elt; offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; elt += __skb_to_sgvec(frag_iter, sg+elt, offset - start, copy); if ((len -= copy) == 0) return elt; offset += copy; } start = end; } BUG_ON(len); return elt; } /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given * sglist without mark the sg which contain last skb data as the end. * So the caller can mannipulate sg list as will when padding new data after * the first call without calling sg_unmark_end to expend sg list. * * Scenario to use skb_to_sgvec_nomark: * 1. sg_init_table * 2. skb_to_sgvec_nomark(payload1) * 3. skb_to_sgvec_nomark(payload2) * * This is equivalent to: * 1. sg_init_table * 2. skb_to_sgvec(payload1) * 3. sg_unmark_end * 4. skb_to_sgvec(payload2) * * When mapping mutilple payload conditionally, skb_to_sgvec_nomark * is more preferable. */ int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { return __skb_to_sgvec(skb, sg, offset, len); } EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark); int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { int nsg = __skb_to_sgvec(skb, sg, offset, len); sg_mark_end(&sg[nsg - 1]); return nsg; } EXPORT_SYMBOL_GPL(skb_to_sgvec); /** * skb_cow_data - Check that a socket buffer's data buffers are writable * @skb: The socket buffer to check. * @tailbits: Amount of trailing space to be added * @trailer: Returned pointer to the skb where the @tailbits space begins * * Make sure that the data buffers attached to a socket buffer are * writable. If they are not, private copies are made of the data buffers * and the socket buffer is set to use these instead. * * If @tailbits is given, make sure that there is space to write @tailbits * bytes of data beyond current end of socket buffer. @trailer will be * set to point to the skb in which this space begins. * * The number of scatterlist elements required to completely map the * COW'd and extended socket buffer will be returned. */ int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer) { int copyflag; int elt; struct sk_buff *skb1, **skb_p; /* If skb is cloned or its head is paged, reallocate * head pulling out all the pages (pages are considered not writable * at the moment even if they are anonymous). */ if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) && __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL) return -ENOMEM; /* Easy case. Most of packets will go this way. */ if (!skb_has_frag_list(skb)) { /* A little of trouble, not enough of space for trailer. * This should not happen, when stack is tuned to generate * good frames. OK, on miss we reallocate and reserve even more * space, 128 bytes is fair. */ if (skb_tailroom(skb) < tailbits && pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC)) return -ENOMEM; /* Voila! */ *trailer = skb; return 1; } /* Misery. We are in troubles, going to mincer fragments... */ elt = 1; skb_p = &skb_shinfo(skb)->frag_list; copyflag = 0; while ((skb1 = *skb_p) != NULL) { int ntail = 0; /* The fragment is partially pulled by someone, * this can happen on input. Copy it and everything * after it. */ if (skb_shared(skb1)) copyflag = 1; /* If the skb is the last, worry about trailer. */ if (skb1->next == NULL && tailbits) { if (skb_shinfo(skb1)->nr_frags || skb_has_frag_list(skb1) || skb_tailroom(skb1) < tailbits) ntail = tailbits + 128; } if (copyflag || skb_cloned(skb1) || ntail || skb_shinfo(skb1)->nr_frags || skb_has_frag_list(skb1)) { struct sk_buff *skb2; /* Fuck, we are miserable poor guys... */ if (ntail == 0) skb2 = skb_copy(skb1, GFP_ATOMIC); else skb2 = skb_copy_expand(skb1, skb_headroom(skb1), ntail, GFP_ATOMIC); if (unlikely(skb2 == NULL)) return -ENOMEM; if (skb1->sk) skb_set_owner_w(skb2, skb1->sk); /* Looking around. Are we still alive? * OK, link new skb, drop old one */ skb2->next = skb1->next; *skb_p = skb2; kfree_skb(skb1); skb1 = skb2; } elt++; *trailer = skb1; skb_p = &skb1->next; } return elt; } EXPORT_SYMBOL_GPL(skb_cow_data); static void sock_rmem_free(struct sk_buff *skb) { struct sock *sk = skb->sk; atomic_sub(skb->truesize, &sk->sk_rmem_alloc); } /* * Note: We dont mem charge error packets (no sk_forward_alloc changes) */ int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf) return -ENOMEM; skb_orphan(skb); skb->sk = sk; skb->destructor = sock_rmem_free; atomic_add(skb->truesize, &sk->sk_rmem_alloc); /* before exiting rcu section, make sure dst is refcounted */ skb_dst_force(skb); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(sock_queue_err_skb); static bool is_icmp_err_skb(const struct sk_buff *skb) { return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP || SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6); } struct sk_buff *sock_dequeue_err_skb(struct sock *sk) { struct sk_buff_head *q = &sk->sk_error_queue; struct sk_buff *skb, *skb_next = NULL; bool icmp_next = false; unsigned long flags; spin_lock_irqsave(&q->lock, flags); skb = __skb_dequeue(q); if (skb && (skb_next = skb_peek(q))) icmp_next = is_icmp_err_skb(skb_next); spin_unlock_irqrestore(&q->lock, flags); if (is_icmp_err_skb(skb) && !icmp_next) sk->sk_err = 0; if (skb_next) sk->sk_error_report(sk); return skb; } EXPORT_SYMBOL(sock_dequeue_err_skb); /** * skb_clone_sk - create clone of skb, and take reference to socket * @skb: the skb to clone * * This function creates a clone of a buffer that holds a reference on * sk_refcnt. Buffers created via this function are meant to be * returned using sock_queue_err_skb, or free via kfree_skb. * * When passing buffers allocated with this function to sock_queue_err_skb * it is necessary to wrap the call with sock_hold/sock_put in order to * prevent the socket from being released prior to being enqueued on * the sk_error_queue. */ struct sk_buff *skb_clone_sk(struct sk_buff *skb) { struct sock *sk = skb->sk; struct sk_buff *clone; if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt)) return NULL; clone = skb_clone(skb, GFP_ATOMIC); if (!clone) { sock_put(sk); return NULL; } clone->sk = sk; clone->destructor = sock_efree; return clone; } EXPORT_SYMBOL(skb_clone_sk); static void __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype) { struct sock_exterr_skb *serr; int err; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); } static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly) { bool ret; if (likely(sysctl_tstamp_allow_data || tsonly)) return true; read_lock_bh(&sk->sk_callback_lock); ret = sk->sk_socket && sk->sk_socket->file && file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW); read_unlock_bh(&sk->sk_callback_lock); return ret; } void skb_complete_tx_timestamp(struct sk_buff *skb, struct skb_shared_hwtstamps *hwtstamps) { struct sock *sk = skb->sk; if (!skb_may_tx_timestamp(sk, false)) return; /* Take a reference to prevent skb_orphan() from freeing the socket, * but only if the socket refcount is not zero. */ if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) { *skb_hwtstamps(skb) = *hwtstamps; __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND); sock_put(sk); } } EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp); void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) skb = tcp_get_timestamping_opt_stats(sk); else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype); } EXPORT_SYMBOL_GPL(__skb_tstamp_tx); void skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps) { return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk, SCM_TSTAMP_SND); } EXPORT_SYMBOL_GPL(skb_tstamp_tx); void skb_complete_wifi_ack(struct sk_buff *skb, bool acked) { struct sock *sk = skb->sk; struct sock_exterr_skb *serr; int err = 1; skb->wifi_acked_valid = 1; skb->wifi_acked = acked; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS; /* Take a reference to prevent skb_orphan() from freeing the socket, * but only if the socket refcount is not zero. */ if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) { err = sock_queue_err_skb(sk, skb); sock_put(sk); } if (err) kfree_skb(skb); } EXPORT_SYMBOL_GPL(skb_complete_wifi_ack); /** * skb_partial_csum_set - set up and verify partial csum values for packet * @skb: the skb to set * @start: the number of bytes after skb->data to start checksumming. * @off: the offset from start to place the checksum. * * For untrusted partially-checksummed packets, we need to make sure the values * for skb->csum_start and skb->csum_offset are valid so we don't oops. * * This function checks and sets those values and skb->ip_summed: if this * returns false you should drop the packet. */ bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off) { if (unlikely(start > skb_headlen(skb)) || unlikely((int)start + off > skb_headlen(skb) - 2)) { net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n", start, off, skb_headlen(skb)); return false; } skb->ip_summed = CHECKSUM_PARTIAL; skb->csum_start = skb_headroom(skb) + start; skb->csum_offset = off; skb_set_transport_header(skb, start); return true; } EXPORT_SYMBOL_GPL(skb_partial_csum_set); static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len, unsigned int max) { if (skb_headlen(skb) >= len) return 0; /* If we need to pullup then pullup to the max, so we * won't need to do it again. */ if (max > skb->len) max = skb->len; if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL) return -ENOMEM; if (skb_headlen(skb) < len) return -EPROTO; return 0; } #define MAX_TCP_HDR_LEN (15 * 4) static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb, typeof(IPPROTO_IP) proto, unsigned int off) { switch (proto) { int err; case IPPROTO_TCP: err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr), off + MAX_TCP_HDR_LEN); if (!err && !skb_partial_csum_set(skb, off, offsetof(struct tcphdr, check))) err = -EPROTO; return err ? ERR_PTR(err) : &tcp_hdr(skb)->check; case IPPROTO_UDP: err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr), off + sizeof(struct udphdr)); if (!err && !skb_partial_csum_set(skb, off, offsetof(struct udphdr, check))) err = -EPROTO; return err ? ERR_PTR(err) : &udp_hdr(skb)->check; } return ERR_PTR(-EPROTO); } /* This value should be large enough to cover a tagged ethernet header plus * maximally sized IP and TCP or UDP headers. */ #define MAX_IP_HDR_LEN 128 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate) { unsigned int off; bool fragment; __sum16 *csum; int err; fragment = false; err = skb_maybe_pull_tail(skb, sizeof(struct iphdr), MAX_IP_HDR_LEN); if (err < 0) goto out; if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF)) fragment = true; off = ip_hdrlen(skb); err = -EPROTO; if (fragment) goto out; csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off); if (IS_ERR(csum)) return PTR_ERR(csum); if (recalculate) *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr, ip_hdr(skb)->daddr, skb->len - off, ip_hdr(skb)->protocol, 0); err = 0; out: return err; } /* This value should be large enough to cover a tagged ethernet header plus * an IPv6 header, all options, and a maximal TCP or UDP header. */ #define MAX_IPV6_HDR_LEN 256 #define OPT_HDR(type, skb, off) \ (type *)(skb_network_header(skb) + (off)) static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate) { int err; u8 nexthdr; unsigned int off; unsigned int len; bool fragment; bool done; __sum16 *csum; fragment = false; done = false; off = sizeof(struct ipv6hdr); err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN); if (err < 0) goto out; nexthdr = ipv6_hdr(skb)->nexthdr; len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len); while (off <= len && !done) { switch (nexthdr) { case IPPROTO_DSTOPTS: case IPPROTO_HOPOPTS: case IPPROTO_ROUTING: { struct ipv6_opt_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct ipv6_opt_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct ipv6_opt_hdr, skb, off); nexthdr = hp->nexthdr; off += ipv6_optlen(hp); break; } case IPPROTO_AH: { struct ip_auth_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct ip_auth_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct ip_auth_hdr, skb, off); nexthdr = hp->nexthdr; off += ipv6_authlen(hp); break; } case IPPROTO_FRAGMENT: { struct frag_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct frag_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct frag_hdr, skb, off); if (hp->frag_off & htons(IP6_OFFSET | IP6_MF)) fragment = true; nexthdr = hp->nexthdr; off += sizeof(struct frag_hdr); break; } default: done = true; break; } } err = -EPROTO; if (!done || fragment) goto out; csum = skb_checksum_setup_ip(skb, nexthdr, off); if (IS_ERR(csum)) return PTR_ERR(csum); if (recalculate) *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, skb->len - off, nexthdr, 0); err = 0; out: return err; } /** * skb_checksum_setup - set up partial checksum offset * @skb: the skb to set up * @recalculate: if true the pseudo-header checksum will be recalculated */ int skb_checksum_setup(struct sk_buff *skb, bool recalculate) { int err; switch (skb->protocol) { case htons(ETH_P_IP): err = skb_checksum_setup_ipv4(skb, recalculate); break; case htons(ETH_P_IPV6): err = skb_checksum_setup_ipv6(skb, recalculate); break; default: err = -EPROTO; break; } return err; } EXPORT_SYMBOL(skb_checksum_setup); /** * skb_checksum_maybe_trim - maybe trims the given skb * @skb: the skb to check * @transport_len: the data length beyond the network header * * Checks whether the given skb has data beyond the given transport length. * If so, returns a cloned skb trimmed to this transport length. * Otherwise returns the provided skb. Returns NULL in error cases * (e.g. transport_len exceeds skb length or out-of-memory). * * Caller needs to set the skb transport header and free any returned skb if it * differs from the provided skb. */ static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb, unsigned int transport_len) { struct sk_buff *skb_chk; unsigned int len = skb_transport_offset(skb) + transport_len; int ret; if (skb->len < len) return NULL; else if (skb->len == len) return skb; skb_chk = skb_clone(skb, GFP_ATOMIC); if (!skb_chk) return NULL; ret = pskb_trim_rcsum(skb_chk, len); if (ret) { kfree_skb(skb_chk); return NULL; } return skb_chk; } /** * skb_checksum_trimmed - validate checksum of an skb * @skb: the skb to check * @transport_len: the data length beyond the network header * @skb_chkf: checksum function to use * * Applies the given checksum function skb_chkf to the provided skb. * Returns a checked and maybe trimmed skb. Returns NULL on error. * * If the skb has data beyond the given transport length, then a * trimmed & cloned skb is checked and returned. * * Caller needs to set the skb transport header and free any returned skb if it * differs from the provided skb. */ struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb, unsigned int transport_len, __sum16(*skb_chkf)(struct sk_buff *skb)) { struct sk_buff *skb_chk; unsigned int offset = skb_transport_offset(skb); __sum16 ret; skb_chk = skb_checksum_maybe_trim(skb, transport_len); if (!skb_chk) goto err; if (!pskb_may_pull(skb_chk, offset)) goto err; skb_pull_rcsum(skb_chk, offset); ret = skb_chkf(skb_chk); skb_push_rcsum(skb_chk, offset); if (ret) goto err; return skb_chk; err: if (skb_chk && skb_chk != skb) kfree_skb(skb_chk); return NULL; } EXPORT_SYMBOL(skb_checksum_trimmed); void __skb_warn_lro_forwarding(const struct sk_buff *skb) { net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n", skb->dev->name); } EXPORT_SYMBOL(__skb_warn_lro_forwarding); void kfree_skb_partial(struct sk_buff *skb, bool head_stolen) { if (head_stolen) { skb_release_head_state(skb); kmem_cache_free(skbuff_head_cache, skb); } else { __kfree_skb(skb); } } EXPORT_SYMBOL(kfree_skb_partial); /** * skb_try_coalesce - try to merge skb to prior one * @to: prior buffer * @from: buffer to add * @fragstolen: pointer to boolean * @delta_truesize: how much more was allocated than was requested */ bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from, bool *fragstolen, int *delta_truesize) { int i, delta, len = from->len; *fragstolen = false; if (skb_cloned(to)) return false; if (len <= skb_tailroom(to)) { if (len) BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len)); *delta_truesize = 0; return true; } if (skb_has_frag_list(to) || skb_has_frag_list(from)) return false; if (skb_headlen(from) != 0) { struct page *page; unsigned int offset; if (skb_shinfo(to)->nr_frags + skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) return false; if (skb_head_is_locked(from)) return false; delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff)); page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); skb_fill_page_desc(to, skb_shinfo(to)->nr_frags, page, offset, skb_headlen(from)); *fragstolen = true; } else { if (skb_shinfo(to)->nr_frags + skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS) return false; delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from)); } WARN_ON_ONCE(delta < len); memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags, skb_shinfo(from)->frags, skb_shinfo(from)->nr_frags * sizeof(skb_frag_t)); skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags; if (!skb_cloned(from)) skb_shinfo(from)->nr_frags = 0; /* if the skb is not cloned this does nothing * since we set nr_frags to 0. */ for (i = 0; i < skb_shinfo(from)->nr_frags; i++) skb_frag_ref(from, i); to->truesize += delta; to->len += len; to->data_len += len; *delta_truesize = delta; return true; } EXPORT_SYMBOL(skb_try_coalesce); /** * skb_scrub_packet - scrub an skb * * @skb: buffer to clean * @xnet: packet is crossing netns * * skb_scrub_packet can be used after encapsulating or decapsulting a packet * into/from a tunnel. Some information have to be cleared during these * operations. * skb_scrub_packet can also be used to clean a skb before injecting it in * another namespace (@xnet == true). We have to clear all information in the * skb that could impact namespace isolation. */ void skb_scrub_packet(struct sk_buff *skb, bool xnet) { skb->tstamp = 0; skb->pkt_type = PACKET_HOST; skb->skb_iif = 0; skb->ignore_df = 0; skb_dst_drop(skb); secpath_reset(skb); nf_reset(skb); nf_reset_trace(skb); if (!xnet) return; skb_orphan(skb); skb->mark = 0; } EXPORT_SYMBOL_GPL(skb_scrub_packet); /** * skb_gso_transport_seglen - Return length of individual segments of a gso packet * * @skb: GSO skb * * skb_gso_transport_seglen is used to determine the real size of the * individual segments, including Layer4 headers (TCP/UDP). * * The MAC/L2 or network (IP, IPv6) headers are not accounted for. */ unsigned int skb_gso_transport_seglen(const struct sk_buff *skb) { const struct skb_shared_info *shinfo = skb_shinfo(skb); unsigned int thlen = 0; if (skb->encapsulation) { thlen = skb_inner_transport_header(skb) - skb_transport_header(skb); if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) thlen += inner_tcp_hdrlen(skb); } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) { thlen = tcp_hdrlen(skb); } else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) { thlen = sizeof(struct sctphdr); } /* UFO sets gso_size to the size of the fragmentation * payload, i.e. the size of the L4 (UDP) header is already * accounted for. */ return thlen + shinfo->gso_size; } EXPORT_SYMBOL_GPL(skb_gso_transport_seglen); /** * skb_gso_validate_mtu - Return in case such skb fits a given MTU * * @skb: GSO skb * @mtu: MTU to validate against * * skb_gso_validate_mtu validates if a given skb will fit a wanted MTU * once split. */ bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu) { const struct skb_shared_info *shinfo = skb_shinfo(skb); const struct sk_buff *iter; unsigned int hlen; hlen = skb_gso_network_seglen(skb); if (shinfo->gso_size != GSO_BY_FRAGS) return hlen <= mtu; /* Undo this so we can re-use header sizes */ hlen -= GSO_BY_FRAGS; skb_walk_frags(skb, iter) { if (hlen + skb_headlen(iter) > mtu) return false; } return true; } EXPORT_SYMBOL_GPL(skb_gso_validate_mtu); static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb) { if (skb_cow(skb, skb_headroom(skb)) < 0) { kfree_skb(skb); return NULL; } memmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN, 2 * ETH_ALEN); skb->mac_header += VLAN_HLEN; return skb; } struct sk_buff *skb_vlan_untag(struct sk_buff *skb) { struct vlan_hdr *vhdr; u16 vlan_tci; if (unlikely(skb_vlan_tag_present(skb))) { /* vlan_tci is already set-up so leave this for another time */ return skb; } skb = skb_share_check(skb, GFP_ATOMIC); if (unlikely(!skb)) goto err_free; if (unlikely(!pskb_may_pull(skb, VLAN_HLEN))) goto err_free; vhdr = (struct vlan_hdr *)skb->data; vlan_tci = ntohs(vhdr->h_vlan_TCI); __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci); skb_pull_rcsum(skb, VLAN_HLEN); vlan_set_encap_proto(skb, vhdr); skb = skb_reorder_vlan_header(skb); if (unlikely(!skb)) goto err_free; skb_reset_network_header(skb); skb_reset_transport_header(skb); skb_reset_mac_len(skb); return skb; err_free: kfree_skb(skb); return NULL; } EXPORT_SYMBOL(skb_vlan_untag); int skb_ensure_writable(struct sk_buff *skb, int write_len) { if (!pskb_may_pull(skb, write_len)) return -ENOMEM; if (!skb_cloned(skb) || skb_clone_writable(skb, write_len)) return 0; return pskb_expand_head(skb, 0, 0, GFP_ATOMIC); } EXPORT_SYMBOL(skb_ensure_writable); /* remove VLAN header from packet and update csum accordingly. * expects a non skb_vlan_tag_present skb with a vlan tag payload */ int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci) { struct vlan_hdr *vhdr; int offset = skb->data - skb_mac_header(skb); int err; if (WARN_ONCE(offset, "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n", offset)) { return -EINVAL; } err = skb_ensure_writable(skb, VLAN_ETH_HLEN); if (unlikely(err)) return err; skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN); vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN); *vlan_tci = ntohs(vhdr->h_vlan_TCI); memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN); __skb_pull(skb, VLAN_HLEN); vlan_set_encap_proto(skb, vhdr); skb->mac_header += VLAN_HLEN; if (skb_network_offset(skb) < ETH_HLEN) skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_len(skb); return err; } EXPORT_SYMBOL(__skb_vlan_pop); /* Pop a vlan tag either from hwaccel or from payload. * Expects skb->data at mac header. */ int skb_vlan_pop(struct sk_buff *skb) { u16 vlan_tci; __be16 vlan_proto; int err; if (likely(skb_vlan_tag_present(skb))) { skb->vlan_tci = 0; } else { if (unlikely(!eth_type_vlan(skb->protocol))) return 0; err = __skb_vlan_pop(skb, &vlan_tci); if (err) return err; } /* move next vlan tag to hw accel tag */ if (likely(!eth_type_vlan(skb->protocol))) return 0; vlan_proto = skb->protocol; err = __skb_vlan_pop(skb, &vlan_tci); if (unlikely(err)) return err; __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci); return 0; } EXPORT_SYMBOL(skb_vlan_pop); /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present). * Expects skb->data at mac header. */ int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) { if (skb_vlan_tag_present(skb)) { int offset = skb->data - skb_mac_header(skb); int err; if (WARN_ONCE(offset, "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n", offset)) { return -EINVAL; } err = __vlan_insert_tag(skb, skb->vlan_proto, skb_vlan_tag_get(skb)); if (err) return err; skb->protocol = skb->vlan_proto; skb->mac_len += VLAN_HLEN; skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN); } __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci); return 0; } EXPORT_SYMBOL(skb_vlan_push); /** * alloc_skb_with_frags - allocate skb with page frags * * @header_len: size of linear part * @data_len: needed length in frags * @max_page_order: max page order desired. * @errcode: pointer to error code if any * @gfp_mask: allocation mask * * This can be used to allocate a paged skb, given a maximal order for frags. */ struct sk_buff *alloc_skb_with_frags(unsigned long header_len, unsigned long data_len, int max_page_order, int *errcode, gfp_t gfp_mask) { int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; unsigned long chunk; struct sk_buff *skb; struct page *page; gfp_t gfp_head; int i; *errcode = -EMSGSIZE; /* Note this test could be relaxed, if we succeed to allocate * high order pages... */ if (npages > MAX_SKB_FRAGS) return NULL; gfp_head = gfp_mask; if (gfp_head & __GFP_DIRECT_RECLAIM) gfp_head |= __GFP_REPEAT; *errcode = -ENOBUFS; skb = alloc_skb(header_len, gfp_head); if (!skb) return NULL; skb->truesize += npages << PAGE_SHIFT; for (i = 0; npages > 0; i++) { int order = max_page_order; while (order) { if (npages >= 1 << order) { page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, order); if (page) goto fill_page; /* Do not retry other high order allocations */ order = 1; max_page_order = 0; } order--; } page = alloc_page(gfp_mask); if (!page) goto failure; fill_page: chunk = min_t(unsigned long, data_len, PAGE_SIZE << order); skb_fill_page_desc(skb, i, page, 0, chunk); data_len -= chunk; npages -= 1 << order; } return skb; failure: kfree_skb(skb); return NULL; } EXPORT_SYMBOL(alloc_skb_with_frags); /* carve out the first off bytes from skb when off < headlen */ static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off, const int headlen, gfp_t gfp_mask) { int i; int size = skb_end_offset(skb); int new_hlen = headlen - off; u8 *data; size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) return -ENOMEM; size = SKB_WITH_OVERHEAD(ksize(data)); /* Copy real data, and all frags */ skb_copy_from_linear_data_offset(skb, off, data, new_hlen); skb->len -= off; memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); if (skb_cloned(skb)) { /* drop the old head gracefully */ if (skb_orphan_frags(skb, gfp_mask)) { kfree(data); return -ENOMEM; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_frag_ref(skb, i); if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); skb_release_data(skb); } else { /* we can reuse existing recount- all we did was * relocate values */ skb_free_head(skb); } skb->head = data; skb->data = data; skb->head_frag = 0; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; #else skb->end = skb->head + size; #endif skb_set_tail_pointer(skb, skb_headlen(skb)); skb_headers_offset_update(skb, 0); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; atomic_set(&skb_shinfo(skb)->dataref, 1); return 0; } static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp); /* carve out the first eat bytes from skb's frag_list. May recurse into * pskb_carve() */ static int pskb_carve_frag_list(struct sk_buff *skb, struct skb_shared_info *shinfo, int eat, gfp_t gfp_mask) { struct sk_buff *list = shinfo->frag_list; struct sk_buff *clone = NULL; struct sk_buff *insp = NULL; do { if (!list) { pr_err("Not enough bytes to eat. Want %d\n", eat); return -EFAULT; } if (list->len <= eat) { /* Eaten as whole. */ eat -= list->len; list = list->next; insp = list; } else { /* Eaten partially. */ if (skb_shared(list)) { clone = skb_clone(list, gfp_mask); if (!clone) return -ENOMEM; insp = list->next; list = clone; } else { /* This may be pulled without problems. */ insp = list; } if (pskb_carve(list, eat, gfp_mask) < 0) { kfree_skb(clone); return -ENOMEM; } break; } } while (eat); /* Free pulled out fragments. */ while ((list = shinfo->frag_list) != insp) { shinfo->frag_list = list->next; kfree_skb(list); } /* And insert new clone at head. */ if (clone) { clone->next = list; shinfo->frag_list = clone; } return 0; } /* carve off first len bytes from skb. Split line (off) is in the * non-linear part of skb */ static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off, int pos, gfp_t gfp_mask) { int i, k = 0; int size = skb_end_offset(skb); u8 *data; const int nfrags = skb_shinfo(skb)->nr_frags; struct skb_shared_info *shinfo; size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) return -ENOMEM; size = SKB_WITH_OVERHEAD(ksize(data)); memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); if (skb_orphan_frags(skb, gfp_mask)) { kfree(data); return -ENOMEM; } shinfo = (struct skb_shared_info *)(data + size); for (i = 0; i < nfrags; i++) { int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (pos + fsize > off) { shinfo->frags[k] = skb_shinfo(skb)->frags[i]; if (pos < off) { /* Split frag. * We have two variants in this case: * 1. Move all the frag to the second * part, if it is possible. F.e. * this approach is mandatory for TUX, * where splitting is expensive. * 2. Split is accurately. We make this. */ shinfo->frags[0].page_offset += off - pos; skb_frag_size_sub(&shinfo->frags[0], off - pos); } skb_frag_ref(skb, i); k++; } pos += fsize; } shinfo->nr_frags = k; if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); if (k == 0) { /* split line is in frag list */ pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask); } skb_release_data(skb); skb->head = data; skb->head_frag = 0; skb->data = data; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; #else skb->end = skb->head + size; #endif skb_reset_tail_pointer(skb); skb_headers_offset_update(skb, 0); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; skb->len -= off; skb->data_len = skb->len; atomic_set(&skb_shinfo(skb)->dataref, 1); return 0; } /* remove len bytes from the beginning of the skb */ static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp) { int headlen = skb_headlen(skb); if (len < headlen) return pskb_carve_inside_header(skb, len, headlen, gfp); else return pskb_carve_inside_nonlinear(skb, len, headlen, gfp); } /* Extract to_copy bytes starting at off from skb, and return this in * a new skb */ struct sk_buff *pskb_extract(struct sk_buff *skb, int off, int to_copy, gfp_t gfp) { struct sk_buff *clone = skb_clone(skb, gfp); if (!clone) return NULL; if (pskb_carve(clone, off, gfp) < 0 || pskb_trim(clone, to_copy)) { kfree_skb(clone); return NULL; } return clone; } EXPORT_SYMBOL(pskb_extract); /** * skb_condense - try to get rid of fragments/frag_list if possible * @skb: buffer * * Can be used to save memory before skb is added to a busy queue. * If packet has bytes in frags and enough tail room in skb->head, * pull all of them, so that we can free the frags right now and adjust * truesize. * Notes: * We do not reallocate skb->head thus can not fail. * Caller must re-evaluate skb->truesize if needed. */ void skb_condense(struct sk_buff *skb) { if (skb->data_len) { if (skb->data_len > skb->end - skb->tail || skb_cloned(skb)) return; /* Nice, we can free page frag(s) right now */ __pskb_pull_tail(skb, skb->data_len); } /* At this point, skb->truesize might be over estimated, * because skb had a fragment, and fragments do not tell * their truesize. * When we pulled its content into skb->head, fragment * was freed, but __pskb_pull_tail() could not possibly * adjust skb->truesize, not knowing the frag truesize. */ skb->truesize = SKB_TRUESIZE(skb_end_offset(skb)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3255_0
crossvul-cpp_data_good_5299_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is: % % Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); return; } switch (type) { case -1: { SetPixelAlpha(image, pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.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); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5299_0
crossvul-cpp_data_bad_2721_0
/* * Copyright (c) 1998-2006 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Carles Kishimoto <Carles.Kishimoto@bsc.es> */ /* \summary: Cisco VLAN Query Protocol (VQP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #define VQP_VERSION 1 #define VQP_EXTRACT_VERSION(x) ((x)&0xFF) /* * VQP common 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Constant | Packet type | Error Code | nitems | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Packet Sequence Number (4 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct vqp_common_header_t { uint8_t version; uint8_t msg_type; uint8_t error_code; uint8_t nitems; uint8_t sequence[4]; }; struct vqp_obj_tlv_t { uint8_t obj_type[4]; uint8_t obj_length[2]; }; #define VQP_OBJ_REQ_JOIN_PORT 0x01 #define VQP_OBJ_RESP_VLAN 0x02 #define VQP_OBJ_REQ_RECONFIRM 0x03 #define VQP_OBJ_RESP_RECONFIRM 0x04 static const struct tok vqp_msg_type_values[] = { { VQP_OBJ_REQ_JOIN_PORT, "Request, Join Port"}, { VQP_OBJ_RESP_VLAN, "Response, VLAN"}, { VQP_OBJ_REQ_RECONFIRM, "Request, Reconfirm"}, { VQP_OBJ_RESP_RECONFIRM, "Response, Reconfirm"}, { 0, NULL} }; static const struct tok vqp_error_code_values[] = { { 0x00, "No error"}, { 0x03, "Access denied"}, { 0x04, "Shutdown port"}, { 0x05, "Wrong VTP domain"}, { 0, NULL} }; /* FIXME the heading 0x0c looks ugly - those must be flags etc. */ #define VQP_OBJ_IP_ADDRESS 0x0c01 #define VQP_OBJ_PORT_NAME 0x0c02 #define VQP_OBJ_VLAN_NAME 0x0c03 #define VQP_OBJ_VTP_DOMAIN 0x0c04 #define VQP_OBJ_ETHERNET_PKT 0x0c05 #define VQP_OBJ_MAC_NULL 0x0c06 #define VQP_OBJ_MAC_ADDRESS 0x0c08 static const struct tok vqp_obj_values[] = { { VQP_OBJ_IP_ADDRESS, "Client IP Address" }, { VQP_OBJ_PORT_NAME, "Port Name" }, { VQP_OBJ_VLAN_NAME, "VLAN Name" }, { VQP_OBJ_VTP_DOMAIN, "VTP Domain" }, { VQP_OBJ_ETHERNET_PKT, "Ethernet Packet" }, { VQP_OBJ_MAC_NULL, "MAC Null" }, { VQP_OBJ_MAC_ADDRESS, "MAC Address" }, { 0, NULL} }; void vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct vqp_common_header_t *vqp_common_header; const struct vqp_obj_tlv_t *vqp_obj_tlv; const u_char *tptr; uint16_t vqp_obj_len; uint32_t vqp_obj_type; int tlen; uint8_t nitems; tptr=pptr; tlen = len; vqp_common_header = (const struct vqp_common_header_t *)pptr; ND_TCHECK(*vqp_common_header); /* * Sanity checking of the header. */ if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) { ND_PRINT((ndo, "VQP version %u packet not supported", VQP_EXTRACT_VERSION(vqp_common_header->version))); return; } /* in non-verbose mode just lets print the basic Message Type */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, len)); return; } /* ok they seem to want to know everything - lets fully decode it */ nitems = vqp_common_header->nitems; ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u", VQP_EXTRACT_VERSION(vqp_common_header->version), tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type), tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code), vqp_common_header->error_code, EXTRACT_32BITS(&vqp_common_header->sequence), nitems, len)); /* skip VQP Common header */ tptr+=sizeof(const struct vqp_common_header_t); tlen-=sizeof(const struct vqp_common_header_t); while (nitems > 0 && tlen > 0) { vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr; vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type); vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length); tptr+=sizeof(struct vqp_obj_tlv_t); tlen-=sizeof(struct vqp_obj_tlv_t); ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ", tok2str(vqp_obj_values, "Unknown", vqp_obj_type), vqp_obj_type, vqp_obj_len)); /* basic sanity check */ if (vqp_obj_type == 0 || vqp_obj_len ==0) { return; } /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, vqp_obj_len); switch(vqp_obj_type) { case VQP_OBJ_IP_ADDRESS: ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr))); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_PORT_NAME: case VQP_OBJ_VLAN_NAME: case VQP_OBJ_VTP_DOMAIN: case VQP_OBJ_ETHERNET_PKT: safeputs(ndo, tptr, vqp_obj_len); break; /* those objects have similar semantics - fall through */ case VQP_OBJ_MAC_ADDRESS: case VQP_OBJ_MAC_NULL: ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr))); break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len); break; } tptr += vqp_obj_len; tlen -= vqp_obj_len; nitems--; } return; trunc: ND_PRINT((ndo, "\n\t[|VQP]")); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2721_0
crossvul-cpp_data_bad_2588_4
/* * mus_wm.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI 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 and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "common.h" #include "wm_error.h" #include "wildmidi_lib.h" #include "internal_midi.h" #include "reverb.h" #include "f_mus.h" #ifdef DEBUG_MUS #define MUS_EVENT_DEBUG(dx,dy,dz) fprintf(stderr,"\r%s, 0x%.2x, 0x%.8x\n",dx,dy,dz) #else #define MUS_EVENT_DEBUG(dx,dy,dz) #endif /* Turns hmp file data into an event stream */ struct _mdi * _WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint32_t mus_song_ofs = 0; uint32_t mus_song_len = 0; uint16_t mus_ch_cnt1 = 0; uint16_t mus_ch_cnt2 = 0; uint16_t mus_no_instr = 0; uint32_t mus_data_ofs = 0; uint16_t * mus_mid_instr = NULL; uint16_t mus_instr_cnt = 0; struct _mdi *mus_mdi; uint32_t mus_divisions = 60; float tempo_f = 0.0; uint16_t mus_freq = 0; float samples_per_tick_f = 0.0; uint8_t mus_event[] = { 0, 0, 0, 0 }; uint8_t mus_event_size = 0; uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint32_t setup_ret = 0; uint32_t mus_ticks = 0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint16_t pitchbend_tmp = 0; if (mus_size < 17) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } if (memcmp(mus_data, mus_hdr, 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0); return NULL; } // Get Song Length mus_song_len = (mus_data[5] << 8) | mus_data[4]; // Get Song Offset mus_song_ofs = (mus_data[7] << 8) | mus_data[6]; // Have yet to determine what this actually is. mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8]; mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10]; UNUSED(mus_ch_cnt1); UNUSED(mus_ch_cnt2); // Number of instruments defined mus_no_instr = (mus_data[13] << 8) | mus_data[12]; // Skip next 2 data bytes mus_data_ofs = 16; // Check that we have enough data to check the rest if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } // Instrument definition mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t)); for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) { mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs]; mus_data_ofs += 2; } // make sure we are at song offset mus_data_ofs = mus_song_ofs; // do some calculations so we know how many samples per mus tick mus_freq = _cvt_get_option(WM_CO_FREQUENCY); if (mus_freq == 0) mus_freq = 140; if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / mus_freq) + 0.5f; } else { tempo_f = (float) (60000000 / mus_freq); } samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f); // initialise the mdi structure mus_mdi = _WM_initMDI(); _WM_midi_setup_divisions(mus_mdi, mus_divisions); _WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f); // lets do this do { // Build the event _mus_build_event: #if 1 // Mus drums happen on channel 15, swap channel 9 & 15 // DEBUG MUS_EVENT_DEBUG("Before", mus_data[mus_data_ofs], 0); if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09; } else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f; } // DEBUG MUS_EVENT_DEBUG("After", mus_data[mus_data_ofs], 0); #endif switch ((mus_data[mus_data_ofs] >> 4) & 0x07) { case 0: // Note Off mus_event_size = 2; mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Note On if (mus_data[mus_data_ofs + 1] & 0x80) { mus_event_size = 3; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2]; } else { mus_event_size = 2; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f]; mus_event[3] = 0; } break; case 2: // Pitch Bend mus_event_size = 2; mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f); pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6; mus_event[1] = pitchbend_tmp & 0x7f; mus_event[2] = (pitchbend_tmp >> 7) & 0x7f; mus_event[3] = 0; break; case 3: mus_event_size = 2; switch (mus_data[mus_data_ofs + 1]) { case 10: // All Sounds Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 120; mus_event[2] = 0; mus_event[3] = 0; break; case 11: // All Notes Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 123; mus_event[2] = 0; mus_event[3] = 0; break; case 12: // Mono (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 126; mus_event[2] = 0; mus_event[3] = 0; break; case 13: // Poly (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 127; mus_event[2] = 0; mus_event[3] = 0; break; case 14: // Reset All Controllers mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 121; mus_event[2] = 0; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 4: mus_event_size = 3; switch (mus_data[mus_data_ofs + 1]) { case 0: // Patch /* ************************************************* FIXME: Check if setting is MIDI or MUS instrument ************************************************* */ mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 2]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Bank Select mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 0; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 2: // Modulation (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 1; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 3: // Volume mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 7; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 4: // Pan mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 10; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 5: // Expression mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 11; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 6: // Reverb (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 91; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 7: // Chorus (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 93; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 8: // Sustain mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 64; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 9: // Soft Peddle (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 67; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 5: mus_event_size = 1; goto _mus_next_data; break; case 6: goto _mus_end_of_song; break; case 7: mus_event_size = 1; goto _mus_next_data; break; } setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, 0); if (setup_ret == 0) { goto _mus_end; } _mus_next_data: if (!(mus_data[mus_data_ofs] & 0x80)) { mus_data_ofs += mus_event_size; goto _mus_build_event; } mus_data_ofs += mus_event_size; mus_ticks = 0; do { mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f); } while (mus_data[mus_data_ofs - 1] & 0x80); sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder; sample_count = (uint32_t)sample_count_f; sample_remainder = sample_count_f - (float)sample_count; mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count; mus_mdi->extra_info.approx_total_samples += sample_count; } while (mus_data_ofs < mus_size); _mus_end_of_song: // Finalise mdi structure if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _mus_end; } _WM_midi_setup_endoftrack(mus_mdi); mus_mdi->extra_info.current_sample = 0; mus_mdi->current_event = &mus_mdi->events[0]; mus_mdi->samples_to_mix = 0; mus_mdi->note = NULL; _WM_ResetToStart(mus_mdi); _mus_end: free(mus_mid_instr); if (mus_mdi->reverb) return (mus_mdi); _WM_freeMDI(mus_mdi); return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2588_4
crossvul-cpp_data_good_2640_0
/* * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Internet, ethernet, port, and protocol string to address * and address to string conversion routines */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_CASPER #include <libcasper.h> #include <casper/cap_dns.h> #endif /* HAVE_CASPER */ #include <netdissect-stdinc.h> #ifdef USE_ETHER_NTOHOST #ifdef HAVE_NETINET_IF_ETHER_H struct mbuf; /* Squelch compiler warnings on some platforms for */ struct rtentry; /* declarations in <net/if.h> */ #include <net/if.h> /* for "struct ifnet" in "struct arpcom" on Solaris */ #include <netinet/if_ether.h> #endif /* HAVE_NETINET_IF_ETHER_H */ #ifdef NETINET_ETHER_H_DECLARES_ETHER_NTOHOST #include <netinet/ether.h> #endif /* NETINET_ETHER_H_DECLARES_ETHER_NTOHOST */ #if !defined(HAVE_DECL_ETHER_NTOHOST) || !HAVE_DECL_ETHER_NTOHOST #ifndef HAVE_STRUCT_ETHER_ADDR struct ether_addr { unsigned char ether_addr_octet[6]; }; #endif extern int ether_ntohost(char *, const struct ether_addr *); #endif #endif /* USE_ETHER_NTOHOST */ #include <pcap.h> #include <pcap-namedb.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "netdissect.h" #include "addrtoname.h" #include "addrtostr.h" #include "ethertype.h" #include "llc.h" #include "setsignal.h" #include "extract.h" #include "oui.h" #ifndef ETHER_ADDR_LEN #define ETHER_ADDR_LEN 6 #endif /* * hash tables for whatever-to-name translations * * ndo_error() called on strdup(3) failure */ #define HASHNAMESIZE 4096 struct hnamemem { uint32_t addr; const char *name; struct hnamemem *nxt; }; static struct hnamemem hnametable[HASHNAMESIZE]; static struct hnamemem tporttable[HASHNAMESIZE]; static struct hnamemem uporttable[HASHNAMESIZE]; static struct hnamemem eprototable[HASHNAMESIZE]; static struct hnamemem dnaddrtable[HASHNAMESIZE]; static struct hnamemem ipxsaptable[HASHNAMESIZE]; #ifdef _WIN32 /* * fake gethostbyaddr for Win2k/XP * gethostbyaddr() returns incorrect value when AF_INET6 is passed * to 3rd argument. * * h_name in struct hostent is only valid. */ static struct hostent * win32_gethostbyaddr(const char *addr, int len, int type) { static struct hostent host; static char hostbuf[NI_MAXHOST]; char hname[NI_MAXHOST]; struct sockaddr_in6 addr6; host.h_name = hostbuf; switch (type) { case AF_INET: return gethostbyaddr(addr, len, type); break; case AF_INET6: memset(&addr6, 0, sizeof(addr6)); addr6.sin6_family = AF_INET6; memcpy(&addr6.sin6_addr, addr, len); if (getnameinfo((struct sockaddr *)&addr6, sizeof(addr6), hname, sizeof(hname), NULL, 0, 0)) { return NULL; } else { strcpy(host.h_name, hname); return &host; } break; default: return NULL; } } #define gethostbyaddr win32_gethostbyaddr #endif /* _WIN32 */ struct h6namemem { struct in6_addr addr; char *name; struct h6namemem *nxt; }; static struct h6namemem h6nametable[HASHNAMESIZE]; struct enamemem { u_short e_addr0; u_short e_addr1; u_short e_addr2; const char *e_name; u_char *e_nsap; /* used only for nsaptable[] */ #define e_bs e_nsap /* for bytestringtable */ size_t e_namelen; /* for bytestringtable */ struct enamemem *e_nxt; }; static struct enamemem enametable[HASHNAMESIZE]; static struct enamemem nsaptable[HASHNAMESIZE]; struct bsnamemem { u_short bs_addr0; u_short bs_addr1; u_short bs_addr2; const char *bs_name; u_char *bs_bytes; unsigned int bs_nbytes; struct bsnamemem *bs_nxt; }; static struct bsnamemem bytestringtable[HASHNAMESIZE]; struct protoidmem { uint32_t p_oui; u_short p_proto; const char *p_name; struct protoidmem *p_nxt; }; static struct protoidmem protoidtable[HASHNAMESIZE]; /* * A faster replacement for inet_ntoa(). */ const char * intoa(uint32_t addr) { register char *cp; register u_int byte; register int n; static char buf[sizeof(".xxx.xxx.xxx.xxx")]; NTOHL(addr); cp = buf + sizeof(buf); *--cp = '\0'; n = 4; do { byte = addr & 0xff; *--cp = byte % 10 + '0'; byte /= 10; if (byte > 0) { *--cp = byte % 10 + '0'; byte /= 10; if (byte > 0) *--cp = byte + '0'; } *--cp = '.'; addr >>= 8; } while (--n > 0); return cp + 1; } static uint32_t f_netmask; static uint32_t f_localnet; #ifdef HAVE_CASPER extern cap_channel_t *capdns; #endif /* * Return a name for the IP address pointed to by ap. This address * is assumed to be in network byte order. * * NOTE: ap is *NOT* necessarily part of the packet data (not even if * this is being called with the "ipaddr_string()" macro), so you * *CANNOT* use the ND_TCHECK{2}/ND_TTEST{2} macros on it. Furthermore, * even in cases where it *is* part of the packet data, the caller * would still have to check for a null return value, even if it's * just printing the return value with "%s" - not all versions of * printf print "(null)" with "%s" and a null pointer, some of them * don't check for a null pointer and crash in that case. * * The callers of this routine should, before handing this routine * a pointer to packet data, be sure that the data is present in * the packet buffer. They should probably do those checks anyway, * as other data at that layer might not be IP addresses, and it * also needs to check whether they're present in the packet buffer. */ const char * getname(netdissect_options *ndo, const u_char *ap) { register struct hostent *hp; uint32_t addr; struct hnamemem *p; memcpy(&addr, ap, sizeof(addr)); p = &hnametable[addr & (HASHNAMESIZE-1)]; for (; p->nxt; p = p->nxt) { if (p->addr == addr) return (p->name); } p->addr = addr; p->nxt = newhnamemem(ndo); /* * Print names unless: * (1) -n was given. * (2) Address is foreign and -f was given. (If -f was not * given, f_netmask and f_localnet are 0 and the test * evaluates to true) */ if (!ndo->ndo_nflag && (addr & f_netmask) == f_localnet) { #ifdef HAVE_CASPER if (capdns != NULL) { hp = cap_gethostbyaddr(capdns, (char *)&addr, 4, AF_INET); } else #endif hp = gethostbyaddr((char *)&addr, 4, AF_INET); if (hp) { char *dotp; p->name = strdup(hp->h_name); if (p->name == NULL) (*ndo->ndo_error)(ndo, "getname: strdup(hp->h_name)"); if (ndo->ndo_Nflag) { /* Remove domain qualifications */ dotp = strchr(p->name, '.'); if (dotp) *dotp = '\0'; } return (p->name); } } p->name = strdup(intoa(addr)); if (p->name == NULL) (*ndo->ndo_error)(ndo, "getname: strdup(intoa(addr))"); return (p->name); } /* * Return a name for the IP6 address pointed to by ap. This address * is assumed to be in network byte order. */ const char * getname6(netdissect_options *ndo, const u_char *ap) { register struct hostent *hp; union { struct in6_addr addr; struct for_hash_addr { char fill[14]; uint16_t d; } addra; } addr; struct h6namemem *p; register const char *cp; char ntop_buf[INET6_ADDRSTRLEN]; memcpy(&addr, ap, sizeof(addr)); p = &h6nametable[addr.addra.d & (HASHNAMESIZE-1)]; for (; p->nxt; p = p->nxt) { if (memcmp(&p->addr, &addr, sizeof(addr)) == 0) return (p->name); } p->addr = addr.addr; p->nxt = newh6namemem(ndo); /* * Do not print names if -n was given. */ if (!ndo->ndo_nflag) { #ifdef HAVE_CASPER if (capdns != NULL) { hp = cap_gethostbyaddr(capdns, (char *)&addr, sizeof(addr), AF_INET6); } else #endif hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET6); if (hp) { char *dotp; p->name = strdup(hp->h_name); if (p->name == NULL) (*ndo->ndo_error)(ndo, "getname6: strdup(hp->h_name)"); if (ndo->ndo_Nflag) { /* Remove domain qualifications */ dotp = strchr(p->name, '.'); if (dotp) *dotp = '\0'; } return (p->name); } } cp = addrtostr6(ap, ntop_buf, sizeof(ntop_buf)); p->name = strdup(cp); if (p->name == NULL) (*ndo->ndo_error)(ndo, "getname6: strdup(cp)"); return (p->name); } static const char hex[] = "0123456789abcdef"; /* Find the hash node that corresponds the ether address 'ep' */ static inline struct enamemem * lookup_emem(netdissect_options *ndo, const u_char *ep) { register u_int i, j, k; struct enamemem *tp; k = (ep[0] << 8) | ep[1]; j = (ep[2] << 8) | ep[3]; i = (ep[4] << 8) | ep[5]; tp = &enametable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->e_nxt) if (tp->e_addr0 == i && tp->e_addr1 == j && tp->e_addr2 == k) return tp; else tp = tp->e_nxt; tp->e_addr0 = i; tp->e_addr1 = j; tp->e_addr2 = k; tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp)); if (tp->e_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_emem: calloc"); return tp; } /* * Find the hash node that corresponds to the bytestring 'bs' * with length 'nlen' */ static inline struct bsnamemem * lookup_bytestring(netdissect_options *ndo, register const u_char *bs, const unsigned int nlen) { struct bsnamemem *tp; register u_int i, j, k; if (nlen >= 6) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = (bs[4] << 8) | bs[5]; } else if (nlen >= 4) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = 0; } else i = j = k = 0; tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->bs_nxt) if (nlen == tp->bs_nbytes && tp->bs_addr0 == i && tp->bs_addr1 == j && tp->bs_addr2 == k && memcmp((const char *)bs, (const char *)(tp->bs_bytes), nlen) == 0) return tp; else tp = tp->bs_nxt; tp->bs_addr0 = i; tp->bs_addr1 = j; tp->bs_addr2 = k; tp->bs_bytes = (u_char *) calloc(1, nlen + 1); if (tp->bs_bytes == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); memcpy(tp->bs_bytes, bs, nlen); tp->bs_nbytes = nlen; tp->bs_nxt = (struct bsnamemem *)calloc(1, sizeof(*tp)); if (tp->bs_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); return tp; } /* Find the hash node that corresponds the NSAP 'nsap' */ static inline struct enamemem * lookup_nsap(netdissect_options *ndo, register const u_char *nsap, register u_int nsap_length) { register u_int i, j, k; struct enamemem *tp; const u_char *ensap; if (nsap_length > 6) { ensap = nsap + nsap_length - 6; k = (ensap[0] << 8) | ensap[1]; j = (ensap[2] << 8) | ensap[3]; i = (ensap[4] << 8) | ensap[5]; } else i = j = k = 0; tp = &nsaptable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->e_nxt) if (tp->e_addr0 == i && tp->e_addr1 == j && tp->e_addr2 == k && tp->e_nsap[0] == nsap_length && memcmp((const char *)&(nsap[1]), (char *)&(tp->e_nsap[1]), nsap_length) == 0) return tp; else tp = tp->e_nxt; tp->e_addr0 = i; tp->e_addr1 = j; tp->e_addr2 = k; tp->e_nsap = (u_char *)malloc(nsap_length + 1); if (tp->e_nsap == NULL) (*ndo->ndo_error)(ndo, "lookup_nsap: malloc"); tp->e_nsap[0] = (u_char)nsap_length; /* guaranteed < ISONSAP_MAX_LENGTH */ memcpy((char *)&tp->e_nsap[1], (const char *)nsap, nsap_length); tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp)); if (tp->e_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_nsap: calloc"); return tp; } /* Find the hash node that corresponds the protoid 'pi'. */ static inline struct protoidmem * lookup_protoid(netdissect_options *ndo, const u_char *pi) { register u_int i, j; struct protoidmem *tp; /* 5 octets won't be aligned */ i = (((pi[0] << 8) + pi[1]) << 8) + pi[2]; j = (pi[3] << 8) + pi[4]; /* XXX should be endian-insensitive, but do big-endian testing XXX */ tp = &protoidtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->p_nxt) if (tp->p_oui == i && tp->p_proto == j) return tp; else tp = tp->p_nxt; tp->p_oui = i; tp->p_proto = j; tp->p_nxt = (struct protoidmem *)calloc(1, sizeof(*tp)); if (tp->p_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_protoid: calloc"); return tp; } const char * etheraddr_string(netdissect_options *ndo, register const u_char *ep) { register int i; register char *cp; register struct enamemem *tp; int oui; char buf[BUFSIZE]; tp = lookup_emem(ndo, ep); if (tp->e_name) return (tp->e_name); #ifdef USE_ETHER_NTOHOST if (!ndo->ndo_nflag) { char buf2[BUFSIZE]; if (ether_ntohost(buf2, (const struct ether_addr *)ep) == 0) { tp->e_name = strdup(buf2); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "etheraddr_string: strdup(buf2)"); return (tp->e_name); } } #endif cp = buf; oui = EXTRACT_24BITS(ep); *cp++ = hex[*ep >> 4 ]; *cp++ = hex[*ep++ & 0xf]; for (i = 5; --i >= 0;) { *cp++ = ':'; *cp++ = hex[*ep >> 4 ]; *cp++ = hex[*ep++ & 0xf]; } if (!ndo->ndo_nflag) { snprintf(cp, BUFSIZE - (2 + 5*3), " (oui %s)", tok2str(oui_values, "Unknown", oui)); } else *cp = '\0'; tp->e_name = strdup(buf); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "etheraddr_string: strdup(buf)"); return (tp->e_name); } const char * le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct bsnamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->bs_name) return (tp->bs_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->bs_name = strdup(buf); if (tp->bs_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->bs_name); } const char * linkaddr_string(netdissect_options *ndo, const u_char *ep, const unsigned int type, const unsigned int len) { register u_int i; register char *cp; register struct bsnamemem *tp; if (len == 0) return ("<empty>"); if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN) return (etheraddr_string(ndo, ep)); if (type == LINKADDR_FRELAY) return (q922_string(ndo, ep, len)); tp = lookup_bytestring(ndo, ep, len); if (tp->bs_name) return (tp->bs_name); tp->bs_name = cp = (char *)malloc(len*3); if (tp->bs_name == NULL) (*ndo->ndo_error)(ndo, "linkaddr_string: malloc"); *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; for (i = len-1; i > 0 ; --i) { *cp++ = ':'; *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; } *cp = '\0'; return (tp->bs_name); } const char * etherproto_string(netdissect_options *ndo, u_short port) { register char *cp; register struct hnamemem *tp; register uint32_t i = port; char buf[sizeof("0000")]; for (tp = &eprototable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt) if (tp->addr == i) return (tp->name); tp->addr = i; tp->nxt = newhnamemem(ndo); cp = buf; NTOHS(port); *cp++ = hex[port >> 12 & 0xf]; *cp++ = hex[port >> 8 & 0xf]; *cp++ = hex[port >> 4 & 0xf]; *cp++ = hex[port & 0xf]; *cp++ = '\0'; tp->name = strdup(buf); if (tp->name == NULL) (*ndo->ndo_error)(ndo, "etherproto_string: strdup(buf)"); return (tp->name); } const char * protoid_string(netdissect_options *ndo, register const u_char *pi) { register u_int i, j; register char *cp; register struct protoidmem *tp; char buf[sizeof("00:00:00:00:00")]; tp = lookup_protoid(ndo, pi); if (tp->p_name) return tp->p_name; cp = buf; if ((j = *pi >> 4) != 0) *cp++ = hex[j]; *cp++ = hex[*pi++ & 0xf]; for (i = 4; (int)--i >= 0;) { *cp++ = ':'; if ((j = *pi >> 4) != 0) *cp++ = hex[j]; *cp++ = hex[*pi++ & 0xf]; } *cp = '\0'; tp->p_name = strdup(buf); if (tp->p_name == NULL) (*ndo->ndo_error)(ndo, "protoid_string: strdup(buf)"); return (tp->p_name); } #define ISONSAP_MAX_LENGTH 20 const char * isonsap_string(netdissect_options *ndo, const u_char *nsap, register u_int nsap_length) { register u_int nsap_idx; register char *cp; register struct enamemem *tp; if (nsap_length < 1 || nsap_length > ISONSAP_MAX_LENGTH) return ("isonsap_string: illegal length"); tp = lookup_nsap(ndo, nsap, nsap_length); if (tp->e_name) return tp->e_name; tp->e_name = cp = (char *)malloc(sizeof("xx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xx")); if (cp == NULL) (*ndo->ndo_error)(ndo, "isonsap_string: malloc"); for (nsap_idx = 0; nsap_idx < nsap_length; nsap_idx++) { *cp++ = hex[*nsap >> 4]; *cp++ = hex[*nsap++ & 0xf]; if (((nsap_idx & 1) == 0) && (nsap_idx + 1 < nsap_length)) { *cp++ = '.'; } } *cp = '\0'; return (tp->e_name); } const char * tcpport_string(netdissect_options *ndo, u_short port) { register struct hnamemem *tp; register uint32_t i = port; char buf[sizeof("00000")]; for (tp = &tporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt) if (tp->addr == i) return (tp->name); tp->addr = i; tp->nxt = newhnamemem(ndo); (void)snprintf(buf, sizeof(buf), "%u", i); tp->name = strdup(buf); if (tp->name == NULL) (*ndo->ndo_error)(ndo, "tcpport_string: strdup(buf)"); return (tp->name); } const char * udpport_string(netdissect_options *ndo, register u_short port) { register struct hnamemem *tp; register uint32_t i = port; char buf[sizeof("00000")]; for (tp = &uporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt) if (tp->addr == i) return (tp->name); tp->addr = i; tp->nxt = newhnamemem(ndo); (void)snprintf(buf, sizeof(buf), "%u", i); tp->name = strdup(buf); if (tp->name == NULL) (*ndo->ndo_error)(ndo, "udpport_string: strdup(buf)"); return (tp->name); } const char * ipxsap_string(netdissect_options *ndo, u_short port) { register char *cp; register struct hnamemem *tp; register uint32_t i = port; char buf[sizeof("0000")]; for (tp = &ipxsaptable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt) if (tp->addr == i) return (tp->name); tp->addr = i; tp->nxt = newhnamemem(ndo); cp = buf; NTOHS(port); *cp++ = hex[port >> 12 & 0xf]; *cp++ = hex[port >> 8 & 0xf]; *cp++ = hex[port >> 4 & 0xf]; *cp++ = hex[port & 0xf]; *cp++ = '\0'; tp->name = strdup(buf); if (tp->name == NULL) (*ndo->ndo_error)(ndo, "ipxsap_string: strdup(buf)"); return (tp->name); } static void init_servarray(netdissect_options *ndo) { struct servent *sv; register struct hnamemem *table; register int i; char buf[sizeof("0000000000")]; while ((sv = getservent()) != NULL) { int port = ntohs(sv->s_port); i = port & (HASHNAMESIZE-1); if (strcmp(sv->s_proto, "tcp") == 0) table = &tporttable[i]; else if (strcmp(sv->s_proto, "udp") == 0) table = &uporttable[i]; else continue; while (table->name) table = table->nxt; if (ndo->ndo_nflag) { (void)snprintf(buf, sizeof(buf), "%d", port); table->name = strdup(buf); } else table->name = strdup(sv->s_name); if (table->name == NULL) (*ndo->ndo_error)(ndo, "init_servarray: strdup"); table->addr = port; table->nxt = newhnamemem(ndo); } endservent(); } static const struct eproto { const char *s; u_short p; } eproto_db[] = { { "pup", ETHERTYPE_PUP }, { "xns", ETHERTYPE_NS }, { "ip", ETHERTYPE_IP }, { "ip6", ETHERTYPE_IPV6 }, { "arp", ETHERTYPE_ARP }, { "rarp", ETHERTYPE_REVARP }, { "sprite", ETHERTYPE_SPRITE }, { "mopdl", ETHERTYPE_MOPDL }, { "moprc", ETHERTYPE_MOPRC }, { "decnet", ETHERTYPE_DN }, { "lat", ETHERTYPE_LAT }, { "sca", ETHERTYPE_SCA }, { "lanbridge", ETHERTYPE_LANBRIDGE }, { "vexp", ETHERTYPE_VEXP }, { "vprod", ETHERTYPE_VPROD }, { "atalk", ETHERTYPE_ATALK }, { "atalkarp", ETHERTYPE_AARP }, { "loopback", ETHERTYPE_LOOPBACK }, { "decdts", ETHERTYPE_DECDTS }, { "decdns", ETHERTYPE_DECDNS }, { (char *)0, 0 } }; static void init_eprotoarray(netdissect_options *ndo) { register int i; register struct hnamemem *table; for (i = 0; eproto_db[i].s; i++) { int j = htons(eproto_db[i].p) & (HASHNAMESIZE-1); table = &eprototable[j]; while (table->name) table = table->nxt; table->name = eproto_db[i].s; table->addr = htons(eproto_db[i].p); table->nxt = newhnamemem(ndo); } } static const struct protoidlist { const u_char protoid[5]; const char *name; } protoidlist[] = { {{ 0x00, 0x00, 0x0c, 0x01, 0x07 }, "CiscoMLS" }, {{ 0x00, 0x00, 0x0c, 0x20, 0x00 }, "CiscoCDP" }, {{ 0x00, 0x00, 0x0c, 0x20, 0x01 }, "CiscoCGMP" }, {{ 0x00, 0x00, 0x0c, 0x20, 0x03 }, "CiscoVTP" }, {{ 0x00, 0xe0, 0x2b, 0x00, 0xbb }, "ExtremeEDP" }, {{ 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL } }; /* * SNAP proto IDs with org code 0:0:0 are actually encapsulated Ethernet * types. */ static void init_protoidarray(netdissect_options *ndo) { register int i; register struct protoidmem *tp; const struct protoidlist *pl; u_char protoid[5]; protoid[0] = 0; protoid[1] = 0; protoid[2] = 0; for (i = 0; eproto_db[i].s; i++) { u_short etype = htons(eproto_db[i].p); memcpy((char *)&protoid[3], (char *)&etype, 2); tp = lookup_protoid(ndo, protoid); tp->p_name = strdup(eproto_db[i].s); if (tp->p_name == NULL) (*ndo->ndo_error)(ndo, "init_protoidarray: strdup(eproto_db[i].s)"); } /* Hardwire some SNAP proto ID names */ for (pl = protoidlist; pl->name != NULL; ++pl) { tp = lookup_protoid(ndo, pl->protoid); /* Don't override existing name */ if (tp->p_name != NULL) continue; tp->p_name = pl->name; } } static const struct etherlist { const u_char addr[6]; const char *name; } etherlist[] = { {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, "Broadcast" }, {{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL } }; /* * Initialize the ethers hash table. We take two different approaches * depending on whether or not the system provides the ethers name * service. If it does, we just wire in a few names at startup, * and etheraddr_string() fills in the table on demand. If it doesn't, * then we suck in the entire /etc/ethers file at startup. The idea * is that parsing the local file will be fast, but spinning through * all the ethers entries via NIS & next_etherent might be very slow. * * XXX pcap_next_etherent doesn't belong in the pcap interface, but * since the pcap module already does name-to-address translation, * it's already does most of the work for the ethernet address-to-name * translation, so we just pcap_next_etherent as a convenience. */ static void init_etherarray(netdissect_options *ndo) { register const struct etherlist *el; register struct enamemem *tp; #ifdef USE_ETHER_NTOHOST char name[256]; #else register struct pcap_etherent *ep; register FILE *fp; /* Suck in entire ethers file */ fp = fopen(PCAP_ETHERS_FILE, "r"); if (fp != NULL) { while ((ep = pcap_next_etherent(fp)) != NULL) { tp = lookup_emem(ndo, ep->addr); tp->e_name = strdup(ep->name); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "init_etherarray: strdup(ep->addr)"); } (void)fclose(fp); } #endif /* Hardwire some ethernet names */ for (el = etherlist; el->name != NULL; ++el) { tp = lookup_emem(ndo, el->addr); /* Don't override existing name */ if (tp->e_name != NULL) continue; #ifdef USE_ETHER_NTOHOST /* * Use YP/NIS version of name if available. */ if (ether_ntohost(name, (const struct ether_addr *)el->addr) == 0) { tp->e_name = strdup(name); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "init_etherarray: strdup(name)"); continue; } #endif tp->e_name = el->name; } } static const struct tok ipxsap_db[] = { { 0x0000, "Unknown" }, { 0x0001, "User" }, { 0x0002, "User Group" }, { 0x0003, "PrintQueue" }, { 0x0004, "FileServer" }, { 0x0005, "JobServer" }, { 0x0006, "Gateway" }, { 0x0007, "PrintServer" }, { 0x0008, "ArchiveQueue" }, { 0x0009, "ArchiveServer" }, { 0x000a, "JobQueue" }, { 0x000b, "Administration" }, { 0x000F, "Novell TI-RPC" }, { 0x0017, "Diagnostics" }, { 0x0020, "NetBIOS" }, { 0x0021, "NAS SNA Gateway" }, { 0x0023, "NACS AsyncGateway" }, { 0x0024, "RemoteBridge/RoutingService" }, { 0x0026, "BridgeServer" }, { 0x0027, "TCP/IP Gateway" }, { 0x0028, "Point-to-point X.25 BridgeServer" }, { 0x0029, "3270 Gateway" }, { 0x002a, "CHI Corp" }, { 0x002c, "PC Chalkboard" }, { 0x002d, "TimeSynchServer" }, { 0x002e, "ARCserve5.0/PalindromeBackup" }, { 0x0045, "DI3270 Gateway" }, { 0x0047, "AdvertisingPrintServer" }, { 0x004a, "NetBlazerModems" }, { 0x004b, "BtrieveVAP" }, { 0x004c, "NetwareSQL" }, { 0x004d, "XtreeNetwork" }, { 0x0050, "BtrieveVAP4.11" }, { 0x0052, "QuickLink" }, { 0x0053, "PrintQueueUser" }, { 0x0058, "Multipoint X.25 Router" }, { 0x0060, "STLB/NLM" }, { 0x0064, "ARCserve" }, { 0x0066, "ARCserve3.0" }, { 0x0072, "WAN CopyUtility" }, { 0x007a, "TES-NetwareVMS" }, { 0x0092, "WATCOM Debugger/EmeraldTapeBackupServer" }, { 0x0095, "DDA OBGYN" }, { 0x0098, "NetwareAccessServer" }, { 0x009a, "Netware for VMS II/NamedPipeServer" }, { 0x009b, "NetwareAccessServer" }, { 0x009e, "PortableNetwareServer/SunLinkNVT" }, { 0x00a1, "PowerchuteAPC UPS" }, { 0x00aa, "LAWserve" }, { 0x00ac, "CompaqIDA StatusMonitor" }, { 0x0100, "PIPE STAIL" }, { 0x0102, "LAN ProtectBindery" }, { 0x0103, "OracleDataBaseServer" }, { 0x0107, "Netware386/RSPX RemoteConsole" }, { 0x010f, "NovellSNA Gateway" }, { 0x0111, "TestServer" }, { 0x0112, "HP PrintServer" }, { 0x0114, "CSA MUX" }, { 0x0115, "CSA LCA" }, { 0x0116, "CSA CM" }, { 0x0117, "CSA SMA" }, { 0x0118, "CSA DBA" }, { 0x0119, "CSA NMA" }, { 0x011a, "CSA SSA" }, { 0x011b, "CSA STATUS" }, { 0x011e, "CSA APPC" }, { 0x0126, "SNA TEST SSA Profile" }, { 0x012a, "CSA TRACE" }, { 0x012b, "NetwareSAA" }, { 0x012e, "IKARUS VirusScan" }, { 0x0130, "CommunicationsExecutive" }, { 0x0133, "NNS DomainServer/NetwareNamingServicesDomain" }, { 0x0135, "NetwareNamingServicesProfile" }, { 0x0137, "Netware386 PrintQueue/NNS PrintQueue" }, { 0x0141, "LAN SpoolServer" }, { 0x0152, "IRMALAN Gateway" }, { 0x0154, "NamedPipeServer" }, { 0x0166, "NetWareManagement" }, { 0x0168, "Intel PICKIT CommServer/Intel CAS TalkServer" }, { 0x0173, "Compaq" }, { 0x0174, "Compaq SNMP Agent" }, { 0x0175, "Compaq" }, { 0x0180, "XTreeServer/XTreeTools" }, { 0x018A, "NASI ServicesBroadcastServer" }, { 0x01b0, "GARP Gateway" }, { 0x01b1, "Binfview" }, { 0x01bf, "IntelLanDeskManager" }, { 0x01ca, "AXTEC" }, { 0x01cb, "ShivaNetModem/E" }, { 0x01cc, "ShivaLanRover/E" }, { 0x01cd, "ShivaLanRover/T" }, { 0x01ce, "ShivaUniversal" }, { 0x01d8, "CastelleFAXPressServer" }, { 0x01da, "CastelleLANPressPrintServer" }, { 0x01dc, "CastelleFAX/Xerox7033 FaxServer/ExcelLanFax" }, { 0x01f0, "LEGATO" }, { 0x01f5, "LEGATO" }, { 0x0233, "NMS Agent/NetwareManagementAgent" }, { 0x0237, "NMS IPX Discovery/LANternReadWriteChannel" }, { 0x0238, "NMS IP Discovery/LANternTrapAlarmChannel" }, { 0x023a, "LANtern" }, { 0x023c, "MAVERICK" }, { 0x023f, "NovellSMDR" }, { 0x024e, "NetwareConnect" }, { 0x024f, "NASI ServerBroadcast Cisco" }, { 0x026a, "NMS ServiceConsole" }, { 0x026b, "TimeSynchronizationServer Netware 4.x" }, { 0x0278, "DirectoryServer Netware 4.x" }, { 0x027b, "NetwareManagementAgent" }, { 0x0280, "Novell File and Printer Sharing Service for PC" }, { 0x0304, "NovellSAA Gateway" }, { 0x0308, "COM/VERMED" }, { 0x030a, "GalacticommWorldgroupServer" }, { 0x030c, "IntelNetport2/HP JetDirect/HP Quicksilver" }, { 0x0320, "AttachmateGateway" }, { 0x0327, "MicrosoftDiagnostiocs" }, { 0x0328, "WATCOM SQL Server" }, { 0x0335, "MultiTechSystems MultisynchCommServer" }, { 0x0343, "Xylogics RemoteAccessServer/LANModem" }, { 0x0355, "ArcadaBackupExec" }, { 0x0358, "MSLCD1" }, { 0x0361, "NETINELO" }, { 0x037e, "Powerchute UPS Monitoring" }, { 0x037f, "ViruSafeNotify" }, { 0x0386, "HP Bridge" }, { 0x0387, "HP Hub" }, { 0x0394, "NetWare SAA Gateway" }, { 0x039b, "LotusNotes" }, { 0x03b7, "CertusAntiVirus" }, { 0x03c4, "ARCserve4.0" }, { 0x03c7, "LANspool3.5" }, { 0x03d7, "LexmarkPrinterServer" }, { 0x03d8, "LexmarkXLE PrinterServer" }, { 0x03dd, "BanyanENS NetwareClient" }, { 0x03de, "GuptaSequelBaseServer/NetWareSQL" }, { 0x03e1, "UnivelUnixware" }, { 0x03e4, "UnivelUnixware" }, { 0x03fc, "IntelNetport" }, { 0x03fd, "PrintServerQueue" }, { 0x040A, "ipnServer" }, { 0x040D, "LVERRMAN" }, { 0x040E, "LVLIC" }, { 0x0414, "NET Silicon (DPI)/Kyocera" }, { 0x0429, "SiteLockVirus" }, { 0x0432, "UFHELPR???" }, { 0x0433, "Synoptics281xAdvancedSNMPAgent" }, { 0x0444, "MicrosoftNT SNA Server" }, { 0x0448, "Oracle" }, { 0x044c, "ARCserve5.01" }, { 0x0457, "CanonGP55" }, { 0x045a, "QMS Printers" }, { 0x045b, "DellSCSI Array" }, { 0x0491, "NetBlazerModems" }, { 0x04ac, "OnTimeScheduler" }, { 0x04b0, "CD-Net" }, { 0x0513, "EmulexNQA" }, { 0x0520, "SiteLockChecks" }, { 0x0529, "SiteLockChecks" }, { 0x052d, "CitrixOS2 AppServer" }, { 0x0535, "Tektronix" }, { 0x0536, "Milan" }, { 0x055d, "Attachmate SNA gateway" }, { 0x056b, "IBM8235 ModemServer" }, { 0x056c, "ShivaLanRover/E PLUS" }, { 0x056d, "ShivaLanRover/T PLUS" }, { 0x0580, "McAfeeNetShield" }, { 0x05B8, "NLM to workstation communication (Revelation Software)" }, { 0x05BA, "CompatibleSystemsRouters" }, { 0x05BE, "CheyenneHierarchicalStorageManager" }, { 0x0606, "JCWatermarkImaging" }, { 0x060c, "AXISNetworkPrinter" }, { 0x0610, "AdaptecSCSIManagement" }, { 0x0621, "IBM AntiVirus" }, { 0x0640, "Windows95 RemoteRegistryService" }, { 0x064e, "MicrosoftIIS" }, { 0x067b, "Microsoft Win95/98 File and Print Sharing for NetWare" }, { 0x067c, "Microsoft Win95/98 File and Print Sharing for NetWare" }, { 0x076C, "Xerox" }, { 0x079b, "ShivaLanRover/E 115" }, { 0x079c, "ShivaLanRover/T 115" }, { 0x07B4, "CubixWorldDesk" }, { 0x07c2, "Quarterdeck IWare Connect V2.x NLM" }, { 0x07c1, "Quarterdeck IWare Connect V3.x NLM" }, { 0x0810, "ELAN License Server Demo" }, { 0x0824, "ShivaLanRoverAccessSwitch/E" }, { 0x086a, "ISSC Collector" }, { 0x087f, "ISSC DAS AgentAIX" }, { 0x0880, "Intel Netport PRO" }, { 0x0881, "Intel Netport PRO" }, { 0x0b29, "SiteLock" }, { 0x0c29, "SiteLockApplications" }, { 0x0c2c, "LicensingServer" }, { 0x2101, "PerformanceTechnologyInstantInternet" }, { 0x2380, "LAI SiteLock" }, { 0x238c, "MeetingMaker" }, { 0x4808, "SiteLockServer/SiteLockMetering" }, { 0x5555, "SiteLockUser" }, { 0x6312, "Tapeware" }, { 0x6f00, "RabbitGateway" }, { 0x7703, "MODEM" }, { 0x8002, "NetPortPrinters" }, { 0x8008, "WordPerfectNetworkVersion" }, { 0x85BE, "Cisco EIGRP" }, { 0x8888, "WordPerfectNetworkVersion/QuickNetworkManagement" }, { 0x9000, "McAfeeNetShield" }, { 0x9604, "CSA-NT_MON" }, { 0xb6a8, "OceanIsleReachoutRemoteControl" }, { 0xf11f, "SiteLockMetering" }, { 0xf1ff, "SiteLock" }, { 0xf503, "Microsoft SQL Server" }, { 0xF905, "IBM TimeAndPlace" }, { 0xfbfb, "TopCallIII FaxServer" }, { 0xffff, "AnyService/Wildcard" }, { 0, (char *)0 } }; static void init_ipxsaparray(netdissect_options *ndo) { register int i; register struct hnamemem *table; for (i = 0; ipxsap_db[i].s != NULL; i++) { int j = htons(ipxsap_db[i].v) & (HASHNAMESIZE-1); table = &ipxsaptable[j]; while (table->name) table = table->nxt; table->name = ipxsap_db[i].s; table->addr = htons(ipxsap_db[i].v); table->nxt = newhnamemem(ndo); } } /* * Initialize the address to name translation machinery. We map all * non-local IP addresses to numeric addresses if ndo->ndo_fflag is true * (i.e., to prevent blocking on the nameserver). localnet is the IP address * of the local network. mask is its subnet mask. */ void init_addrtoname(netdissect_options *ndo, uint32_t localnet, uint32_t mask) { if (ndo->ndo_fflag) { f_localnet = localnet; f_netmask = mask; } if (ndo->ndo_nflag) /* * Simplest way to suppress names. */ return; init_etherarray(ndo); init_servarray(ndo); init_eprotoarray(ndo); init_protoidarray(ndo); init_ipxsaparray(ndo); } const char * dnaddr_string(netdissect_options *ndo, u_short dnaddr) { register struct hnamemem *tp; for (tp = &dnaddrtable[dnaddr & (HASHNAMESIZE-1)]; tp->nxt != NULL; tp = tp->nxt) if (tp->addr == dnaddr) return (tp->name); tp->addr = dnaddr; tp->nxt = newhnamemem(ndo); if (ndo->ndo_nflag) tp->name = dnnum_string(ndo, dnaddr); else tp->name = dnname_string(ndo, dnaddr); return(tp->name); } /* Return a zero'ed hnamemem struct and cuts down on calloc() overhead */ struct hnamemem * newhnamemem(netdissect_options *ndo) { register struct hnamemem *p; static struct hnamemem *ptr = NULL; static u_int num = 0; if (num <= 0) { num = 64; ptr = (struct hnamemem *)calloc(num, sizeof (*ptr)); if (ptr == NULL) (*ndo->ndo_error)(ndo, "newhnamemem: calloc"); } --num; p = ptr++; return (p); } /* Return a zero'ed h6namemem struct and cuts down on calloc() overhead */ struct h6namemem * newh6namemem(netdissect_options *ndo) { register struct h6namemem *p; static struct h6namemem *ptr = NULL; static u_int num = 0; if (num <= 0) { num = 64; ptr = (struct h6namemem *)calloc(num, sizeof (*ptr)); if (ptr == NULL) (*ndo->ndo_error)(ndo, "newh6namemem: calloc"); } --num; p = ptr++; return (p); } /* Represent TCI part of the 802.1Q 4-octet tag as text. */ const char * ieee8021q_tci_string(const uint16_t tci) { static char buf[128]; snprintf(buf, sizeof(buf), "vlan %u, p %u%s", tci & 0xfff, tci >> 13, (tci & 0x1000) ? ", DEI" : ""); return buf; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2640_0
crossvul-cpp_data_good_2911_1
/* * USB Attached SCSI * Note that this is not the same as the USB Mass Storage driver * * Copyright Hans de Goede <hdegoede@redhat.com> for Red Hat, Inc. 2013 - 2016 * Copyright Matthew Wilcox for Intel Corp, 2010 * Copyright Sarah Sharp for Intel Corp, 2010 * * Distributed under the terms of the GNU GPL, version two. */ #include <linux/blkdev.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/module.h> #include <linux/usb.h> #include <linux/usb_usual.h> #include <linux/usb/hcd.h> #include <linux/usb/storage.h> #include <linux/usb/uas.h> #include <scsi/scsi.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_dbg.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include "uas-detect.h" #include "scsiglue.h" #define MAX_CMNDS 256 struct uas_dev_info { struct usb_interface *intf; struct usb_device *udev; struct usb_anchor cmd_urbs; struct usb_anchor sense_urbs; struct usb_anchor data_urbs; unsigned long flags; int qdepth, resetting; unsigned cmd_pipe, status_pipe, data_in_pipe, data_out_pipe; unsigned use_streams:1; unsigned shutdown:1; struct scsi_cmnd *cmnd[MAX_CMNDS]; spinlock_t lock; struct work_struct work; }; enum { SUBMIT_STATUS_URB = BIT(1), ALLOC_DATA_IN_URB = BIT(2), SUBMIT_DATA_IN_URB = BIT(3), ALLOC_DATA_OUT_URB = BIT(4), SUBMIT_DATA_OUT_URB = BIT(5), ALLOC_CMD_URB = BIT(6), SUBMIT_CMD_URB = BIT(7), COMMAND_INFLIGHT = BIT(8), DATA_IN_URB_INFLIGHT = BIT(9), DATA_OUT_URB_INFLIGHT = BIT(10), COMMAND_ABORTED = BIT(11), IS_IN_WORK_LIST = BIT(12), }; /* Overrides scsi_pointer */ struct uas_cmd_info { unsigned int state; unsigned int uas_tag; struct urb *cmd_urb; struct urb *data_in_urb; struct urb *data_out_urb; }; /* I hate forward declarations, but I actually have a loop */ static int uas_submit_urbs(struct scsi_cmnd *cmnd, struct uas_dev_info *devinfo); static void uas_do_work(struct work_struct *work); static int uas_try_complete(struct scsi_cmnd *cmnd, const char *caller); static void uas_free_streams(struct uas_dev_info *devinfo); static void uas_log_cmd_state(struct scsi_cmnd *cmnd, const char *prefix, int status); static void uas_do_work(struct work_struct *work) { struct uas_dev_info *devinfo = container_of(work, struct uas_dev_info, work); struct uas_cmd_info *cmdinfo; struct scsi_cmnd *cmnd; unsigned long flags; int i, err; spin_lock_irqsave(&devinfo->lock, flags); if (devinfo->resetting) goto out; for (i = 0; i < devinfo->qdepth; i++) { if (!devinfo->cmnd[i]) continue; cmnd = devinfo->cmnd[i]; cmdinfo = (void *)&cmnd->SCp; if (!(cmdinfo->state & IS_IN_WORK_LIST)) continue; err = uas_submit_urbs(cmnd, cmnd->device->hostdata); if (!err) cmdinfo->state &= ~IS_IN_WORK_LIST; else schedule_work(&devinfo->work); } out: spin_unlock_irqrestore(&devinfo->lock, flags); } static void uas_add_work(struct uas_cmd_info *cmdinfo) { struct scsi_pointer *scp = (void *)cmdinfo; struct scsi_cmnd *cmnd = container_of(scp, struct scsi_cmnd, SCp); struct uas_dev_info *devinfo = cmnd->device->hostdata; lockdep_assert_held(&devinfo->lock); cmdinfo->state |= IS_IN_WORK_LIST; schedule_work(&devinfo->work); } static void uas_zap_pending(struct uas_dev_info *devinfo, int result) { struct uas_cmd_info *cmdinfo; struct scsi_cmnd *cmnd; unsigned long flags; int i, err; spin_lock_irqsave(&devinfo->lock, flags); for (i = 0; i < devinfo->qdepth; i++) { if (!devinfo->cmnd[i]) continue; cmnd = devinfo->cmnd[i]; cmdinfo = (void *)&cmnd->SCp; uas_log_cmd_state(cmnd, __func__, 0); /* Sense urbs were killed, clear COMMAND_INFLIGHT manually */ cmdinfo->state &= ~COMMAND_INFLIGHT; cmnd->result = result << 16; err = uas_try_complete(cmnd, __func__); WARN_ON(err != 0); } spin_unlock_irqrestore(&devinfo->lock, flags); } static void uas_sense(struct urb *urb, struct scsi_cmnd *cmnd) { struct sense_iu *sense_iu = urb->transfer_buffer; struct scsi_device *sdev = cmnd->device; if (urb->actual_length > 16) { unsigned len = be16_to_cpup(&sense_iu->len); if (len + 16 != urb->actual_length) { int newlen = min(len + 16, urb->actual_length) - 16; if (newlen < 0) newlen = 0; sdev_printk(KERN_INFO, sdev, "%s: urb length %d " "disagrees with IU sense data length %d, " "using %d bytes of sense data\n", __func__, urb->actual_length, len, newlen); len = newlen; } memcpy(cmnd->sense_buffer, sense_iu->sense, len); } cmnd->result = sense_iu->status; } static void uas_log_cmd_state(struct scsi_cmnd *cmnd, const char *prefix, int status) { struct uas_cmd_info *ci = (void *)&cmnd->SCp; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; scmd_printk(KERN_INFO, cmnd, "%s %d uas-tag %d inflight:%s%s%s%s%s%s%s%s%s%s%s%s ", prefix, status, cmdinfo->uas_tag, (ci->state & SUBMIT_STATUS_URB) ? " s-st" : "", (ci->state & ALLOC_DATA_IN_URB) ? " a-in" : "", (ci->state & SUBMIT_DATA_IN_URB) ? " s-in" : "", (ci->state & ALLOC_DATA_OUT_URB) ? " a-out" : "", (ci->state & SUBMIT_DATA_OUT_URB) ? " s-out" : "", (ci->state & ALLOC_CMD_URB) ? " a-cmd" : "", (ci->state & SUBMIT_CMD_URB) ? " s-cmd" : "", (ci->state & COMMAND_INFLIGHT) ? " CMD" : "", (ci->state & DATA_IN_URB_INFLIGHT) ? " IN" : "", (ci->state & DATA_OUT_URB_INFLIGHT) ? " OUT" : "", (ci->state & COMMAND_ABORTED) ? " abort" : "", (ci->state & IS_IN_WORK_LIST) ? " work" : ""); scsi_print_command(cmnd); } static void uas_free_unsubmitted_urbs(struct scsi_cmnd *cmnd) { struct uas_cmd_info *cmdinfo; if (!cmnd) return; cmdinfo = (void *)&cmnd->SCp; if (cmdinfo->state & SUBMIT_CMD_URB) usb_free_urb(cmdinfo->cmd_urb); /* data urbs may have never gotten their submit flag set */ if (!(cmdinfo->state & DATA_IN_URB_INFLIGHT)) usb_free_urb(cmdinfo->data_in_urb); if (!(cmdinfo->state & DATA_OUT_URB_INFLIGHT)) usb_free_urb(cmdinfo->data_out_urb); } static int uas_try_complete(struct scsi_cmnd *cmnd, const char *caller) { struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata; lockdep_assert_held(&devinfo->lock); if (cmdinfo->state & (COMMAND_INFLIGHT | DATA_IN_URB_INFLIGHT | DATA_OUT_URB_INFLIGHT | COMMAND_ABORTED)) return -EBUSY; devinfo->cmnd[cmdinfo->uas_tag - 1] = NULL; uas_free_unsubmitted_urbs(cmnd); cmnd->scsi_done(cmnd); return 0; } static void uas_xfer_data(struct urb *urb, struct scsi_cmnd *cmnd, unsigned direction) { struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; int err; cmdinfo->state |= direction | SUBMIT_STATUS_URB; err = uas_submit_urbs(cmnd, cmnd->device->hostdata); if (err) { uas_add_work(cmdinfo); } } static bool uas_evaluate_response_iu(struct response_iu *riu, struct scsi_cmnd *cmnd) { u8 response_code = riu->response_code; switch (response_code) { case RC_INCORRECT_LUN: cmnd->result = DID_BAD_TARGET << 16; break; case RC_TMF_SUCCEEDED: cmnd->result = DID_OK << 16; break; case RC_TMF_NOT_SUPPORTED: cmnd->result = DID_TARGET_FAILURE << 16; break; default: uas_log_cmd_state(cmnd, "response iu", response_code); cmnd->result = DID_ERROR << 16; break; } return response_code == RC_TMF_SUCCEEDED; } static void uas_stat_cmplt(struct urb *urb) { struct iu *iu = urb->transfer_buffer; struct Scsi_Host *shost = urb->context; struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; struct urb *data_in_urb = NULL; struct urb *data_out_urb = NULL; struct scsi_cmnd *cmnd; struct uas_cmd_info *cmdinfo; unsigned long flags; unsigned int idx; int status = urb->status; bool success; spin_lock_irqsave(&devinfo->lock, flags); if (devinfo->resetting) goto out; if (status) { if (status != -ENOENT && status != -ECONNRESET && status != -ESHUTDOWN) dev_err(&urb->dev->dev, "stat urb: status %d\n", status); goto out; } idx = be16_to_cpup(&iu->tag) - 1; if (idx >= MAX_CMNDS || !devinfo->cmnd[idx]) { dev_err(&urb->dev->dev, "stat urb: no pending cmd for uas-tag %d\n", idx + 1); goto out; } cmnd = devinfo->cmnd[idx]; cmdinfo = (void *)&cmnd->SCp; if (!(cmdinfo->state & COMMAND_INFLIGHT)) { uas_log_cmd_state(cmnd, "unexpected status cmplt", 0); goto out; } switch (iu->iu_id) { case IU_ID_STATUS: uas_sense(urb, cmnd); if (cmnd->result != 0) { /* cancel data transfers on error */ data_in_urb = usb_get_urb(cmdinfo->data_in_urb); data_out_urb = usb_get_urb(cmdinfo->data_out_urb); } cmdinfo->state &= ~COMMAND_INFLIGHT; uas_try_complete(cmnd, __func__); break; case IU_ID_READ_READY: if (!cmdinfo->data_in_urb || (cmdinfo->state & DATA_IN_URB_INFLIGHT)) { uas_log_cmd_state(cmnd, "unexpected read rdy", 0); break; } uas_xfer_data(urb, cmnd, SUBMIT_DATA_IN_URB); break; case IU_ID_WRITE_READY: if (!cmdinfo->data_out_urb || (cmdinfo->state & DATA_OUT_URB_INFLIGHT)) { uas_log_cmd_state(cmnd, "unexpected write rdy", 0); break; } uas_xfer_data(urb, cmnd, SUBMIT_DATA_OUT_URB); break; case IU_ID_RESPONSE: cmdinfo->state &= ~COMMAND_INFLIGHT; success = uas_evaluate_response_iu((struct response_iu *)iu, cmnd); if (!success) { /* Error, cancel data transfers */ data_in_urb = usb_get_urb(cmdinfo->data_in_urb); data_out_urb = usb_get_urb(cmdinfo->data_out_urb); } uas_try_complete(cmnd, __func__); break; default: uas_log_cmd_state(cmnd, "bogus IU", iu->iu_id); } out: usb_free_urb(urb); spin_unlock_irqrestore(&devinfo->lock, flags); /* Unlinking of data urbs must be done without holding the lock */ if (data_in_urb) { usb_unlink_urb(data_in_urb); usb_put_urb(data_in_urb); } if (data_out_urb) { usb_unlink_urb(data_out_urb); usb_put_urb(data_out_urb); } } static void uas_data_cmplt(struct urb *urb) { struct scsi_cmnd *cmnd = urb->context; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata; struct scsi_data_buffer *sdb = NULL; unsigned long flags; int status = urb->status; spin_lock_irqsave(&devinfo->lock, flags); if (cmdinfo->data_in_urb == urb) { sdb = scsi_in(cmnd); cmdinfo->state &= ~DATA_IN_URB_INFLIGHT; cmdinfo->data_in_urb = NULL; } else if (cmdinfo->data_out_urb == urb) { sdb = scsi_out(cmnd); cmdinfo->state &= ~DATA_OUT_URB_INFLIGHT; cmdinfo->data_out_urb = NULL; } if (sdb == NULL) { WARN_ON_ONCE(1); goto out; } if (devinfo->resetting) goto out; /* Data urbs should not complete before the cmd urb is submitted */ if (cmdinfo->state & SUBMIT_CMD_URB) { uas_log_cmd_state(cmnd, "unexpected data cmplt", 0); goto out; } if (status) { if (status != -ENOENT && status != -ECONNRESET && status != -ESHUTDOWN) uas_log_cmd_state(cmnd, "data cmplt err", status); /* error: no data transfered */ sdb->resid = sdb->length; } else { sdb->resid = sdb->length - urb->actual_length; } uas_try_complete(cmnd, __func__); out: usb_free_urb(urb); spin_unlock_irqrestore(&devinfo->lock, flags); } static void uas_cmd_cmplt(struct urb *urb) { if (urb->status) dev_err(&urb->dev->dev, "cmd cmplt err %d\n", urb->status); usb_free_urb(urb); } static struct urb *uas_alloc_data_urb(struct uas_dev_info *devinfo, gfp_t gfp, struct scsi_cmnd *cmnd, enum dma_data_direction dir) { struct usb_device *udev = devinfo->udev; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct urb *urb = usb_alloc_urb(0, gfp); struct scsi_data_buffer *sdb = (dir == DMA_FROM_DEVICE) ? scsi_in(cmnd) : scsi_out(cmnd); unsigned int pipe = (dir == DMA_FROM_DEVICE) ? devinfo->data_in_pipe : devinfo->data_out_pipe; if (!urb) goto out; usb_fill_bulk_urb(urb, udev, pipe, NULL, sdb->length, uas_data_cmplt, cmnd); if (devinfo->use_streams) urb->stream_id = cmdinfo->uas_tag; urb->num_sgs = udev->bus->sg_tablesize ? sdb->table.nents : 0; urb->sg = sdb->table.sgl; out: return urb; } static struct urb *uas_alloc_sense_urb(struct uas_dev_info *devinfo, gfp_t gfp, struct scsi_cmnd *cmnd) { struct usb_device *udev = devinfo->udev; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct urb *urb = usb_alloc_urb(0, gfp); struct sense_iu *iu; if (!urb) goto out; iu = kzalloc(sizeof(*iu), gfp); if (!iu) goto free; usb_fill_bulk_urb(urb, udev, devinfo->status_pipe, iu, sizeof(*iu), uas_stat_cmplt, cmnd->device->host); if (devinfo->use_streams) urb->stream_id = cmdinfo->uas_tag; urb->transfer_flags |= URB_FREE_BUFFER; out: return urb; free: usb_free_urb(urb); return NULL; } static struct urb *uas_alloc_cmd_urb(struct uas_dev_info *devinfo, gfp_t gfp, struct scsi_cmnd *cmnd) { struct usb_device *udev = devinfo->udev; struct scsi_device *sdev = cmnd->device; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct urb *urb = usb_alloc_urb(0, gfp); struct command_iu *iu; int len; if (!urb) goto out; len = cmnd->cmd_len - 16; if (len < 0) len = 0; len = ALIGN(len, 4); iu = kzalloc(sizeof(*iu) + len, gfp); if (!iu) goto free; iu->iu_id = IU_ID_COMMAND; iu->tag = cpu_to_be16(cmdinfo->uas_tag); iu->prio_attr = UAS_SIMPLE_TAG; iu->len = len; int_to_scsilun(sdev->lun, &iu->lun); memcpy(iu->cdb, cmnd->cmnd, cmnd->cmd_len); usb_fill_bulk_urb(urb, udev, devinfo->cmd_pipe, iu, sizeof(*iu) + len, uas_cmd_cmplt, NULL); urb->transfer_flags |= URB_FREE_BUFFER; out: return urb; free: usb_free_urb(urb); return NULL; } /* * Why should I request the Status IU before sending the Command IU? Spec * says to, but also says the device may receive them in any order. Seems * daft to me. */ static struct urb *uas_submit_sense_urb(struct scsi_cmnd *cmnd, gfp_t gfp) { struct uas_dev_info *devinfo = cmnd->device->hostdata; struct urb *urb; int err; urb = uas_alloc_sense_urb(devinfo, gfp, cmnd); if (!urb) return NULL; usb_anchor_urb(urb, &devinfo->sense_urbs); err = usb_submit_urb(urb, gfp); if (err) { usb_unanchor_urb(urb); uas_log_cmd_state(cmnd, "sense submit err", err); usb_free_urb(urb); return NULL; } return urb; } static int uas_submit_urbs(struct scsi_cmnd *cmnd, struct uas_dev_info *devinfo) { struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct urb *urb; int err; lockdep_assert_held(&devinfo->lock); if (cmdinfo->state & SUBMIT_STATUS_URB) { urb = uas_submit_sense_urb(cmnd, GFP_ATOMIC); if (!urb) return SCSI_MLQUEUE_DEVICE_BUSY; cmdinfo->state &= ~SUBMIT_STATUS_URB; } if (cmdinfo->state & ALLOC_DATA_IN_URB) { cmdinfo->data_in_urb = uas_alloc_data_urb(devinfo, GFP_ATOMIC, cmnd, DMA_FROM_DEVICE); if (!cmdinfo->data_in_urb) return SCSI_MLQUEUE_DEVICE_BUSY; cmdinfo->state &= ~ALLOC_DATA_IN_URB; } if (cmdinfo->state & SUBMIT_DATA_IN_URB) { usb_anchor_urb(cmdinfo->data_in_urb, &devinfo->data_urbs); err = usb_submit_urb(cmdinfo->data_in_urb, GFP_ATOMIC); if (err) { usb_unanchor_urb(cmdinfo->data_in_urb); uas_log_cmd_state(cmnd, "data in submit err", err); return SCSI_MLQUEUE_DEVICE_BUSY; } cmdinfo->state &= ~SUBMIT_DATA_IN_URB; cmdinfo->state |= DATA_IN_URB_INFLIGHT; } if (cmdinfo->state & ALLOC_DATA_OUT_URB) { cmdinfo->data_out_urb = uas_alloc_data_urb(devinfo, GFP_ATOMIC, cmnd, DMA_TO_DEVICE); if (!cmdinfo->data_out_urb) return SCSI_MLQUEUE_DEVICE_BUSY; cmdinfo->state &= ~ALLOC_DATA_OUT_URB; } if (cmdinfo->state & SUBMIT_DATA_OUT_URB) { usb_anchor_urb(cmdinfo->data_out_urb, &devinfo->data_urbs); err = usb_submit_urb(cmdinfo->data_out_urb, GFP_ATOMIC); if (err) { usb_unanchor_urb(cmdinfo->data_out_urb); uas_log_cmd_state(cmnd, "data out submit err", err); return SCSI_MLQUEUE_DEVICE_BUSY; } cmdinfo->state &= ~SUBMIT_DATA_OUT_URB; cmdinfo->state |= DATA_OUT_URB_INFLIGHT; } if (cmdinfo->state & ALLOC_CMD_URB) { cmdinfo->cmd_urb = uas_alloc_cmd_urb(devinfo, GFP_ATOMIC, cmnd); if (!cmdinfo->cmd_urb) return SCSI_MLQUEUE_DEVICE_BUSY; cmdinfo->state &= ~ALLOC_CMD_URB; } if (cmdinfo->state & SUBMIT_CMD_URB) { usb_anchor_urb(cmdinfo->cmd_urb, &devinfo->cmd_urbs); err = usb_submit_urb(cmdinfo->cmd_urb, GFP_ATOMIC); if (err) { usb_unanchor_urb(cmdinfo->cmd_urb); uas_log_cmd_state(cmnd, "cmd submit err", err); return SCSI_MLQUEUE_DEVICE_BUSY; } cmdinfo->cmd_urb = NULL; cmdinfo->state &= ~SUBMIT_CMD_URB; cmdinfo->state |= COMMAND_INFLIGHT; } return 0; } static int uas_queuecommand_lck(struct scsi_cmnd *cmnd, void (*done)(struct scsi_cmnd *)) { struct scsi_device *sdev = cmnd->device; struct uas_dev_info *devinfo = sdev->hostdata; struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; unsigned long flags; int idx, err; BUILD_BUG_ON(sizeof(struct uas_cmd_info) > sizeof(struct scsi_pointer)); /* Re-check scsi_block_requests now that we've the host-lock */ if (cmnd->device->host->host_self_blocked) return SCSI_MLQUEUE_DEVICE_BUSY; if ((devinfo->flags & US_FL_NO_ATA_1X) && (cmnd->cmnd[0] == ATA_12 || cmnd->cmnd[0] == ATA_16)) { memcpy(cmnd->sense_buffer, usb_stor_sense_invalidCDB, sizeof(usb_stor_sense_invalidCDB)); cmnd->result = SAM_STAT_CHECK_CONDITION; cmnd->scsi_done(cmnd); return 0; } spin_lock_irqsave(&devinfo->lock, flags); if (devinfo->resetting) { cmnd->result = DID_ERROR << 16; cmnd->scsi_done(cmnd); spin_unlock_irqrestore(&devinfo->lock, flags); return 0; } /* Find a free uas-tag */ for (idx = 0; idx < devinfo->qdepth; idx++) { if (!devinfo->cmnd[idx]) break; } if (idx == devinfo->qdepth) { spin_unlock_irqrestore(&devinfo->lock, flags); return SCSI_MLQUEUE_DEVICE_BUSY; } cmnd->scsi_done = done; memset(cmdinfo, 0, sizeof(*cmdinfo)); cmdinfo->uas_tag = idx + 1; /* uas-tag == usb-stream-id, so 1 based */ cmdinfo->state = SUBMIT_STATUS_URB | ALLOC_CMD_URB | SUBMIT_CMD_URB; switch (cmnd->sc_data_direction) { case DMA_FROM_DEVICE: cmdinfo->state |= ALLOC_DATA_IN_URB | SUBMIT_DATA_IN_URB; break; case DMA_BIDIRECTIONAL: cmdinfo->state |= ALLOC_DATA_IN_URB | SUBMIT_DATA_IN_URB; case DMA_TO_DEVICE: cmdinfo->state |= ALLOC_DATA_OUT_URB | SUBMIT_DATA_OUT_URB; case DMA_NONE: break; } if (!devinfo->use_streams) cmdinfo->state &= ~(SUBMIT_DATA_IN_URB | SUBMIT_DATA_OUT_URB); err = uas_submit_urbs(cmnd, devinfo); if (err) { /* If we did nothing, give up now */ if (cmdinfo->state & SUBMIT_STATUS_URB) { spin_unlock_irqrestore(&devinfo->lock, flags); return SCSI_MLQUEUE_DEVICE_BUSY; } uas_add_work(cmdinfo); } devinfo->cmnd[idx] = cmnd; spin_unlock_irqrestore(&devinfo->lock, flags); return 0; } static DEF_SCSI_QCMD(uas_queuecommand) /* * For now we do not support actually sending an abort to the device, so * this eh always fails. Still we must define it to make sure that we've * dropped all references to the cmnd in question once this function exits. */ static int uas_eh_abort_handler(struct scsi_cmnd *cmnd) { struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp; struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata; struct urb *data_in_urb = NULL; struct urb *data_out_urb = NULL; unsigned long flags; spin_lock_irqsave(&devinfo->lock, flags); uas_log_cmd_state(cmnd, __func__, 0); /* Ensure that try_complete does not call scsi_done */ cmdinfo->state |= COMMAND_ABORTED; /* Drop all refs to this cmnd, kill data urbs to break their ref */ devinfo->cmnd[cmdinfo->uas_tag - 1] = NULL; if (cmdinfo->state & DATA_IN_URB_INFLIGHT) data_in_urb = usb_get_urb(cmdinfo->data_in_urb); if (cmdinfo->state & DATA_OUT_URB_INFLIGHT) data_out_urb = usb_get_urb(cmdinfo->data_out_urb); uas_free_unsubmitted_urbs(cmnd); spin_unlock_irqrestore(&devinfo->lock, flags); if (data_in_urb) { usb_kill_urb(data_in_urb); usb_put_urb(data_in_urb); } if (data_out_urb) { usb_kill_urb(data_out_urb); usb_put_urb(data_out_urb); } return FAILED; } static int uas_eh_device_reset_handler(struct scsi_cmnd *cmnd) { struct scsi_device *sdev = cmnd->device; struct uas_dev_info *devinfo = sdev->hostdata; struct usb_device *udev = devinfo->udev; unsigned long flags; int err; err = usb_lock_device_for_reset(udev, devinfo->intf); if (err) { shost_printk(KERN_ERR, sdev->host, "%s FAILED to get lock err %d\n", __func__, err); return FAILED; } shost_printk(KERN_INFO, sdev->host, "%s start\n", __func__); spin_lock_irqsave(&devinfo->lock, flags); devinfo->resetting = 1; spin_unlock_irqrestore(&devinfo->lock, flags); usb_kill_anchored_urbs(&devinfo->cmd_urbs); usb_kill_anchored_urbs(&devinfo->sense_urbs); usb_kill_anchored_urbs(&devinfo->data_urbs); uas_zap_pending(devinfo, DID_RESET); err = usb_reset_device(udev); spin_lock_irqsave(&devinfo->lock, flags); devinfo->resetting = 0; spin_unlock_irqrestore(&devinfo->lock, flags); usb_unlock_device(udev); if (err) { shost_printk(KERN_INFO, sdev->host, "%s FAILED err %d\n", __func__, err); return FAILED; } shost_printk(KERN_INFO, sdev->host, "%s success\n", __func__); return SUCCESS; } static int uas_target_alloc(struct scsi_target *starget) { struct uas_dev_info *devinfo = (struct uas_dev_info *) dev_to_shost(starget->dev.parent)->hostdata; if (devinfo->flags & US_FL_NO_REPORT_LUNS) starget->no_report_luns = 1; return 0; } static int uas_slave_alloc(struct scsi_device *sdev) { struct uas_dev_info *devinfo = (struct uas_dev_info *)sdev->host->hostdata; sdev->hostdata = devinfo; /* * USB has unusual DMA-alignment requirements: Although the * starting address of each scatter-gather element doesn't matter, * the length of each element except the last must be divisible * by the Bulk maxpacket value. There's currently no way to * express this by block-layer constraints, so we'll cop out * and simply require addresses to be aligned at 512-byte * boundaries. This is okay since most block I/O involves * hardware sectors that are multiples of 512 bytes in length, * and since host controllers up through USB 2.0 have maxpacket * values no larger than 512. * * But it doesn't suffice for Wireless USB, where Bulk maxpacket * values can be as large as 2048. To make that work properly * will require changes to the block layer. */ blk_queue_update_dma_alignment(sdev->request_queue, (512 - 1)); if (devinfo->flags & US_FL_MAX_SECTORS_64) blk_queue_max_hw_sectors(sdev->request_queue, 64); else if (devinfo->flags & US_FL_MAX_SECTORS_240) blk_queue_max_hw_sectors(sdev->request_queue, 240); return 0; } static int uas_slave_configure(struct scsi_device *sdev) { struct uas_dev_info *devinfo = sdev->hostdata; if (devinfo->flags & US_FL_NO_REPORT_OPCODES) sdev->no_report_opcodes = 1; /* A few buggy USB-ATA bridges don't understand FUA */ if (devinfo->flags & US_FL_BROKEN_FUA) sdev->broken_fua = 1; scsi_change_queue_depth(sdev, devinfo->qdepth - 2); return 0; } static struct scsi_host_template uas_host_template = { .module = THIS_MODULE, .name = "uas", .queuecommand = uas_queuecommand, .target_alloc = uas_target_alloc, .slave_alloc = uas_slave_alloc, .slave_configure = uas_slave_configure, .eh_abort_handler = uas_eh_abort_handler, .eh_device_reset_handler = uas_eh_device_reset_handler, .this_id = -1, .sg_tablesize = SG_NONE, .skip_settle_delay = 1, }; #define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \ vendorName, productName, useProtocol, useTransport, \ initFunction, flags) \ { USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \ .driver_info = (flags) } static struct usb_device_id uas_usb_ids[] = { # include "unusual_uas.h" { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, USB_SC_SCSI, USB_PR_BULK) }, { USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, USB_SC_SCSI, USB_PR_UAS) }, { } }; MODULE_DEVICE_TABLE(usb, uas_usb_ids); #undef UNUSUAL_DEV static int uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { struct usb_host_interface *alt; alt = uas_find_uas_alt_setting(intf); if (!alt) return -ENODEV; return usb_set_interface(udev, alt->desc.bInterfaceNumber, alt->desc.bAlternateSetting); } static int uas_configure_endpoints(struct uas_dev_info *devinfo) { struct usb_host_endpoint *eps[4] = { }; struct usb_device *udev = devinfo->udev; int r; r = uas_find_endpoints(devinfo->intf->cur_altsetting, eps); if (r) return r; devinfo->cmd_pipe = usb_sndbulkpipe(udev, usb_endpoint_num(&eps[0]->desc)); devinfo->status_pipe = usb_rcvbulkpipe(udev, usb_endpoint_num(&eps[1]->desc)); devinfo->data_in_pipe = usb_rcvbulkpipe(udev, usb_endpoint_num(&eps[2]->desc)); devinfo->data_out_pipe = usb_sndbulkpipe(udev, usb_endpoint_num(&eps[3]->desc)); if (udev->speed < USB_SPEED_SUPER) { devinfo->qdepth = 32; devinfo->use_streams = 0; } else { devinfo->qdepth = usb_alloc_streams(devinfo->intf, eps + 1, 3, MAX_CMNDS, GFP_NOIO); if (devinfo->qdepth < 0) return devinfo->qdepth; devinfo->use_streams = 1; } return 0; } static void uas_free_streams(struct uas_dev_info *devinfo) { struct usb_device *udev = devinfo->udev; struct usb_host_endpoint *eps[3]; eps[0] = usb_pipe_endpoint(udev, devinfo->status_pipe); eps[1] = usb_pipe_endpoint(udev, devinfo->data_in_pipe); eps[2] = usb_pipe_endpoint(udev, devinfo->data_out_pipe); usb_free_streams(devinfo->intf, eps, 3, GFP_NOIO); } static int uas_probe(struct usb_interface *intf, const struct usb_device_id *id) { int result = -ENOMEM; struct Scsi_Host *shost = NULL; struct uas_dev_info *devinfo; struct usb_device *udev = interface_to_usbdev(intf); unsigned long dev_flags; if (!uas_use_uas_driver(intf, id, &dev_flags)) return -ENODEV; if (uas_switch_interface(udev, intf)) return -ENODEV; shost = scsi_host_alloc(&uas_host_template, sizeof(struct uas_dev_info)); if (!shost) goto set_alt0; shost->max_cmd_len = 16 + 252; shost->max_id = 1; shost->max_lun = 256; shost->max_channel = 0; shost->sg_tablesize = udev->bus->sg_tablesize; devinfo = (struct uas_dev_info *)shost->hostdata; devinfo->intf = intf; devinfo->udev = udev; devinfo->resetting = 0; devinfo->shutdown = 0; devinfo->flags = dev_flags; init_usb_anchor(&devinfo->cmd_urbs); init_usb_anchor(&devinfo->sense_urbs); init_usb_anchor(&devinfo->data_urbs); spin_lock_init(&devinfo->lock); INIT_WORK(&devinfo->work, uas_do_work); result = uas_configure_endpoints(devinfo); if (result) goto set_alt0; /* * 1 tag is reserved for untagged commands + * 1 tag to avoid off by one errors in some bridge firmwares */ shost->can_queue = devinfo->qdepth - 2; usb_set_intfdata(intf, shost); result = scsi_add_host(shost, &intf->dev); if (result) goto free_streams; scsi_scan_host(shost); return result; free_streams: uas_free_streams(devinfo); usb_set_intfdata(intf, NULL); set_alt0: usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, 0); if (shost) scsi_host_put(shost); return result; } static int uas_cmnd_list_empty(struct uas_dev_info *devinfo) { unsigned long flags; int i, r = 1; spin_lock_irqsave(&devinfo->lock, flags); for (i = 0; i < devinfo->qdepth; i++) { if (devinfo->cmnd[i]) { r = 0; /* Not empty */ break; } } spin_unlock_irqrestore(&devinfo->lock, flags); return r; } /* * Wait for any pending cmnds to complete, on usb-2 sense_urbs may temporarily * get empty while there still is more work to do due to sense-urbs completing * with a READ/WRITE_READY iu code, so keep waiting until the list gets empty. */ static int uas_wait_for_pending_cmnds(struct uas_dev_info *devinfo) { unsigned long start_time; int r; start_time = jiffies; do { flush_work(&devinfo->work); r = usb_wait_anchor_empty_timeout(&devinfo->sense_urbs, 5000); if (r == 0) return -ETIME; r = usb_wait_anchor_empty_timeout(&devinfo->data_urbs, 500); if (r == 0) return -ETIME; if (time_after(jiffies, start_time + 5 * HZ)) return -ETIME; } while (!uas_cmnd_list_empty(devinfo)); return 0; } static int uas_pre_reset(struct usb_interface *intf) { struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; unsigned long flags; if (devinfo->shutdown) return 0; /* Block new requests */ spin_lock_irqsave(shost->host_lock, flags); scsi_block_requests(shost); spin_unlock_irqrestore(shost->host_lock, flags); if (uas_wait_for_pending_cmnds(devinfo) != 0) { shost_printk(KERN_ERR, shost, "%s: timed out\n", __func__); scsi_unblock_requests(shost); return 1; } uas_free_streams(devinfo); return 0; } static int uas_post_reset(struct usb_interface *intf) { struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; unsigned long flags; int err; if (devinfo->shutdown) return 0; err = uas_configure_endpoints(devinfo); if (err) { shost_printk(KERN_ERR, shost, "%s: alloc streams error %d after reset", __func__, err); return 1; } spin_lock_irqsave(shost->host_lock, flags); scsi_report_bus_reset(shost, 0); spin_unlock_irqrestore(shost->host_lock, flags); scsi_unblock_requests(shost); return 0; } static int uas_suspend(struct usb_interface *intf, pm_message_t message) { struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; if (uas_wait_for_pending_cmnds(devinfo) != 0) { shost_printk(KERN_ERR, shost, "%s: timed out\n", __func__); return -ETIME; } return 0; } static int uas_resume(struct usb_interface *intf) { return 0; } static int uas_reset_resume(struct usb_interface *intf) { struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; unsigned long flags; int err; err = uas_configure_endpoints(devinfo); if (err) { shost_printk(KERN_ERR, shost, "%s: alloc streams error %d after reset", __func__, err); return -EIO; } spin_lock_irqsave(shost->host_lock, flags); scsi_report_bus_reset(shost, 0); spin_unlock_irqrestore(shost->host_lock, flags); return 0; } static void uas_disconnect(struct usb_interface *intf) { struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; unsigned long flags; spin_lock_irqsave(&devinfo->lock, flags); devinfo->resetting = 1; spin_unlock_irqrestore(&devinfo->lock, flags); cancel_work_sync(&devinfo->work); usb_kill_anchored_urbs(&devinfo->cmd_urbs); usb_kill_anchored_urbs(&devinfo->sense_urbs); usb_kill_anchored_urbs(&devinfo->data_urbs); uas_zap_pending(devinfo, DID_NO_CONNECT); scsi_remove_host(shost); uas_free_streams(devinfo); scsi_host_put(shost); } /* * Put the device back in usb-storage mode on shutdown, as some BIOS-es * hang on reboot when the device is still in uas mode. Note the reset is * necessary as some devices won't revert to usb-storage mode without it. */ static void uas_shutdown(struct device *dev) { struct usb_interface *intf = to_usb_interface(dev); struct usb_device *udev = interface_to_usbdev(intf); struct Scsi_Host *shost = usb_get_intfdata(intf); struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata; if (system_state != SYSTEM_RESTART) return; devinfo->shutdown = 1; uas_free_streams(devinfo); usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, 0); usb_reset_device(udev); } static struct usb_driver uas_driver = { .name = "uas", .probe = uas_probe, .disconnect = uas_disconnect, .pre_reset = uas_pre_reset, .post_reset = uas_post_reset, .suspend = uas_suspend, .resume = uas_resume, .reset_resume = uas_reset_resume, .drvwrap.driver.shutdown = uas_shutdown, .id_table = uas_usb_ids, }; module_usb_driver(uas_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR( "Hans de Goede <hdegoede@redhat.com>, Matthew Wilcox and Sarah Sharp");
./CrossVul/dataset_final_sorted/CWE-125/c/good_2911_1
crossvul-cpp_data_bad_486_7
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. RDP order processing Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008 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 "rdesktop.h" #include "orders.h" extern uint8 *g_next_packet; static RDP_ORDER_STATE g_order_state; extern RDP_VERSION g_rdp_version; /* Read field indicating which parameters are present */ static void rdp_in_present(STREAM s, uint32 * present, uint8 flags, int size) { uint8 bits; int i; if (flags & RDP_ORDER_SMALL) { size--; } if (flags & RDP_ORDER_TINY) { if (size < 2) size = 0; else size -= 2; } *present = 0; for (i = 0; i < size; i++) { in_uint8(s, bits); *present |= bits << (i * 8); } } /* Read a co-ordinate (16-bit, or 8-bit delta) */ static void rdp_in_coord(STREAM s, sint16 * coord, RD_BOOL delta) { sint8 change; if (delta) { in_uint8(s, change); *coord += change; } else { in_uint16_le(s, *coord); } } /* Parse a delta co-ordinate in polyline/polygon order form */ static int parse_delta(uint8 * buffer, int *offset) { int value = buffer[(*offset)++]; int two_byte = value & 0x80; if (value & 0x40) /* sign bit */ value |= ~0x3f; else value &= 0x3f; if (two_byte) value = (value << 8) | buffer[(*offset)++]; return value; } /* Read a colour entry */ static void rdp_in_colour(STREAM s, uint32 * colour) { uint32 i; in_uint8(s, i); *colour = i; in_uint8(s, i); *colour |= i << 8; in_uint8(s, i); *colour |= i << 16; } /* Parse bounds information */ static RD_BOOL rdp_parse_bounds(STREAM s, BOUNDS * bounds) { uint8 present; in_uint8(s, present); if (present & 1) rdp_in_coord(s, &bounds->left, False); else if (present & 16) rdp_in_coord(s, &bounds->left, True); if (present & 2) rdp_in_coord(s, &bounds->top, False); else if (present & 32) rdp_in_coord(s, &bounds->top, True); if (present & 4) rdp_in_coord(s, &bounds->right, False); else if (present & 64) rdp_in_coord(s, &bounds->right, True); if (present & 8) rdp_in_coord(s, &bounds->bottom, False); else if (present & 128) rdp_in_coord(s, &bounds->bottom, True); return s_check(s); } /* Parse a pen */ static RD_BOOL rdp_parse_pen(STREAM s, PEN * pen, uint32 present) { if (present & 1) in_uint8(s, pen->style); if (present & 2) in_uint8(s, pen->width); if (present & 4) rdp_in_colour(s, &pen->colour); return s_check(s); } static void setup_brush(BRUSH * out_brush, BRUSH * in_brush) { BRUSHDATA *brush_data; uint8 cache_idx; uint8 colour_code; memcpy(out_brush, in_brush, sizeof(BRUSH)); if (out_brush->style & 0x80) { colour_code = out_brush->style & 0x0f; cache_idx = out_brush->pattern[0]; brush_data = cache_get_brush_data(colour_code, cache_idx); if ((brush_data == NULL) || (brush_data->data == NULL)) { logger(Graphics, Error, "setup_brush(), error getting brush data, style %x", out_brush->style); out_brush->bd = NULL; memset(out_brush->pattern, 0, 8); } else { out_brush->bd = brush_data; } out_brush->style = 3; } } /* Parse a brush */ static RD_BOOL rdp_parse_brush(STREAM s, BRUSH * brush, uint32 present) { if (present & 1) in_uint8(s, brush->xorigin); if (present & 2) in_uint8(s, brush->yorigin); if (present & 4) in_uint8(s, brush->style); if (present & 8) in_uint8(s, brush->pattern[0]); if (present & 16) in_uint8a(s, &brush->pattern[1], 7); return s_check(s); } /* Process a destination blt order */ static void process_destblt(STREAM s, DESTBLT_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) rdp_in_coord(s, &os->cx, delta); if (present & 0x08) rdp_in_coord(s, &os->cy, delta); if (present & 0x10) in_uint8(s, os->opcode); logger(Graphics, Debug, "process_destblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d", os->opcode, os->x, os->y, os->cx, os->cy); ui_destblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy); } /* Process a pattern blt order */ static void process_patblt(STREAM s, PATBLT_ORDER * os, uint32 present, RD_BOOL delta) { BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) rdp_in_coord(s, &os->cx, delta); if (present & 0x0008) rdp_in_coord(s, &os->cy, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) rdp_in_colour(s, &os->bgcolour); if (present & 0x0040) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 7); logger(Graphics, Debug, "process_patblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, bs=%d, bg=0x%x, fg=0x%x)", os->opcode, os->x, os->y, os->cx, os->cy, os->brush.style, os->bgcolour, os->fgcolour); setup_brush(&brush, &os->brush); ui_patblt(ROP2_P(os->opcode), os->x, os->y, os->cx, os->cy, &brush, os->bgcolour, os->fgcolour); } /* Process a screen blt order */ static void process_screenblt(STREAM s, SCREENBLT_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) rdp_in_coord(s, &os->cx, delta); if (present & 0x0008) rdp_in_coord(s, &os->cy, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) rdp_in_coord(s, &os->srcx, delta); if (present & 0x0040) rdp_in_coord(s, &os->srcy, delta); logger(Graphics, Debug, "process_screenblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, srcx=%d, srcy=%d)", os->opcode, os->x, os->y, os->cx, os->cy, os->srcx, os->srcy); ui_screenblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy, os->srcx, os->srcy); } /* Process a line order */ static void process_line(STREAM s, LINE_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x0001) in_uint16_le(s, os->mixmode); if (present & 0x0002) rdp_in_coord(s, &os->startx, delta); if (present & 0x0004) rdp_in_coord(s, &os->starty, delta); if (present & 0x0008) rdp_in_coord(s, &os->endx, delta); if (present & 0x0010) rdp_in_coord(s, &os->endy, delta); if (present & 0x0020) rdp_in_colour(s, &os->bgcolour); if (present & 0x0040) in_uint8(s, os->opcode); rdp_parse_pen(s, &os->pen, present >> 7); logger(Graphics, Debug, "process_line(), op=0x%x, sx=%d, sy=%d, dx=%d, dy=%d, fg=0x%x)", os->opcode, os->startx, os->starty, os->endx, os->endy, os->pen.colour); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_line(), bad ROP2 0x%x", os->opcode); return; } ui_line(os->opcode - 1, os->startx, os->starty, os->endx, os->endy, &os->pen); } /* Process an opaque rectangle order */ static void process_rect(STREAM s, RECT_ORDER * os, uint32 present, RD_BOOL delta) { uint32 i; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) rdp_in_coord(s, &os->cx, delta); if (present & 0x08) rdp_in_coord(s, &os->cy, delta); if (present & 0x10) { in_uint8(s, i); os->colour = (os->colour & 0xffffff00) | i; } if (present & 0x20) { in_uint8(s, i); os->colour = (os->colour & 0xffff00ff) | (i << 8); } if (present & 0x40) { in_uint8(s, i); os->colour = (os->colour & 0xff00ffff) | (i << 16); } logger(Graphics, Debug, "process_rect(), x=%d, y=%d, cx=%d, cy=%d, fg=0x%x", os->x, os->y, os->cx, os->cy, os->colour); ui_rect(os->x, os->y, os->cx, os->cy, os->colour); } /* Process a desktop save order */ static void process_desksave(STREAM s, DESKSAVE_ORDER * os, uint32 present, RD_BOOL delta) { int width, height; if (present & 0x01) in_uint32_le(s, os->offset); if (present & 0x02) rdp_in_coord(s, &os->left, delta); if (present & 0x04) rdp_in_coord(s, &os->top, delta); if (present & 0x08) rdp_in_coord(s, &os->right, delta); if (present & 0x10) rdp_in_coord(s, &os->bottom, delta); if (present & 0x20) in_uint8(s, os->action); logger(Graphics, Debug, "process_desksave(), l=%d, t=%d, r=%d, b=%d, off=%d, op=%d", os->left, os->top, os->right, os->bottom, os->offset, os->action); width = os->right - os->left + 1; height = os->bottom - os->top + 1; if (os->action == 0) ui_desktop_save(os->offset, os->left, os->top, width, height); else ui_desktop_restore(os->offset, os->left, os->top, width, height); } /* Process a memory blt order */ static void process_memblt(STREAM s, MEMBLT_ORDER * os, uint32 present, RD_BOOL delta) { RD_HBITMAP bitmap; if (present & 0x0001) { in_uint8(s, os->cache_id); in_uint8(s, os->colour_table); } if (present & 0x0002) rdp_in_coord(s, &os->x, delta); if (present & 0x0004) rdp_in_coord(s, &os->y, delta); if (present & 0x0008) rdp_in_coord(s, &os->cx, delta); if (present & 0x0010) rdp_in_coord(s, &os->cy, delta); if (present & 0x0020) in_uint8(s, os->opcode); if (present & 0x0040) rdp_in_coord(s, &os->srcx, delta); if (present & 0x0080) rdp_in_coord(s, &os->srcy, delta); if (present & 0x0100) in_uint16_le(s, os->cache_idx); logger(Graphics, Debug, "process_memblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, id=%d, idx=%d", os->opcode, os->x, os->y, os->cx, os->cy, os->cache_id, os->cache_idx); bitmap = cache_get_bitmap(os->cache_id, os->cache_idx); if (bitmap == NULL) return; ui_memblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy, bitmap, os->srcx, os->srcy); } /* Process a 3-way blt order */ static void process_triblt(STREAM s, TRIBLT_ORDER * os, uint32 present, RD_BOOL delta) { RD_HBITMAP bitmap; BRUSH brush; if (present & 0x000001) { in_uint8(s, os->cache_id); in_uint8(s, os->colour_table); } if (present & 0x000002) rdp_in_coord(s, &os->x, delta); if (present & 0x000004) rdp_in_coord(s, &os->y, delta); if (present & 0x000008) rdp_in_coord(s, &os->cx, delta); if (present & 0x000010) rdp_in_coord(s, &os->cy, delta); if (present & 0x000020) in_uint8(s, os->opcode); if (present & 0x000040) rdp_in_coord(s, &os->srcx, delta); if (present & 0x000080) rdp_in_coord(s, &os->srcy, delta); if (present & 0x000100) rdp_in_colour(s, &os->bgcolour); if (present & 0x000200) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 10); if (present & 0x008000) in_uint16_le(s, os->cache_idx); if (present & 0x010000) in_uint16_le(s, os->unknown); logger(Graphics, Debug, "process_triblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, id=%d, idx=%d, bs=%d, bg=0x%x, fg=0x%x", os->opcode, os->x, os->y, os->cx, os->cy, os->cache_id, os->cache_idx, os->brush.style, os->bgcolour, os->fgcolour); bitmap = cache_get_bitmap(os->cache_id, os->cache_idx); if (bitmap == NULL) return; setup_brush(&brush, &os->brush); ui_triblt(os->opcode, os->x, os->y, os->cx, os->cy, bitmap, os->srcx, os->srcy, &brush, os->bgcolour, os->fgcolour); } /* Process a polygon order */ static void process_polygon(STREAM s, POLYGON_ORDER * os, uint32 present, RD_BOOL delta) { int index, data, next; uint8 flags = 0; RD_POINT *points; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) in_uint8(s, os->opcode); if (present & 0x08) in_uint8(s, os->fillmode); if (present & 0x10) rdp_in_colour(s, &os->fgcolour); if (present & 0x20) in_uint8(s, os->npoints); if (present & 0x40) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polygon(), x=%d, y=%d, op=0x%x, fm=%d, fg=0x%x, n=%d, sz=%d", os->x, os->y, os->opcode, os->fillmode, os->fgcolour, os->npoints, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polygon(), bad ROP2 0x%x", os->opcode); return; } points = (RD_POINT *) xmalloc((os->npoints + 1) * sizeof(RD_POINT)); memset(points, 0, (os->npoints + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; index = 0; data = ((os->npoints - 1) / 4) + 1; for (next = 1; (next <= os->npoints) && (next < 256) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->npoints) ui_polygon(os->opcode - 1, os->fillmode, points, os->npoints + 1, NULL, 0, os->fgcolour); else logger(Graphics, Error, "process_polygon(), polygon parse error"); xfree(points); } /* Process a polygon2 order */ static void process_polygon2(STREAM s, POLYGON2_ORDER * os, uint32 present, RD_BOOL delta) { int index, data, next; uint8 flags = 0; RD_POINT *points; BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) in_uint8(s, os->opcode); if (present & 0x0008) in_uint8(s, os->fillmode); if (present & 0x0010) rdp_in_colour(s, &os->bgcolour); if (present & 0x0020) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 6); if (present & 0x0800) in_uint8(s, os->npoints); if (present & 0x1000) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polygon2(), x=%d, y=%d, op=0x%x, fm=%d, bs=%d, bg=0x%x, fg=0x%x, n=%d, sz=%d)", os->x, os->y, os->opcode, os->fillmode, os->brush.style, os->bgcolour, os->fgcolour, os->npoints, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polygon2(), bad ROP2 0x%x", os->opcode); return; } setup_brush(&brush, &os->brush); points = (RD_POINT *) xmalloc((os->npoints + 1) * sizeof(RD_POINT)); memset(points, 0, (os->npoints + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; index = 0; data = ((os->npoints - 1) / 4) + 1; for (next = 1; (next <= os->npoints) && (next < 256) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->npoints) ui_polygon(os->opcode - 1, os->fillmode, points, os->npoints + 1, &brush, os->bgcolour, os->fgcolour); else logger(Graphics, Error, "process_polygon2(), polygon parse error"); xfree(points); } /* Process a polyline order */ static void process_polyline(STREAM s, POLYLINE_ORDER * os, uint32 present, RD_BOOL delta) { int index, next, data; uint8 flags = 0; PEN pen; RD_POINT *points; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) in_uint8(s, os->opcode); if (present & 0x10) rdp_in_colour(s, &os->fgcolour); if (present & 0x20) in_uint8(s, os->lines); if (present & 0x40) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polyline(), x=%d, y=%d, op=0x%x, fg=0x%x, n=%d, sz=%d)", os->x, os->y, os->opcode, os->fgcolour, os->lines, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polyline(), bad ROP2 0x%x", os->opcode); return; } points = (RD_POINT *) xmalloc((os->lines + 1) * sizeof(RD_POINT)); memset(points, 0, (os->lines + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; pen.style = pen.width = 0; pen.colour = os->fgcolour; index = 0; data = ((os->lines - 1) / 4) + 1; for (next = 1; (next <= os->lines) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->lines) ui_polyline(os->opcode - 1, points, os->lines + 1, &pen); else logger(Graphics, Error, "process_polyline(), parse error"); xfree(points); } /* Process an ellipse order */ static void process_ellipse(STREAM s, ELLIPSE_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x01) rdp_in_coord(s, &os->left, delta); if (present & 0x02) rdp_in_coord(s, &os->top, delta); if (present & 0x04) rdp_in_coord(s, &os->right, delta); if (present & 0x08) rdp_in_coord(s, &os->bottom, delta); if (present & 0x10) in_uint8(s, os->opcode); if (present & 0x20) in_uint8(s, os->fillmode); if (present & 0x40) rdp_in_colour(s, &os->fgcolour); logger(Graphics, Debug, "process_ellipse(), l=%d, t=%d, r=%d, b=%d, op=0x%x, fm=%d, fg=0x%x", os->left, os->top, os->right, os->bottom, os->opcode, os->fillmode, os->fgcolour); ui_ellipse(os->opcode - 1, os->fillmode, os->left, os->top, os->right - os->left, os->bottom - os->top, NULL, 0, os->fgcolour); } /* Process an ellipse2 order */ static void process_ellipse2(STREAM s, ELLIPSE2_ORDER * os, uint32 present, RD_BOOL delta) { BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->left, delta); if (present & 0x0002) rdp_in_coord(s, &os->top, delta); if (present & 0x0004) rdp_in_coord(s, &os->right, delta); if (present & 0x0008) rdp_in_coord(s, &os->bottom, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) in_uint8(s, os->fillmode); if (present & 0x0040) rdp_in_colour(s, &os->bgcolour); if (present & 0x0080) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 8); logger(Graphics, Debug, "process_ellipse2(), l=%d, t=%d, r=%d, b=%d, op=0x%x, fm=%d, bs=%d, bg=0x%x, fg=0x%x", os->left, os->top, os->right, os->bottom, os->opcode, os->fillmode, os->brush.style, os->bgcolour, os->fgcolour); setup_brush(&brush, &os->brush); ui_ellipse(os->opcode - 1, os->fillmode, os->left, os->top, os->right - os->left, os->bottom - os->top, &brush, os->bgcolour, os->fgcolour); } /* Process a text order */ static void process_text2(STREAM s, TEXT2_ORDER * os, uint32 present, RD_BOOL delta) { UNUSED(delta); BRUSH brush; if (present & 0x000001) in_uint8(s, os->font); if (present & 0x000002) in_uint8(s, os->flags); if (present & 0x000004) in_uint8(s, os->opcode); if (present & 0x000008) in_uint8(s, os->mixmode); if (present & 0x000010) rdp_in_colour(s, &os->fgcolour); if (present & 0x000020) rdp_in_colour(s, &os->bgcolour); if (present & 0x000040) in_uint16_le(s, os->clipleft); if (present & 0x000080) in_uint16_le(s, os->cliptop); if (present & 0x000100) in_uint16_le(s, os->clipright); if (present & 0x000200) in_uint16_le(s, os->clipbottom); if (present & 0x000400) in_uint16_le(s, os->boxleft); if (present & 0x000800) in_uint16_le(s, os->boxtop); if (present & 0x001000) in_uint16_le(s, os->boxright); if (present & 0x002000) in_uint16_le(s, os->boxbottom); rdp_parse_brush(s, &os->brush, present >> 14); if (present & 0x080000) in_uint16_le(s, os->x); if (present & 0x100000) in_uint16_le(s, os->y); if (present & 0x200000) { in_uint8(s, os->length); in_uint8a(s, os->text, os->length); } logger(Graphics, Debug, "process_text2(), x=%d, y=%d, cl=%d, ct=%d, cr=%d, cb=%d, bl=%d, bt=%d, br=%d, bb=%d, bs=%d, bg=0x%x, fg=0x%x, font=%d, fl=0x%x, op=0x%x, mix=%d, n=%d", os->x, os->y, os->clipleft, os->cliptop, os->clipright, os->clipbottom, os->boxleft, os->boxtop, os->boxright, os->boxbottom, os->brush.style, os->bgcolour, os->fgcolour, os->font, os->flags, os->opcode, os->mixmode, os->length); setup_brush(&brush, &os->brush); ui_draw_text(os->font, os->flags, os->opcode - 1, os->mixmode, os->x, os->y, os->clipleft, os->cliptop, os->clipright - os->clipleft, os->clipbottom - os->cliptop, os->boxleft, os->boxtop, os->boxright - os->boxleft, os->boxbottom - os->boxtop, &brush, os->bgcolour, os->fgcolour, os->text, os->length); } /* Process a raw bitmap cache order */ static void process_raw_bmpcache(STREAM s) { RD_HBITMAP bitmap; uint16 cache_idx, bufsize; uint8 cache_id, width, height, bpp, Bpp; uint8 *data, *inverted; int y; in_uint8(s, cache_id); in_uint8s(s, 1); /* pad */ in_uint8(s, width); in_uint8(s, height); in_uint8(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, bufsize); in_uint16_le(s, cache_idx); in_uint8p(s, data, bufsize); logger(Graphics, Debug, "process_raw_bpmcache(), cx=%d, cy=%d, id=%d, idx=%d", width, height, cache_id, cache_idx); inverted = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { memcpy(&inverted[(height - y - 1) * (width * Bpp)], &data[y * (width * Bpp)], width * Bpp); } bitmap = ui_create_bitmap(width, height, inverted); xfree(inverted); cache_put_bitmap(cache_id, cache_idx, bitmap); } /* Process a bitmap cache order */ static void process_bmpcache(STREAM s) { RD_HBITMAP bitmap; uint16 cache_idx, size; uint8 cache_id, width, height, bpp, Bpp; uint8 *data, *bmpdata; uint16 bufsize, pad2, row_size, final_size; uint8 pad1; pad2 = row_size = final_size = 0xffff; /* Shut the compiler up */ in_uint8(s, cache_id); in_uint8(s, pad1); /* pad */ in_uint8(s, width); in_uint8(s, height); in_uint8(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, bufsize); /* bufsize */ in_uint16_le(s, cache_idx); if (g_rdp_version >= RDP_V5) { size = bufsize; } else { /* Begin compressedBitmapData */ in_uint16_le(s, pad2); /* pad */ in_uint16_le(s, size); /* in_uint8s(s, 4); *//* row_size, final_size */ in_uint16_le(s, row_size); in_uint16_le(s, final_size); } in_uint8p(s, data, size); logger(Graphics, Debug, "process_bmpcache(), cx=%d, cy=%d, id=%d, idx=%d, bpp=%d, size=%d, pad1=%d, bufsize=%d, pad2=%d, rs=%d, fs=%d", width, height, cache_id, cache_idx, bpp, size, pad1, bufsize, pad2, row_size, final_size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { bitmap = ui_create_bitmap(width, height, bmpdata); cache_put_bitmap(cache_id, cache_idx, bitmap); } else { logger(Graphics, Error, "process_bmpcache(), Failed to decompress bitmap data"); } xfree(bmpdata); } /* Process a bitmap cache v2 order */ static void process_bmpcache2(STREAM s, uint16 flags, RD_BOOL compressed) { RD_HBITMAP bitmap; int y; uint8 cache_id, cache_idx_low, width, height, Bpp; uint16 cache_idx, bufsize; uint8 *data, *bmpdata, *bitmap_id; bitmap_id = NULL; /* prevent compiler warning */ cache_id = flags & ID_MASK; Bpp = ((flags & MODE_MASK) >> MODE_SHIFT) - 2; if (flags & PERSIST) { in_uint8p(s, bitmap_id, 8); } if (flags & SQUARE) { in_uint8(s, width); height = width; } else { in_uint8(s, width); in_uint8(s, height); } in_uint16_be(s, bufsize); bufsize &= BUFSIZE_MASK; in_uint8(s, cache_idx); if (cache_idx & LONG_FORMAT) { in_uint8(s, cache_idx_low); cache_idx = ((cache_idx ^ LONG_FORMAT) << 8) + cache_idx_low; } in_uint8p(s, data, bufsize); logger(Graphics, Debug, "process_bmpcache2(), compr=%d, flags=%x, cx=%d, cy=%d, id=%d, idx=%d, Bpp=%d, bs=%d", compressed, flags, width, height, cache_id, cache_idx, Bpp, bufsize); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (compressed) { if (!bitmap_decompress(bmpdata, width, height, data, bufsize, Bpp)) { logger(Graphics, Error, "process_bmpcache2(), failed to decompress bitmap data"); xfree(bmpdata); return; } } else { for (y = 0; y < height; y++) memcpy(&bmpdata[(height - y - 1) * (width * Bpp)], &data[y * (width * Bpp)], width * Bpp); } bitmap = ui_create_bitmap(width, height, bmpdata); if (bitmap) { cache_put_bitmap(cache_id, cache_idx, bitmap); if (flags & PERSIST) pstcache_save_bitmap(cache_id, cache_idx, bitmap_id, width, height, width * height * Bpp, bmpdata); } else { logger(Graphics, Error, "process_bmpcache2(), ui_create_bitmap(), failed"); } xfree(bmpdata); } /* Process a colourmap cache order */ static void process_colcache(STREAM s) { COLOURENTRY *entry; COLOURMAP map; RD_HCOLOURMAP hmap; uint8 cache_id; int i; in_uint8(s, cache_id); in_uint16_le(s, map.ncolours); map.colours = (COLOURENTRY *) xmalloc(sizeof(COLOURENTRY) * map.ncolours); for (i = 0; i < map.ncolours; i++) { entry = &map.colours[i]; in_uint8(s, entry->blue); in_uint8(s, entry->green); in_uint8(s, entry->red); in_uint8s(s, 1); /* pad */ } logger(Graphics, Debug, "process_colcache(), id=%d, n=%d", cache_id, map.ncolours); hmap = ui_create_colourmap(&map); if (cache_id) ui_set_colourmap(hmap); xfree(map.colours); } /* Process a font cache order */ static void process_fontcache(STREAM s) { RD_HGLYPH bitmap; uint8 font, nglyphs; uint16 character, offset, baseline, width, height; int i, datasize; uint8 *data; in_uint8(s, font); in_uint8(s, nglyphs); logger(Graphics, Debug, "process_fontcache(), font=%d, n=%d", font, nglyphs); for (i = 0; i < nglyphs; i++) { in_uint16_le(s, character); in_uint16_le(s, offset); in_uint16_le(s, baseline); in_uint16_le(s, width); in_uint16_le(s, height); datasize = (height * ((width + 7) / 8) + 3) & ~3; in_uint8p(s, data, datasize); bitmap = ui_create_glyph(width, height, data); cache_put_font(font, character, offset, baseline, width, height, bitmap); } } static void process_compressed_8x8_brush_data(uint8 * in, uint8 * out, int Bpp) { int x, y, pal_index, in_index, shift, do2, i; uint8 *pal; in_index = 0; pal = in + 16; /* read it bottom up */ for (y = 7; y >= 0; y--) { /* 2 bytes per row */ x = 0; for (do2 = 0; do2 < 2; do2++) { /* 4 pixels per byte */ shift = 6; while (shift >= 0) { pal_index = (in[in_index] >> shift) & 3; /* size of palette entries depends on Bpp */ for (i = 0; i < Bpp; i++) { out[(y * 8 + x) * Bpp + i] = pal[pal_index * Bpp + i]; } x++; shift -= 2; } in_index++; } } } /* Process a brush cache order */ static void process_brushcache(STREAM s, uint16 flags) { UNUSED(flags); BRUSHDATA brush_data; uint8 cache_idx, colour_code, width, height, size, type; uint8 *comp_brush; int index; int Bpp; in_uint8(s, cache_idx); in_uint8(s, colour_code); in_uint8(s, width); in_uint8(s, height); in_uint8(s, type); /* type, 0x8x = cached */ in_uint8(s, size); logger(Graphics, Debug, "process_brushcache(), idx=%d, wd=%d, ht=%d, type=0x%x sz=%d", cache_idx, width, height, type, size); if ((width == 8) && (height == 8)) { if (colour_code == 1) { brush_data.colour_code = 1; brush_data.data_size = 8; brush_data.data = xmalloc(8); if (size == 8) { /* read it bottom up */ for (index = 7; index >= 0; index--) { in_uint8(s, brush_data.data[index]); } } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, colour_code %d size %d", colour_code, size); } cache_put_brush_data(1, cache_idx, &brush_data); } else if ((colour_code >= 3) && (colour_code <= 6)) { Bpp = colour_code - 2; brush_data.colour_code = colour_code; brush_data.data_size = 8 * 8 * Bpp; brush_data.data = xmalloc(8 * 8 * Bpp); if (size == 16 + 4 * Bpp) { in_uint8p(s, comp_brush, 16 + 4 * Bpp); process_compressed_8x8_brush_data(comp_brush, brush_data.data, Bpp); } else { in_uint8a(s, brush_data.data, 8 * 8 * Bpp); } cache_put_brush_data(colour_code, cache_idx, &brush_data); } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, colour_code %d size %d", colour_code, size); } } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, width height %d %d", width, height); } } /* Process a secondary order */ static void process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; } /* Process an order PDU */ void process_orders(STREAM s, uint16 num_orders) { RDP_ORDER_STATE *os = &g_order_state; uint32 present; uint8 order_flags; int size, processed = 0; RD_BOOL delta; while (processed < num_orders) { in_uint8(s, order_flags); if (!(order_flags & RDP_ORDER_STANDARD)) { logger(Graphics, Error, "process_orders(), order parsing failed"); break; } if (order_flags & RDP_ORDER_SECONDARY) { process_secondary_order(s); } else { if (order_flags & RDP_ORDER_CHANGE) { in_uint8(s, os->order_type); } switch (os->order_type) { case RDP_ORDER_TRIBLT: case RDP_ORDER_TEXT2: size = 3; break; case RDP_ORDER_PATBLT: case RDP_ORDER_MEMBLT: case RDP_ORDER_LINE: case RDP_ORDER_POLYGON2: case RDP_ORDER_ELLIPSE2: size = 2; break; default: size = 1; } rdp_in_present(s, &present, order_flags, size); if (order_flags & RDP_ORDER_BOUNDS) { if (!(order_flags & RDP_ORDER_LASTBOUNDS)) rdp_parse_bounds(s, &os->bounds); ui_set_clip(os->bounds.left, os->bounds.top, os->bounds.right - os->bounds.left + 1, os->bounds.bottom - os->bounds.top + 1); } delta = order_flags & RDP_ORDER_DELTA; switch (os->order_type) { case RDP_ORDER_DESTBLT: process_destblt(s, &os->destblt, present, delta); break; case RDP_ORDER_PATBLT: process_patblt(s, &os->patblt, present, delta); break; case RDP_ORDER_SCREENBLT: process_screenblt(s, &os->screenblt, present, delta); break; case RDP_ORDER_LINE: process_line(s, &os->line, present, delta); break; case RDP_ORDER_RECT: process_rect(s, &os->rect, present, delta); break; case RDP_ORDER_DESKSAVE: process_desksave(s, &os->desksave, present, delta); break; case RDP_ORDER_MEMBLT: process_memblt(s, &os->memblt, present, delta); break; case RDP_ORDER_TRIBLT: process_triblt(s, &os->triblt, present, delta); break; case RDP_ORDER_POLYGON: process_polygon(s, &os->polygon, present, delta); break; case RDP_ORDER_POLYGON2: process_polygon2(s, &os->polygon2, present, delta); break; case RDP_ORDER_POLYLINE: process_polyline(s, &os->polyline, present, delta); break; case RDP_ORDER_ELLIPSE: process_ellipse(s, &os->ellipse, present, delta); break; case RDP_ORDER_ELLIPSE2: process_ellipse2(s, &os->ellipse2, present, delta); break; case RDP_ORDER_TEXT2: process_text2(s, &os->text2, present, delta); break; default: logger(Graphics, Warning, "process_orders(), unhandled order type %d", os->order_type); return; } if (order_flags & RDP_ORDER_BOUNDS) ui_reset_clip(); } processed++; } #if 0 /* not true when RDP_COMPRESSION is set */ if (s->p != g_next_packet) logger(Graphics, Error, "process_orders(), %d bytes remaining", (int) (g_next_packet - s->p)); #endif } /* Reset order state */ void reset_order_state(void) { memset(&g_order_state, 0, sizeof(g_order_state)); g_order_state.order_type = RDP_ORDER_PATBLT; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_7
crossvul-cpp_data_good_1330_0
/* * Copyright (c) Red Hat Inc. * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sub license, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: Dave Airlie <airlied@redhat.com> * Jerome Glisse <jglisse@redhat.com> * Pauli Nieminen <suokkos@gmail.com> */ /* simple list based uncached page pool * - Pool collects resently freed pages for reuse * - Use page->lru to keep a free list * - doesn't track currently in use pages */ #define pr_fmt(fmt) "[TTM] " fmt #include <linux/list.h> #include <linux/spinlock.h> #include <linux/highmem.h> #include <linux/mm_types.h> #include <linux/module.h> #include <linux/mm.h> #include <linux/seq_file.h> /* for seq_printf */ #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/atomic.h> #include <drm/ttm/ttm_bo_driver.h> #include <drm/ttm/ttm_page_alloc.h> #include <drm/ttm/ttm_set_memory.h> #define NUM_PAGES_TO_ALLOC (PAGE_SIZE/sizeof(struct page *)) #define SMALL_ALLOCATION 16 #define FREE_ALL_PAGES (~0U) /* times are in msecs */ #define PAGE_FREE_INTERVAL 1000 /** * struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages. * * @lock: Protects the shared pool from concurrnet access. Must be used with * irqsave/irqrestore variants because pool allocator maybe called from * delayed work. * @fill_lock: Prevent concurrent calls to fill. * @list: Pool of free uc/wc pages for fast reuse. * @gfp_flags: Flags to pass for alloc_page. * @npages: Number of pages in pool. */ struct ttm_page_pool { spinlock_t lock; bool fill_lock; struct list_head list; gfp_t gfp_flags; unsigned npages; char *name; unsigned long nfrees; unsigned long nrefills; unsigned int order; }; /** * Limits for the pool. They are handled without locks because only place where * they may change is in sysfs store. They won't have immediate effect anyway * so forcing serialization to access them is pointless. */ struct ttm_pool_opts { unsigned alloc_size; unsigned max_size; unsigned small; }; #define NUM_POOLS 6 /** * struct ttm_pool_manager - Holds memory pools for fst allocation * * Manager is read only object for pool code so it doesn't need locking. * * @free_interval: minimum number of jiffies between freeing pages from pool. * @page_alloc_inited: reference counting for pool allocation. * @work: Work that is used to shrink the pool. Work is only run when there is * some pages to free. * @small_allocation: Limit in number of pages what is small allocation. * * @pools: All pool objects in use. **/ struct ttm_pool_manager { struct kobject kobj; struct shrinker mm_shrink; struct ttm_pool_opts options; union { struct ttm_page_pool pools[NUM_POOLS]; struct { struct ttm_page_pool wc_pool; struct ttm_page_pool uc_pool; struct ttm_page_pool wc_pool_dma32; struct ttm_page_pool uc_pool_dma32; struct ttm_page_pool wc_pool_huge; struct ttm_page_pool uc_pool_huge; } ; }; }; static struct attribute ttm_page_pool_max = { .name = "pool_max_size", .mode = S_IRUGO | S_IWUSR }; static struct attribute ttm_page_pool_small = { .name = "pool_small_allocation", .mode = S_IRUGO | S_IWUSR }; static struct attribute ttm_page_pool_alloc_size = { .name = "pool_allocation_size", .mode = S_IRUGO | S_IWUSR }; static struct attribute *ttm_pool_attrs[] = { &ttm_page_pool_max, &ttm_page_pool_small, &ttm_page_pool_alloc_size, NULL }; static void ttm_pool_kobj_release(struct kobject *kobj) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); kfree(m); } static ssize_t ttm_pool_store(struct kobject *kobj, struct attribute *attr, const char *buffer, size_t size) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); int chars; unsigned val; chars = sscanf(buffer, "%u", &val); if (chars == 0) return size; /* Convert kb to number of pages */ val = val / (PAGE_SIZE >> 10); if (attr == &ttm_page_pool_max) m->options.max_size = val; else if (attr == &ttm_page_pool_small) m->options.small = val; else if (attr == &ttm_page_pool_alloc_size) { if (val > NUM_PAGES_TO_ALLOC*8) { pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7), NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); return size; } else if (val > NUM_PAGES_TO_ALLOC) { pr_warn("Setting allocation size to larger than %lu is not recommended\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); } m->options.alloc_size = val; } return size; } static ssize_t ttm_pool_show(struct kobject *kobj, struct attribute *attr, char *buffer) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); unsigned val = 0; if (attr == &ttm_page_pool_max) val = m->options.max_size; else if (attr == &ttm_page_pool_small) val = m->options.small; else if (attr == &ttm_page_pool_alloc_size) val = m->options.alloc_size; val = val * (PAGE_SIZE >> 10); return snprintf(buffer, PAGE_SIZE, "%u\n", val); } static const struct sysfs_ops ttm_pool_sysfs_ops = { .show = &ttm_pool_show, .store = &ttm_pool_store, }; static struct kobj_type ttm_pool_kobj_type = { .release = &ttm_pool_kobj_release, .sysfs_ops = &ttm_pool_sysfs_ops, .default_attrs = ttm_pool_attrs, }; static struct ttm_pool_manager *_manager; /** * Select the right pool or requested caching state and ttm flags. */ static struct ttm_page_pool *ttm_get_pool(int flags, bool huge, enum ttm_caching_state cstate) { int pool_index; if (cstate == tt_cached) return NULL; if (cstate == tt_wc) pool_index = 0x0; else pool_index = 0x1; if (flags & TTM_PAGE_FLAG_DMA32) { if (huge) return NULL; pool_index |= 0x2; } else if (huge) { pool_index |= 0x4; } return &_manager->pools[pool_index]; } /* set memory back to wb and free the pages. */ static void ttm_pages_put(struct page *pages[], unsigned npages, unsigned int order) { unsigned int i, pages_nr = (1 << order); if (order == 0) { if (ttm_set_pages_array_wb(pages, npages)) pr_err("Failed to set %d pages to wb!\n", npages); } for (i = 0; i < npages; ++i) { if (order > 0) { if (ttm_set_pages_wb(pages[i], pages_nr)) pr_err("Failed to set %d pages to wb!\n", pages_nr); } __free_pages(pages[i], order); } } static void ttm_pool_update_free_locked(struct ttm_page_pool *pool, unsigned freed_pages) { pool->npages -= freed_pages; pool->nfrees += freed_pages; } /** * Free pages from pool. * * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC * number of pages in one go. * * @pool: to free the pages from * @free_all: If set to true will free all pages in pool * @use_static: Safe to use static buffer **/ static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free, bool use_static) { static struct page *static_buf[NUM_PAGES_TO_ALLOC]; unsigned long irq_flags; struct page *p; struct page **pages_to_free; unsigned freed_pages = 0, npages_to_free = nr_free; if (NUM_PAGES_TO_ALLOC < nr_free) npages_to_free = NUM_PAGES_TO_ALLOC; if (use_static) pages_to_free = static_buf; else pages_to_free = kmalloc_array(npages_to_free, sizeof(struct page *), GFP_KERNEL); if (!pages_to_free) { pr_debug("Failed to allocate memory for pool free operation\n"); return 0; } restart: spin_lock_irqsave(&pool->lock, irq_flags); list_for_each_entry_reverse(p, &pool->list, lru) { if (freed_pages >= npages_to_free) break; pages_to_free[freed_pages++] = p; /* We can only remove NUM_PAGES_TO_ALLOC at a time. */ if (freed_pages >= NUM_PAGES_TO_ALLOC) { /* remove range of pages from the pool */ __list_del(p->lru.prev, &pool->list); ttm_pool_update_free_locked(pool, freed_pages); /** * Because changing page caching is costly * we unlock the pool to prevent stalling. */ spin_unlock_irqrestore(&pool->lock, irq_flags); ttm_pages_put(pages_to_free, freed_pages, pool->order); if (likely(nr_free != FREE_ALL_PAGES)) nr_free -= freed_pages; if (NUM_PAGES_TO_ALLOC >= nr_free) npages_to_free = nr_free; else npages_to_free = NUM_PAGES_TO_ALLOC; freed_pages = 0; /* free all so restart the processing */ if (nr_free) goto restart; /* Not allowed to fall through or break because * following context is inside spinlock while we are * outside here. */ goto out; } } /* remove range of pages from the pool */ if (freed_pages) { __list_del(&p->lru, &pool->list); ttm_pool_update_free_locked(pool, freed_pages); nr_free -= freed_pages; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (freed_pages) ttm_pages_put(pages_to_free, freed_pages, pool->order); out: if (pages_to_free != static_buf) kfree(pages_to_free); return nr_free; } /** * Callback for mm to request pool to reduce number of page held. * * XXX: (dchinner) Deadlock warning! * * This code is crying out for a shrinker per pool.... */ static unsigned long ttm_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) { static DEFINE_MUTEX(lock); static unsigned start_pool; unsigned i; unsigned pool_offset; struct ttm_page_pool *pool; int shrink_pages = sc->nr_to_scan; unsigned long freed = 0; unsigned int nr_free_pool; if (!mutex_trylock(&lock)) return SHRINK_STOP; pool_offset = ++start_pool % NUM_POOLS; /* select start pool in round robin fashion */ for (i = 0; i < NUM_POOLS; ++i) { unsigned nr_free = shrink_pages; unsigned page_nr; if (shrink_pages == 0) break; pool = &_manager->pools[(i + pool_offset)%NUM_POOLS]; page_nr = (1 << pool->order); /* OK to use static buffer since global mutex is held. */ nr_free_pool = roundup(nr_free, page_nr) >> pool->order; shrink_pages = ttm_page_pool_free(pool, nr_free_pool, true); freed += (nr_free_pool - shrink_pages) << pool->order; if (freed >= sc->nr_to_scan) break; shrink_pages <<= pool->order; } mutex_unlock(&lock); return freed; } static unsigned long ttm_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc) { unsigned i; unsigned long count = 0; struct ttm_page_pool *pool; for (i = 0; i < NUM_POOLS; ++i) { pool = &_manager->pools[i]; count += (pool->npages << pool->order); } return count; } static int ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager) { manager->mm_shrink.count_objects = ttm_pool_shrink_count; manager->mm_shrink.scan_objects = ttm_pool_shrink_scan; manager->mm_shrink.seeks = 1; return register_shrinker(&manager->mm_shrink); } static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager) { unregister_shrinker(&manager->mm_shrink); } static int ttm_set_pages_caching(struct page **pages, enum ttm_caching_state cstate, unsigned cpages) { int r = 0; /* Set page caching */ switch (cstate) { case tt_uncached: r = ttm_set_pages_array_uc(pages, cpages); if (r) pr_err("Failed to set %d pages to uc!\n", cpages); break; case tt_wc: r = ttm_set_pages_array_wc(pages, cpages); if (r) pr_err("Failed to set %d pages to wc!\n", cpages); break; default: break; } return r; } /** * Free pages the pages that failed to change the caching state. If there is * any pages that have changed their caching state already put them to the * pool. */ static void ttm_handle_caching_state_failure(struct list_head *pages, int ttm_flags, enum ttm_caching_state cstate, struct page **failed_pages, unsigned cpages) { unsigned i; /* Failed pages have to be freed */ for (i = 0; i < cpages; ++i) { list_del(&failed_pages[i]->lru); __free_page(failed_pages[i]); } } /** * Allocate new pages with correct caching. * * This function is reentrant if caller updates count depending on number of * pages returned in pages array. */ static int ttm_alloc_new_pages(struct list_head *pages, gfp_t gfp_flags, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned order) { struct page **caching_array; struct page *p; int r = 0; unsigned i, j, cpages; unsigned npages = 1 << order; unsigned max_cpages = min(count << order, (unsigned)NUM_PAGES_TO_ALLOC); /* allocate array for page caching change */ caching_array = kmalloc_array(max_cpages, sizeof(struct page *), GFP_KERNEL); if (!caching_array) { pr_debug("Unable to allocate table for new pages\n"); return -ENOMEM; } for (i = 0, cpages = 0; i < count; ++i) { p = alloc_pages(gfp_flags, order); if (!p) { pr_debug("Unable to get page %u\n", i); /* store already allocated pages in the pool after * setting the caching state */ if (cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); } r = -ENOMEM; goto out; } list_add(&p->lru, pages); #ifdef CONFIG_HIGHMEM /* gfp flags of highmem page should never be dma32 so we * we should be fine in such case */ if (PageHighMem(p)) continue; #endif for (j = 0; j < npages; ++j) { caching_array[cpages++] = p++; if (cpages == max_cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) { ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); goto out; } cpages = 0; } } } if (cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); } out: kfree(caching_array); return r; } /** * Fill the given pool if there aren't enough pages and the requested number of * pages is small. */ static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned long *irq_flags) { struct page *p; int r; unsigned cpages = 0; /** * Only allow one pool fill operation at a time. * If pool doesn't have enough pages for the allocation new pages are * allocated from outside of pool. */ if (pool->fill_lock) return; pool->fill_lock = true; /* If allocation request is small and there are not enough * pages in a pool we fill the pool up first. */ if (count < _manager->options.small && count > pool->npages) { struct list_head new_pages; unsigned alloc_size = _manager->options.alloc_size; /** * Can't change page caching if in irqsave context. We have to * drop the pool->lock. */ spin_unlock_irqrestore(&pool->lock, *irq_flags); INIT_LIST_HEAD(&new_pages); r = ttm_alloc_new_pages(&new_pages, pool->gfp_flags, ttm_flags, cstate, alloc_size, 0); spin_lock_irqsave(&pool->lock, *irq_flags); if (!r) { list_splice(&new_pages, &pool->list); ++pool->nrefills; pool->npages += alloc_size; } else { pr_debug("Failed to fill pool (%p)\n", pool); /* If we have any pages left put them to the pool. */ list_for_each_entry(p, &new_pages, lru) { ++cpages; } list_splice(&new_pages, &pool->list); pool->npages += cpages; } } pool->fill_lock = false; } /** * Allocate pages from the pool and put them on the return list. * * @return zero for success or negative error code. */ static int ttm_page_pool_get_pages(struct ttm_page_pool *pool, struct list_head *pages, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned order) { unsigned long irq_flags; struct list_head *p; unsigned i; int r = 0; spin_lock_irqsave(&pool->lock, irq_flags); if (!order) ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count, &irq_flags); if (count >= pool->npages) { /* take all pages from the pool */ list_splice_init(&pool->list, pages); count -= pool->npages; pool->npages = 0; goto out; } /* find the last pages to include for requested number of pages. Split * pool to begin and halve it to reduce search space. */ if (count <= pool->npages/2) { i = 0; list_for_each(p, &pool->list) { if (++i == count) break; } } else { i = pool->npages + 1; list_for_each_prev(p, &pool->list) { if (--i == count) break; } } /* Cut 'count' number of pages from the pool */ list_cut_position(pages, &pool->list, p); pool->npages -= count; count = 0; out: spin_unlock_irqrestore(&pool->lock, irq_flags); /* clear the pages coming from the pool if requested */ if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) { struct page *page; list_for_each_entry(page, pages, lru) { if (PageHighMem(page)) clear_highpage(page); else clear_page(page_address(page)); } } /* If pool didn't have enough pages allocate new one. */ if (count) { gfp_t gfp_flags = pool->gfp_flags; /* set zero flag for page allocation if required */ if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) gfp_flags |= __GFP_ZERO; if (ttm_flags & TTM_PAGE_FLAG_NO_RETRY) gfp_flags |= __GFP_RETRY_MAYFAIL; /* ttm_alloc_new_pages doesn't reference pool so we can run * multiple requests in parallel. **/ r = ttm_alloc_new_pages(pages, gfp_flags, ttm_flags, cstate, count, order); } return r; } /* Put all pages in pages list to correct pool to wait for reuse */ static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32) && (npages - i) >= HPAGE_PMD_NR) { for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while ((npages - i) >= HPAGE_PMD_NR) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); } /* * On success pages list will hold count number of correctly * cached pages. */ static int ttm_get_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif struct list_head plist; struct page *p = NULL; unsigned count, first; int r; /* No pool for cached pages */ if (pool == NULL) { gfp_t gfp_flags = GFP_USER; unsigned i; #ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned j; #endif /* set zero flag for page allocation if required */ if (flags & TTM_PAGE_FLAG_ZERO_ALLOC) gfp_flags |= __GFP_ZERO; if (flags & TTM_PAGE_FLAG_NO_RETRY) gfp_flags |= __GFP_RETRY_MAYFAIL; if (flags & TTM_PAGE_FLAG_DMA32) gfp_flags |= GFP_DMA32; else gfp_flags |= GFP_HIGHUSER; i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(gfp_flags & GFP_DMA32)) { while (npages >= HPAGE_PMD_NR) { gfp_t huge_flags = gfp_flags; huge_flags |= GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM; huge_flags &= ~__GFP_MOVABLE; huge_flags &= ~__GFP_COMP; p = alloc_pages(huge_flags, HPAGE_PMD_ORDER); if (!p) break; for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = p++; npages -= HPAGE_PMD_NR; } } #endif first = i; while (npages) { p = alloc_page(gfp_flags); if (!p) { pr_debug("Unable to allocate page\n"); return -ENOMEM; } /* Swap the pages if we detect consecutive order */ if (i > first && pages[i - 1] == p - 1) swap(p, pages[i - 1]); pages[i++] = p; --npages; } return 0; } count = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge && npages >= HPAGE_PMD_NR) { INIT_LIST_HEAD(&plist); ttm_page_pool_get_pages(huge, &plist, flags, cstate, npages / HPAGE_PMD_NR, HPAGE_PMD_ORDER); list_for_each_entry(p, &plist, lru) { unsigned j; for (j = 0; j < HPAGE_PMD_NR; ++j) pages[count++] = &p[j]; } } #endif INIT_LIST_HEAD(&plist); r = ttm_page_pool_get_pages(pool, &plist, flags, cstate, npages - count, 0); first = count; list_for_each_entry(p, &plist, lru) { struct page *tmp = p; /* Swap the pages if we detect consecutive order */ if (count > first && pages[count - 1] == tmp - 1) swap(tmp, pages[count - 1]); pages[count++] = tmp; } if (r) { /* If there is any pages in the list put them back to * the pool. */ pr_debug("Failed to allocate extra pages for large request\n"); ttm_put_pages(pages, count, flags, cstate); return r; } return 0; } static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, gfp_t flags, char *name, unsigned int order) { spin_lock_init(&pool->lock); pool->fill_lock = false; INIT_LIST_HEAD(&pool->list); pool->npages = pool->nfrees = 0; pool->gfp_flags = flags; pool->name = name; pool->order = order; } int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages) { int ret; #ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned order = HPAGE_PMD_ORDER; #else unsigned order = 0; #endif WARN_ON(_manager); pr_info("Initializing pool allocator\n"); _manager = kzalloc(sizeof(*_manager), GFP_KERNEL); if (!_manager) return -ENOMEM; ttm_page_pool_init_locked(&_manager->wc_pool, GFP_HIGHUSER, "wc", 0); ttm_page_pool_init_locked(&_manager->uc_pool, GFP_HIGHUSER, "uc", 0); ttm_page_pool_init_locked(&_manager->wc_pool_dma32, GFP_USER | GFP_DMA32, "wc dma", 0); ttm_page_pool_init_locked(&_manager->uc_pool_dma32, GFP_USER | GFP_DMA32, "uc dma", 0); ttm_page_pool_init_locked(&_manager->wc_pool_huge, (GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM) & ~(__GFP_MOVABLE | __GFP_COMP), "wc huge", order); ttm_page_pool_init_locked(&_manager->uc_pool_huge, (GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM) & ~(__GFP_MOVABLE | __GFP_COMP) , "uc huge", order); _manager->options.max_size = max_pages; _manager->options.small = SMALL_ALLOCATION; _manager->options.alloc_size = NUM_PAGES_TO_ALLOC; ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type, &glob->kobj, "pool"); if (unlikely(ret != 0)) goto error; ret = ttm_pool_mm_shrink_init(_manager); if (unlikely(ret != 0)) goto error; return 0; error: kobject_put(&_manager->kobj); _manager = NULL; return ret; } void ttm_page_alloc_fini(void) { int i; pr_info("Finalizing pool allocator\n"); ttm_pool_mm_shrink_fini(_manager); /* OK to use static buffer since global mutex is no longer used. */ for (i = 0; i < NUM_POOLS; ++i) ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES, true); kobject_put(&_manager->kobj); _manager = NULL; } static void ttm_pool_unpopulate_helper(struct ttm_tt *ttm, unsigned mem_count_update) { struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob; unsigned i; if (mem_count_update == 0) goto put_pages; for (i = 0; i < mem_count_update; ++i) { if (!ttm->pages[i]) continue; ttm_mem_global_free_page(mem_glob, ttm->pages[i], PAGE_SIZE); } put_pages: ttm_put_pages(ttm->pages, ttm->num_pages, ttm->page_flags, ttm->caching_state); ttm->state = tt_unpopulated; } int ttm_pool_populate(struct ttm_tt *ttm, struct ttm_operation_ctx *ctx) { struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob; unsigned i; int ret; if (ttm->state != tt_unpopulated) return 0; if (ttm_check_under_lowerlimit(mem_glob, ttm->num_pages, ctx)) return -ENOMEM; ret = ttm_get_pages(ttm->pages, ttm->num_pages, ttm->page_flags, ttm->caching_state); if (unlikely(ret != 0)) { ttm_pool_unpopulate_helper(ttm, 0); return ret; } for (i = 0; i < ttm->num_pages; ++i) { ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i], PAGE_SIZE, ctx); if (unlikely(ret != 0)) { ttm_pool_unpopulate_helper(ttm, i); return -ENOMEM; } } if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) { ret = ttm_tt_swapin(ttm); if (unlikely(ret != 0)) { ttm_pool_unpopulate(ttm); return ret; } } ttm->state = tt_unbound; return 0; } EXPORT_SYMBOL(ttm_pool_populate); void ttm_pool_unpopulate(struct ttm_tt *ttm) { ttm_pool_unpopulate_helper(ttm, ttm->num_pages); } EXPORT_SYMBOL(ttm_pool_unpopulate); int ttm_populate_and_map_pages(struct device *dev, struct ttm_dma_tt *tt, struct ttm_operation_ctx *ctx) { unsigned i, j; int r; r = ttm_pool_populate(&tt->ttm, ctx); if (r) return r; for (i = 0; i < tt->ttm.num_pages; ++i) { struct page *p = tt->ttm.pages[i]; size_t num_pages = 1; for (j = i + 1; j < tt->ttm.num_pages; ++j) { if (++p != tt->ttm.pages[j]) break; ++num_pages; } tt->dma_address[i] = dma_map_page(dev, tt->ttm.pages[i], 0, num_pages * PAGE_SIZE, DMA_BIDIRECTIONAL); if (dma_mapping_error(dev, tt->dma_address[i])) { while (i--) { dma_unmap_page(dev, tt->dma_address[i], PAGE_SIZE, DMA_BIDIRECTIONAL); tt->dma_address[i] = 0; } ttm_pool_unpopulate(&tt->ttm); return -EFAULT; } for (j = 1; j < num_pages; ++j) { tt->dma_address[i + 1] = tt->dma_address[i] + PAGE_SIZE; ++i; } } return 0; } EXPORT_SYMBOL(ttm_populate_and_map_pages); void ttm_unmap_and_unpopulate_pages(struct device *dev, struct ttm_dma_tt *tt) { unsigned i, j; for (i = 0; i < tt->ttm.num_pages;) { struct page *p = tt->ttm.pages[i]; size_t num_pages = 1; if (!tt->dma_address[i] || !tt->ttm.pages[i]) { ++i; continue; } for (j = i + 1; j < tt->ttm.num_pages; ++j) { if (++p != tt->ttm.pages[j]) break; ++num_pages; } dma_unmap_page(dev, tt->dma_address[i], num_pages * PAGE_SIZE, DMA_BIDIRECTIONAL); i += num_pages; } ttm_pool_unpopulate(&tt->ttm); } EXPORT_SYMBOL(ttm_unmap_and_unpopulate_pages); int ttm_page_alloc_debugfs(struct seq_file *m, void *data) { struct ttm_page_pool *p; unsigned i; char *h[] = {"pool", "refills", "pages freed", "size"}; if (!_manager) { seq_printf(m, "No pool allocator running.\n"); return 0; } seq_printf(m, "%7s %12s %13s %8s\n", h[0], h[1], h[2], h[3]); for (i = 0; i < NUM_POOLS; ++i) { p = &_manager->pools[i]; seq_printf(m, "%7s %12ld %13ld %8d\n", p->name, p->nrefills, p->nfrees, p->npages); } return 0; } EXPORT_SYMBOL(ttm_page_alloc_debugfs);
./CrossVul/dataset_final_sorted/CWE-125/c/good_1330_0
crossvul-cpp_data_good_3328_0
/* Copyright (c) 2013-2014. The YARA Authors. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ #define _GNU_SOURCE #include <string.h> #include <assert.h> #include <time.h> #include <math.h> #include <yara/endian.h> #include <yara/exec.h> #include <yara/limits.h> #include <yara/error.h> #include <yara/object.h> #include <yara/modules.h> #include <yara/re.h> #include <yara/strutils.h> #include <yara/utils.h> #include <yara/mem.h> #include <yara.h> #define MEM_SIZE MAX_LOOP_NESTING * LOOP_LOCAL_VARS #define push(x) \ if (sp < stack_size) \ { \ stack[sp++] = (x); \ } \ else \ { \ result = ERROR_EXEC_STACK_OVERFLOW; \ stop = TRUE; \ break; \ } \ #define pop(x) x = stack[--sp] #define is_undef(x) IS_UNDEFINED((x).i) #define ensure_defined(x) \ if (is_undef(x)) \ { \ r1.i = UNDEFINED; \ push(r1); \ break; \ } #define little_endian_uint8_t(x) (x) #define little_endian_int8_t(x) (x) #define little_endian_uint16_t(x) yr_le16toh(x) #define little_endian_int16_t(x) yr_le16toh(x) #define little_endian_uint32_t(x) yr_le32toh(x) #define little_endian_int32_t(x) yr_le32toh(x) #define big_endian_uint8_t(x) (x) #define big_endian_int8_t(x) (x) #define big_endian_uint16_t(x) yr_be16toh(x) #define big_endian_int16_t(x) yr_be16toh(x) #define big_endian_uint32_t(x) yr_be32toh(x) #define big_endian_int32_t(x) yr_be32toh(x) #define function_read(type, endianess) \ int64_t read_##type##_##endianess(YR_MEMORY_BLOCK_ITERATOR* iterator, size_t offset) \ { \ YR_MEMORY_BLOCK* block = iterator->first(iterator); \ while (block != NULL) \ { \ if (offset >= block->base && \ block->size >= sizeof(type) && \ offset <= block->base + block->size - sizeof(type)) \ { \ type result; \ uint8_t* data = block->fetch_data(block); \ if (data == NULL) \ return UNDEFINED; \ result = *(type *)(data + offset - block->base); \ result = endianess##_##type(result); \ return result; \ } \ block = iterator->next(iterator); \ } \ return UNDEFINED; \ }; function_read(uint8_t, little_endian) function_read(uint16_t, little_endian) function_read(uint32_t, little_endian) function_read(int8_t, little_endian) function_read(int16_t, little_endian) function_read(int32_t, little_endian) function_read(uint8_t, big_endian) function_read(uint16_t, big_endian) function_read(uint32_t, big_endian) function_read(int8_t, big_endian) function_read(int16_t, big_endian) function_read(int32_t, big_endian) static uint8_t* jmp_if( int condition, uint8_t* ip) { uint8_t* result; if (condition) { result = *(uint8_t**)(ip + 1); // ip will be incremented at the end of the execution loop, // decrement it here to compensate. result--; } else { result = ip + sizeof(uint64_t); } return result; } int yr_execute_code( YR_RULES* rules, YR_SCAN_CONTEXT* context, int timeout, time_t start_time) { int64_t mem[MEM_SIZE]; int32_t sp = 0; uint8_t* ip = rules->code_start; YR_VALUE args[MAX_FUNCTION_ARGS]; YR_VALUE *stack; YR_VALUE r1; YR_VALUE r2; YR_VALUE r3; #ifdef PROFILING_ENABLED YR_RULE* current_rule = NULL; #endif YR_RULE* rule; YR_MATCH* match; YR_OBJECT_FUNCTION* function; char* identifier; char* args_fmt; int i; int found; int count; int result = ERROR_SUCCESS; int stop = FALSE; int cycle = 0; int tidx = context->tidx; int stack_size; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); if (stack == NULL) return ERROR_INSUFFICIENT_MEMORY; while(!stop) { switch(*ip) { case OP_HALT: assert(sp == 0); // When HALT is reached the stack should be empty. stop = TRUE; break; case OP_PUSH: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); push(r1); break; case OP_POP: pop(r1); break; case OP_CLEAR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i] = 0; break; case OP_ADD_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (!is_undef(r2)) mem[r1.i] += r2.i; break; case OP_INCR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i]++; break; case OP_PUSH_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r1.i = mem[r1.i]; push(r1); break; case OP_POP_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); mem[r1.i] = r2.i; break; case OP_SWAPUNDEF: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (is_undef(r2)) { r1.i = mem[r1.i]; push(r1); } else { push(r2); } break; case OP_JNUNDEF: pop(r1); push(r1); ip = jmp_if(!is_undef(r1), ip); break; case OP_JLE: pop(r2); pop(r1); push(r1); push(r2); ip = jmp_if(r1.i <= r2.i, ip); break; case OP_JTRUE: pop(r1); push(r1); ip = jmp_if(!is_undef(r1) && r1.i, ip); break; case OP_JFALSE: pop(r1); push(r1); ip = jmp_if(is_undef(r1) || !r1.i, ip); break; case OP_AND: pop(r2); pop(r1); if (is_undef(r1) || is_undef(r2)) r1.i = 0; else r1.i = r1.i && r2.i; push(r1); break; case OP_OR: pop(r2); pop(r1); if (is_undef(r1)) { push(r2); } else if (is_undef(r2)) { push(r1); } else { r1.i = r1.i || r2.i; push(r1); } break; case OP_NOT: pop(r1); if (is_undef(r1)) r1.i = UNDEFINED; else r1.i= !r1.i; push(r1); break; case OP_MOD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i % r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_SHR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >> r2.i; push(r1); break; case OP_SHL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i << r2.i; push(r1); break; case OP_BITWISE_NOT: pop(r1); ensure_defined(r1); r1.i = ~r1.i; push(r1); break; case OP_BITWISE_AND: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i & r2.i; push(r1); break; case OP_BITWISE_OR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i | r2.i; push(r1); break; case OP_BITWISE_XOR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i ^ r2.i; push(r1); break; case OP_PUSH_RULE: rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; push(r1); break; case OP_INIT_RULE: #ifdef PROFILING_ENABLED current_rule = *(YR_RULE**)(ip + 1); #endif ip += sizeof(uint64_t); break; case OP_MATCH_RULE: pop(r1); rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); if (!is_undef(r1) && r1.i) rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; else if (RULE_IS_GLOBAL(rule)) rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; #ifdef PROFILING_ENABLED rule->clock_ticks += clock() - start; start = clock(); #endif break; case OP_OBJ_LOAD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); r1.o = (YR_OBJECT*) yr_hash_table_lookup( context->objects_table, identifier, NULL); assert(r1.o != NULL); push(r1); break; case OP_OBJ_FIELD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); pop(r1); ensure_defined(r1); r1.o = yr_object_lookup_field(r1.o, identifier); assert(r1.o != NULL); push(r1); break; case OP_OBJ_VALUE: pop(r1); ensure_defined(r1); switch(r1.o->type) { case OBJECT_TYPE_INTEGER: r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; break; case OBJECT_TYPE_FLOAT: if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) r1.i = UNDEFINED; else r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; break; case OBJECT_TYPE_STRING: if (((YR_OBJECT_STRING*) r1.o)->value == NULL) r1.i = UNDEFINED; else r1.p = ((YR_OBJECT_STRING*) r1.o)->value; break; default: assert(FALSE); } push(r1); break; case OP_INDEX_ARRAY: pop(r1); // index pop(r2); // array ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_ARRAY); r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_LOOKUP_DICT: pop(r1); // key pop(r2); // dictionary ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_DICTIONARY); r1.o = yr_object_dict_get_item( r2.o, 0, r1.ss->c_string); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_CALL: args_fmt = *(char**)(ip + 1); ip += sizeof(uint64_t); i = (int) strlen(args_fmt); count = 0; // pop arguments from stack and copy them to args array while (i > 0) { pop(r1); if (is_undef(r1)) // count the number of undefined args count++; args[i - 1] = r1; i--; } pop(r2); ensure_defined(r2); if (count > 0) { // if there are undefined args, result for function call // is undefined as well. r1.i = UNDEFINED; push(r1); break; } function = (YR_OBJECT_FUNCTION*) r2.o; result = ERROR_INTERNAL_FATAL_ERROR; for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { if (function->prototypes[i].arguments_fmt == NULL) break; if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) { result = function->prototypes[i].code(args, context, function); break; } } assert(i < MAX_OVERLOADED_FUNCTIONS); if (result == ERROR_SUCCESS) { r1.o = function->return_obj; push(r1); } else { stop = TRUE; } break; case OP_FOUND: pop(r1); r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; push(r1); break; case OP_FOUND_AT: pop(r2); pop(r1); if (is_undef(r1)) { r1.i = 0; push(r1); break; } match = r2.s->matches[tidx].head; r3.i = FALSE; while (match != NULL) { if (r1.i == match->base + match->offset) { r3.i = TRUE; break; } if (r1.i < match->base + match->offset) break; match = match->next; } push(r3); break; case OP_FOUND_IN: pop(r3); pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); match = r3.s->matches[tidx].head; r3.i = FALSE; while (match != NULL && !r3.i) { if (match->base + match->offset >= r1.i && match->base + match->offset <= r2.i) { r3.i = TRUE; } if (match->base + match->offset > r2.i) break; match = match->next; } push(r3); break; case OP_COUNT: pop(r1); r1.i = r1.s->matches[tidx].count; push(r1); break; case OP_OFFSET: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->base + match->offset; i++; match = match->next; } push(r3); break; case OP_LENGTH: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->match_length; i++; match = match->next; } push(r3); break; case OP_OF: found = 0; count = 0; pop(r1); while (!is_undef(r1)) { if (r1.s->matches[tidx].tail != NULL) found++; count++; pop(r1); } pop(r2); if (is_undef(r2)) r1.i = found >= count ? 1 : 0; else r1.i = found >= r2.i ? 1 : 0; push(r1); break; case OP_FILESIZE: r1.i = context->file_size; push(r1); break; case OP_ENTRYPOINT: r1.i = context->entry_point; push(r1); break; case OP_INT8: pop(r1); r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16: pop(r1); r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32: pop(r1); r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8: pop(r1); r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16: pop(r1); r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32: pop(r1); r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT8BE: pop(r1); r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16BE: pop(r1); r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32BE: pop(r1); r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8BE: pop(r1); r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16BE: pop(r1); r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32BE: pop(r1); r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_CONTAINS: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); r1.i = memmem(r1.ss->c_string, r1.ss->length, r2.ss->c_string, r2.ss->length) != NULL; push(r1); break; case OP_IMPORT: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); result = yr_modules_load((char*) r1.p, context); if (result != ERROR_SUCCESS) stop = TRUE; break; case OP_MATCHES: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r1.ss->length == 0) { r1.i = FALSE; push(r1); break; } r1.i = yr_re_exec( (uint8_t*) r2.re->code, (uint8_t*) r1.ss->c_string, r1.ss->length, 0, r2.re->flags | RE_FLAGS_SCAN, NULL, NULL) >= 0; push(r1); break; case OP_INT_TO_DBL: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r2 = stack[sp - r1.i]; if (is_undef(r2)) stack[sp - r1.i].i = UNDEFINED; else stack[sp - r1.i].d = (double) r2.i; break; case OP_STR_TO_BOOL: pop(r1); ensure_defined(r1); r1.i = r1.ss->length > 0; push(r1); break; case OP_INT_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i == r2.i; push(r1); break; case OP_INT_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i != r2.i; push(r1); break; case OP_INT_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i < r2.i; push(r1); break; case OP_INT_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i > r2.i; push(r1); break; case OP_INT_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i <= r2.i; push(r1); break; case OP_INT_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >= r2.i; push(r1); break; case OP_INT_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i + r2.i; push(r1); break; case OP_INT_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i - r2.i; push(r1); break; case OP_INT_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i * r2.i; push(r1); break; case OP_INT_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i / r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_INT_MINUS: pop(r1); ensure_defined(r1); r1.i = -r1.i; push(r1); break; case OP_DBL_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d < r2.d; push(r1); break; case OP_DBL_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d > r2.d; push(r1); break; case OP_DBL_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d <= r2.d; push(r1); break; case OP_DBL_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d >= r2.d; push(r1); break; case OP_DBL_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d == r2.d; push(r1); break; case OP_DBL_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d != r2.d; push(r1); break; case OP_DBL_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d + r2.d; push(r1); break; case OP_DBL_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d - r2.d; push(r1); break; case OP_DBL_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d * r2.d; push(r1); break; case OP_DBL_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d / r2.d; push(r1); break; case OP_DBL_MINUS: pop(r1); ensure_defined(r1); r1.d = -r1.d; push(r1); break; case OP_STR_EQ: case OP_STR_NEQ: case OP_STR_LT: case OP_STR_LE: case OP_STR_GT: case OP_STR_GE: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); switch(*ip) { case OP_STR_EQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); break; case OP_STR_NEQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); break; case OP_STR_LT: r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); break; case OP_STR_LE: r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); break; case OP_STR_GT: r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); break; case OP_STR_GE: r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); break; } push(r1); break; default: // Unknown instruction, this shouldn't happen. assert(FALSE); } if (timeout > 0) // timeout == 0 means no timeout { // Check for timeout every 10 instruction cycles. if (++cycle == 10) { if (difftime(time(NULL), start_time) > timeout) { #ifdef PROFILING_ENABLED assert(current_rule != NULL); current_rule->clock_ticks += clock() - start; #endif result = ERROR_SCAN_TIMEOUT; stop = TRUE; } cycle = 0; } } ip++; } yr_modules_unload_all(context); yr_free(stack); return result; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3328_0
crossvul-cpp_data_good_5248_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS GGGG IIIII % % SS G I % % SSS G GG I % % SS G G I % % SSSSS GGG IIIII % % % % % % Read/Write Irix RGB 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 "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Typedef declaractions. */ typedef struct _SGIInfo { unsigned short magic; unsigned char storage, bytes_per_pixel; unsigned short dimension, columns, rows, depth; size_t minimum_value, maximum_value, sans; char name[80]; size_t pixel_format; unsigned char filler[404]; } SGIInfo; /* Forward declarations. */ static MagickBooleanType WriteSGIImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S G I % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSGI() returns MagickTrue if the image format type, identified by the % magick string, is SGI. % % The format of the IsSGI method is: % % MagickBooleanType IsSGI(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 IsSGI(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\001\332",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S G I I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSGIImage() reads a SGI RGB 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 ReadSGIImage method is: % % Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SGIDecode(const size_t bytes_per_pixel, ssize_t number_packets,unsigned char *packets,ssize_t number_pixels, unsigned char *pixels) { register unsigned char *p, *q; size_t pixel; ssize_t count; p=packets; q=pixels; if (bytes_per_pixel == 2) { for ( ; number_pixels > 0; ) { if (number_packets-- == 0) return(MagickFalse); pixel=(size_t) (*p++) << 8; pixel|=(*p++); count=(ssize_t) (pixel & 0x7f); if (count == 0) break; if (count > (ssize_t) number_pixels) return(MagickFalse); number_pixels-=count; if ((pixel & 0x80) != 0) for ( ; count != 0; count--) { if (number_packets-- == 0) return(MagickFalse); *q=(*p++); *(q+1)=(*p++); q+=8; } else { pixel=(size_t) (*p++) << 8; pixel|=(*p++); for ( ; count != 0; count--) { if (number_packets-- == 0) return(MagickFalse); *q=(unsigned char) (pixel >> 8); *(q+1)=(unsigned char) pixel; q+=8; } } } return(MagickTrue); } for ( ; number_pixels > 0; ) { if (number_packets-- == 0) return(MagickFalse); pixel=(size_t) (*p++); count=(ssize_t) (pixel & 0x7f); if (count == 0) break; if (count > (ssize_t) number_pixels) return(MagickFalse); number_pixels-=count; if ((pixel & 0x80) != 0) for ( ; count != 0; count--) { if (number_packets-- == 0) return(MagickFalse); *q=(*p++); q+=4; } else { if (number_packets-- == 0) return(MagickFalse); pixel=(size_t) (*p++); for ( ; count != 0; count--) { *q=(unsigned char) pixel; q+=4; } } } return(MagickTrue); } static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); (void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,"label",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); (void) count; image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256; } if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S G I I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSGIImage() adds properties for the SGI 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 RegisterSGIImage method is: % % size_t RegisterSGIImage(void) % */ ModuleExport size_t RegisterSGIImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("SGI","SGI","Irix RGB image"); entry->decoder=(DecodeImageHandler *) ReadSGIImage; entry->encoder=(EncodeImageHandler *) WriteSGIImage; entry->magick=(IsImageFormatHandler *) IsSGI; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S G I I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSGIImage() removes format registrations made by the % SGI module from the list of supported formats. % % The format of the UnregisterSGIImage method is: % % UnregisterSGIImage(void) % */ ModuleExport void UnregisterSGIImage(void) { (void) UnregisterMagickInfo("SGI"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S G I I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSGIImage() writes an image in SGI RGB encoded image format. % % The format of the WriteSGIImage method is: % % MagickBooleanType WriteSGIImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static size_t SGIEncode(unsigned char *pixels,size_t length, unsigned char *packets) { short runlength; register unsigned char *p, *q; unsigned char *limit, *mark; p=pixels; limit=p+length*4; q=packets; while (p < limit) { mark=p; p+=8; while ((p < limit) && ((*(p-8) != *(p-4)) || (*(p-4) != *p))) p+=4; p-=8; length=(size_t) (p-mark) >> 2; while (length != 0) { runlength=(short) (length > 126 ? 126 : length); length-=runlength; *q++=(unsigned char) (0x80 | runlength); for ( ; runlength > 0; runlength--) { *q++=(*mark); mark+=4; } } mark=p; p+=4; while ((p < limit) && (*p == *mark)) p+=4; length=(size_t) (p-mark) >> 2; while (length != 0) { runlength=(short) (length > 126 ? 126 : length); length-=runlength; *q++=(unsigned char) runlength; *q++=(*mark); } } *q++='\0'; return((size_t) (q-packets)); } static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { CompressionType compression; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; MemoryInfo *pixel_info; SGIInfo iris_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; ssize_t y, z; unsigned char *pixels, *packets; /* 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); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SGI raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) ResetMagickMemory(&iris_info,0,sizeof(iris_info)); iris_info.magic=0x01DA; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (image->depth > 8) compression=NoCompression; if (compression == NoCompression) iris_info.storage=(unsigned char) 0x00; else iris_info.storage=(unsigned char) 0x01; iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1); iris_info.dimension=3; iris_info.columns=(unsigned short) image->columns; iris_info.rows=(unsigned short) image->rows; if (image->alpha_trait != UndefinedPixelTrait) iris_info.depth=4; else { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { iris_info.dimension=2; iris_info.depth=1; } else iris_info.depth=3; } iris_info.minimum_value=0; iris_info.maximum_value=(size_t) (image->depth <= 8 ? 1UL*ScaleQuantumToChar(QuantumRange) : 1UL*ScaleQuantumToShort(QuantumRange)); /* Write SGI header. */ (void) WriteBlobMSBShort(image,iris_info.magic); (void) WriteBlobByte(image,iris_info.storage); (void) WriteBlobByte(image,iris_info.bytes_per_pixel); (void) WriteBlobMSBShort(image,iris_info.dimension); (void) WriteBlobMSBShort(image,iris_info.columns); (void) WriteBlobMSBShort(image,iris_info.rows); (void) WriteBlobMSBShort(image,iris_info.depth); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name)); (void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format); (void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler); /* Allocate SGI pixels. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*iris_info.bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory((size_t) number_pixels,4* iris_info.bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Convert image pixels to uncompressed SGI pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (image->depth <= 8) for (x=0; x < (ssize_t) image->columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } else for (x=0; x < (ssize_t) image->columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } switch (compression) { case NoCompression: { /* Write uncompressed SGI pixels. */ for (z=0; z < (ssize_t) iris_info.depth; z++) { for (y=0; y < (ssize_t) iris_info.rows; y++) { if (image->depth <= 8) for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobByte(image,*q); } else for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobMSBShort(image,*q); } } } break; } default: { MemoryInfo *packet_info; size_t length, number_packets, *runlength; ssize_t offset, *offsets; /* Convert SGI uncompressed pixels. */ offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)* image->rows,4*sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets != (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength != (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info != (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth); number_packets=0; q=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { length=SGIEncode(q+z,(size_t) iris_info.columns,packets+ number_packets); number_packets+=length; offsets[y+z*iris_info.rows]=offset; runlength[y+z*iris_info.rows]=(size_t) length; offset+=(ssize_t) length; } q+=(iris_info.columns*4); } /* Write out line start and length tables and runlength-encoded pixels. */ for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) offsets[i]); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) runlength[i]); (void) WriteBlob(image,number_packets,packets); /* Relinquish resources. */ offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5248_1
crossvul-cpp_data_good_89_0
/* * Copyright (c) Christos Zoulas 2003. * 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 immediately at the beginning of the file, without modification, * 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 AUTHOR 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 AUTHOR 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 "file.h" #ifndef lint FILE_RCSID("@(#)$File: readelf.c,v 1.143 2018/06/09 16:00:06 christos Exp $") #endif #ifdef BUILTIN_ELF #include <string.h> #include <ctype.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "readelf.h" #include "magic.h" #ifdef ELFCORE private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int *, uint16_t *); #endif private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int *, uint16_t *); private int doshn(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int, int *, uint16_t *); private size_t donote(struct magic_set *, void *, size_t, size_t, int, int, size_t, int *, uint16_t *, int, off_t, int, off_t); #define ELF_ALIGN(a) ((((a) + align - 1) / align) * align) #define isquote(c) (strchr("'\"`", (c)) != NULL) private uint16_t getu16(int, uint16_t); private uint32_t getu32(int, uint32_t); private uint64_t getu64(int, uint64_t); #define MAX_PHNUM 128 #define MAX_SHNUM 32768 #define SIZE_UNKNOWN CAST(off_t, -1) private int toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s (%u)", name, num) == -1) return -1; return 0; } private uint16_t getu16(int swap, uint16_t value) { union { uint16_t ui; char c[2]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[1]; retval.c[1] = tmpval.c[0]; return retval.ui; } else return value; } private uint32_t getu32(int swap, uint32_t value) { union { uint32_t ui; char c[4]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[3]; retval.c[1] = tmpval.c[2]; retval.c[2] = tmpval.c[1]; retval.c[3] = tmpval.c[0]; return retval.ui; } else return value; } private uint64_t getu64(int swap, uint64_t value) { union { uint64_t ui; char c[8]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[7]; retval.c[1] = tmpval.c[6]; retval.c[2] = tmpval.c[5]; retval.c[3] = tmpval.c[4]; retval.c[4] = tmpval.c[3]; retval.c[5] = tmpval.c[2]; retval.c[6] = tmpval.c[1]; retval.c[7] = tmpval.c[0]; return retval.ui; } else return value; } #define elf_getu16(swap, value) getu16(swap, value) #define elf_getu32(swap, value) getu32(swap, value) #define elf_getu64(swap, value) getu64(swap, value) #define xsh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &sh32) \ : CAST(void *, &sh64)) #define xsh_sizeof (clazz == ELFCLASS32 \ ? sizeof(sh32) \ : sizeof(sh64)) #define xsh_size CAST(size_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_size) \ : elf_getu64(swap, sh64.sh_size))) #define xsh_offset CAST(off_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_offset) \ : elf_getu64(swap, sh64.sh_offset))) #define xsh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_type) \ : elf_getu32(swap, sh64.sh_type)) #define xsh_name (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_name) \ : elf_getu32(swap, sh64.sh_name)) #define xph_addr (clazz == ELFCLASS32 \ ? CAST(void *, &ph32) \ : CAST(void *, &ph64)) #define xph_sizeof (clazz == ELFCLASS32 \ ? sizeof(ph32) \ : sizeof(ph64)) #define xph_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_type) \ : elf_getu32(swap, ph64.p_type)) #define xph_offset CAST(off_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_offset) \ : elf_getu64(swap, ph64.p_offset))) #define xph_align CAST(size_t, (clazz == ELFCLASS32 \ ? CAST(off_t, (ph32.p_align ? \ elf_getu32(swap, ph32.p_align) : 4))\ : CAST(off_t, (ph64.p_align ? \ elf_getu64(swap, ph64.p_align) : 4)))) #define xph_vaddr CAST(size_t, (clazz == ELFCLASS32 \ ? CAST(off_t, (ph32.p_vaddr ? \ elf_getu32(swap, ph32.p_vaddr) : 4))\ : CAST(off_t, (ph64.p_vaddr ? \ elf_getu64(swap, ph64.p_vaddr) : 4)))) #define xph_filesz CAST(size_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_filesz) \ : elf_getu64(swap, ph64.p_filesz))) #define xph_memsz CAST(size_t, ((clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_memsz) \ : elf_getu64(swap, ph64.p_memsz)))) #define xnh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &nh32) \ : CAST(void *, &nh64)) #define xnh_sizeof (clazz == ELFCLASS32 \ ? sizeof(nh32) \ : sizeof(nh64)) #define xnh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_type) \ : elf_getu32(swap, nh64.n_type)) #define xnh_namesz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_namesz) \ : elf_getu32(swap, nh64.n_namesz)) #define xnh_descsz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_descsz) \ : elf_getu32(swap, nh64.n_descsz)) #define xdh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &dh32) \ : CAST(void *, &dh64)) #define xdh_sizeof (clazz == ELFCLASS32 \ ? sizeof(dh32) \ : sizeof(dh64)) #define xdh_tag (clazz == ELFCLASS32 \ ? elf_getu32(swap, dh32.d_tag) \ : elf_getu64(swap, dh64.d_tag)) #define xdh_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, dh32.d_un.d_val) \ : elf_getu64(swap, dh64.d_un.d_val)) #define xcap_addr (clazz == ELFCLASS32 \ ? CAST(void *, &cap32) \ : CAST(void *, &cap64)) #define xcap_sizeof (clazz == ELFCLASS32 \ ? sizeof(cap32) \ : sizeof(cap64)) #define xcap_tag (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_tag) \ : elf_getu64(swap, cap64.c_tag)) #define xcap_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_un.c_val) \ : elf_getu64(swap, cap64.c_un.c_val)) #define xauxv_addr (clazz == ELFCLASS32 \ ? CAST(void *, &auxv32) \ : CAST(void *, &auxv64)) #define xauxv_sizeof (clazz == ELFCLASS32 \ ? sizeof(auxv32) \ : sizeof(auxv64)) #define xauxv_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_type) \ : elf_getu64(swap, auxv64.a_type)) #define xauxv_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_v) \ : elf_getu64(swap, auxv64.a_v)) #define prpsoffsets(i) (clazz == ELFCLASS32 \ ? prpsoffsets32[i] \ : prpsoffsets64[i]) #ifdef ELFCORE /* * Try larger offsets first to avoid false matches * from earlier data that happen to look like strings. */ static const size_t prpsoffsets32[] = { #ifdef USE_NT_PSINFO 104, /* SunOS 5.x (command line) */ 88, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 100, /* SunOS 5.x (command line) */ 84, /* SunOS 5.x (short name) */ 44, /* Linux (command line) */ 28, /* Linux 2.0.36 (short name) */ 8, /* FreeBSD */ }; static const size_t prpsoffsets64[] = { #ifdef USE_NT_PSINFO 152, /* SunOS 5.x (command line) */ 136, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 136, /* SunOS 5.x, 64-bit (command line) */ 120, /* SunOS 5.x, 64-bit (short name) */ 56, /* Linux (command line) */ 40, /* Linux (tested on core from 2.4.x, short name) */ 16, /* FreeBSD, 64-bit */ }; #define NOFFSETS32 (sizeof(prpsoffsets32) / sizeof(prpsoffsets32[0])) #define NOFFSETS64 (sizeof(prpsoffsets64) / sizeof(prpsoffsets64[0])) #define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64) /* * Look through the program headers of an executable image, searching * for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or * "FreeBSD"; if one is found, try looking in various places in its * contents for a 16-character string containing only printable * characters - if found, that string should be the name of the program * that dropped core. Note: right after that 16-character string is, * at least in SunOS 5.x (and possibly other SVR4-flavored systems) and * Linux, a longer string (80 characters, in 5.x, probably other * SVR4-flavored systems, and Linux) containing the start of the * command line for that program. * * SunOS 5.x core files contain two PT_NOTE sections, with the types * NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the * same info about the command name and command line, so it probably * isn't worthwhile to look for NT_PSINFO, but the offsets are provided * above (see USE_NT_PSINFO), in case we ever decide to do so. The * NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent; * the SunOS 5.x file command relies on this (and prefers the latter). * * The signal number probably appears in a section of type NT_PRSTATUS, * but that's also rather OS-dependent, in ways that are harder to * dissect with heuristics, so I'm not bothering with the signal number. * (I suppose the signal number could be of interest in situations where * you don't have the binary of the program that dropped core; if you * *do* have that binary, the debugger will probably tell you what * signal it was.) */ #define OS_STYLE_SVR4 0 #define OS_STYLE_FREEBSD 1 #define OS_STYLE_NETBSD 2 private const char os_style_names[][8] = { "SVR4", "FreeBSD", "NetBSD", }; #define FLAGS_CORE_STYLE 0x0003 #define FLAGS_DID_CORE 0x0004 #define FLAGS_DID_OS_NOTE 0x0008 #define FLAGS_DID_BUILD_ID 0x0010 #define FLAGS_DID_CORE_STYLE 0x0020 #define FLAGS_DID_NETBSD_PAX 0x0040 #define FLAGS_DID_NETBSD_MARCH 0x0080 #define FLAGS_DID_NETBSD_CMODEL 0x0100 #define FLAGS_DID_NETBSD_EMULATION 0x0200 #define FLAGS_DID_NETBSD_UNKNOWN 0x0400 #define FLAGS_IS_CORE 0x0800 #define FLAGS_DID_AUXV 0x1000 private int dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; off_t ph_off = off; int ph_num = num; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < CAST(ssize_t, xph_sizeof)) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags, notecount, fd, ph_off, ph_num, fsize); if (offset == 0) break; } } return 0; } #endif static void do_note_netbsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for NetBSD") == -1) return; /* * The version number used to be stuck as 199905, and was thus * basically content-free. Newer versions of NetBSD have fixed * this and now use the encoding of __NetBSD_Version__: * * MMmmrrpp00 * * M = major version * m = minor version * r = release ["",A-Z,Z[A-Z] but numeric] * p = patchlevel */ if (desc > 100000000U) { uint32_t ver_patch = (desc / 100) % 100; uint32_t ver_rel = (desc / 10000) % 100; uint32_t ver_min = (desc / 1000000) % 100; uint32_t ver_maj = desc / 100000000; if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1) return; if (ver_rel == 0 && ver_patch != 0) { if (file_printf(ms, ".%u", ver_patch) == -1) return; } else if (ver_rel != 0) { while (ver_rel > 26) { if (file_printf(ms, "Z") == -1) return; ver_rel -= 26; } if (file_printf(ms, "%c", 'A' + ver_rel - 1) == -1) return; } } } static void do_note_freebsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for FreeBSD") == -1) return; /* * Contents is __FreeBSD_version, whose relation to OS * versions is defined by a huge table in the Porter's * Handbook. This is the general scheme: * * Releases: * Mmp000 (before 4.10) * Mmi0p0 (before 5.0) * Mmm0p0 * * Development branches: * Mmpxxx (before 4.6) * Mmp1xx (before 4.10) * Mmi1xx (before 5.0) * M000xx (pre-M.0) * Mmm1xx * * M = major version * m = minor version * i = minor version increment (491000 -> 4.10) * p = patchlevel * x = revision * * The first release of FreeBSD to use ELF by default * was version 3.0. */ if (desc == 460002) { if (file_printf(ms, " 4.6.2") == -1) return; } else if (desc < 460100) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10) == -1) return; if (desc / 1000 % 10 > 0) if (file_printf(ms, ".%d", desc / 1000 % 10) == -1) return; if ((desc % 1000 > 0) || (desc % 100000 == 0)) if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc < 500000) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10 + desc / 1000 % 10) == -1) return; if (desc / 100 % 10 > 0) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } else { if (file_printf(ms, " %d.%d", desc / 100000, desc / 1000 % 100) == -1) return; if ((desc / 100 % 10 > 0) || (desc % 100000 / 100 == 0)) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } } private int /*ARGSUSED*/ do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; } private int do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && type == NT_GNU_VERSION && descsz == 2) { *flags |= FLAGS_DID_OS_NOTE; file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]); return 1; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; memcpy(desc, &nbuf[doff], sizeof(desc)); *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for GNU/") == -1) return 1; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return 1; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return 1; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return 1; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return 1; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return 1; break; default: if (file_printf(ms, "<unknown>") == -1) return 1; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return 1; return 1; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (type == NT_NETBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_netbsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (type == NT_FREEBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_freebsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && type == NT_OPENBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for OpenBSD") == -1) return 1; /* Content of note is always 0 */ return 1; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for DragonFly") == -1) return 1; memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, " %d.%d.%d", desc / 100000, desc / 10000 % 10, desc % 10000) == -1) return 1; return 1; } return 0; } private int do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && type == NT_NETBSD_PAX && descsz == 4) { static const char *pax[] = { "+mprotect", "-mprotect", "+segvguard", "-segvguard", "+ASLR", "-ASLR", }; uint32_t desc; size_t i; int did = 0; *flags |= FLAGS_DID_NETBSD_PAX; memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return 1; for (i = 0; i < __arraycount(pax); i++) { if (((1 << (int)i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return 1; } return 1; } return 0; } private int do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, " "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)", file_printable(sbuf, sizeof(sbuf), CAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; cp < nbuf + size && *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; } private off_t get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t off, int num, off_t fsize, uint64_t virtaddr) { Elf32_Phdr ph32; Elf64_Phdr ph64; /* * Loop through all the program headers and find the header with * virtual address in which the "virtaddr" belongs to. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += xph_sizeof; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz) return xph_offset + (virtaddr - xph_vaddr); } return 0; } private size_t get_string_on_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t ph_off, int ph_num, off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen) { char *bptr; off_t offset; if (buflen == 0) return 0; offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, virtaddr); if ((buflen = pread(fd, buf, CAST(size_t, buflen), offset)) <= 0) { file_badread(ms); return 0; } buf[buflen - 1] = '\0'; /* We expect only printable characters, so return if buffer contains * non-printable character before the '\0' or just '\0'. */ for (bptr = buf; *bptr && isprint((unsigned char)*bptr); bptr++) continue; if (*bptr != '\0') return 0; return bptr - buf; } /*ARGSUSED*/ private int do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz __attribute__((__unused__)), uint32_t descsz __attribute__((__unused__)), size_t noff __attribute__((__unused__)), size_t doff, int *flags, size_t size __attribute__((__unused__)), int clazz, int fd, off_t ph_off, int ph_num, off_t fsize) { #ifdef ELFCORE Aux32Info auxv32; Aux64Info auxv64; size_t elsize = xauxv_sizeof; const char *tag; int is_string; size_t nval; if ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) != (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) return 0; switch (*flags & FLAGS_CORE_STYLE) { case OS_STYLE_SVR4: if (type != NT_AUXV) return 0; break; #ifdef notyet case OS_STYLE_NETBSD: if (type != NT_NETBSD_CORE_AUXV) return 0; break; case OS_STYLE_FREEBSD: if (type != NT_FREEBSD_PROCSTAT_AUXV) return 0; break; #endif default: return 0; } *flags |= FLAGS_DID_AUXV; nval = 0; for (size_t off = 0; off + elsize <= descsz; off += elsize) { memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof); /* Limit processing to 50 vector entries to prevent DoS */ if (nval++ >= 50) { file_error(ms, 0, "Too many ELF Auxv elements"); return 1; } switch(xauxv_type) { case AT_LINUX_EXECFN: is_string = 1; tag = "execfn"; break; case AT_LINUX_PLATFORM: is_string = 1; tag = "platform"; break; case AT_LINUX_UID: is_string = 0; tag = "real uid"; break; case AT_LINUX_GID: is_string = 0; tag = "real gid"; break; case AT_LINUX_EUID: is_string = 0; tag = "effective uid"; break; case AT_LINUX_EGID: is_string = 0; tag = "effective gid"; break; default: is_string = 0; tag = NULL; break; } if (tag == NULL) continue; if (is_string) { char buf[256]; ssize_t buflen; buflen = get_string_on_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf)); if (buflen == 0) continue; if (file_printf(ms, ", %s: '%s'", tag, buf) == -1) return 0; } else { if (file_printf(ms, ", %s: %d", tag, (int) xauxv_val) == -1) return 0; } } return 1; #else return 0; #endif } private size_t dodynamic(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap) { Elf32_Dyn dh32; Elf64_Dyn dh64; unsigned char *dbuf = CAST(unsigned char *, vbuf); if (xdh_sizeof + offset > size) { /* * We're out of note headers. */ return xdh_sizeof + offset; } memcpy(xdh_addr, &dbuf[offset], xdh_sizeof); offset += xdh_sizeof; switch (xdh_tag) { case DT_FLAGS_1: if (xdh_val == DF_1_PIE) ms->mode |= 0111; else ms->mode &= ~0111; break; default: break; } return offset; } private size_t donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags, uint16_t *notecount, int fd, off_t ph_off, int ph_num, off_t fsize) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { file_printf(ms, ", bad note name size %#lx", CAST(unsigned long, namesz)); return 0; } if (descsz & 0x80000000) { file_printf(ms, ", bad note description size %#lx", CAST(unsigned long, descsz)); return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & FLAGS_DID_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return offset; } if ((*flags & FLAGS_DID_AUXV) == 0) { if (do_auxv_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz, fd, ph_off, ph_num, fsize)) return offset; } if (namesz == 7 && strcmp(CAST(char *, &nbuf[noff]), "NetBSD") == 0) { int descw, flag; const char *str, *tag; if (descsz > 100) descsz = 100; switch (xnh_type) { case NT_NETBSD_VERSION: return offset; case NT_NETBSD_MARCH: flag = FLAGS_DID_NETBSD_MARCH; tag = "compiled for"; break; case NT_NETBSD_CMODEL: flag = FLAGS_DID_NETBSD_CMODEL; tag = "compiler model"; break; case NT_NETBSD_EMULATION: flag = FLAGS_DID_NETBSD_EMULATION; tag = "emulation:"; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return offset; *flags |= FLAGS_DID_NETBSD_UNKNOWN; if (file_printf(ms, ", note=%u", xnh_type) == -1) return offset; return offset; } if (*flags & flag) return offset; str = CAST(const char *, &nbuf[doff]); descw = CAST(int, descsz); *flags |= flag; file_printf(ms, ", %s: %.*s", tag, descw, str); return offset; } return offset; } /* SunOS 5.x hardware capability descriptions */ typedef struct cap_desc { uint64_t cd_mask; const char *cd_name; } cap_desc_t; static const cap_desc_t cap_desc_sparc[] = { { AV_SPARC_MUL32, "MUL32" }, { AV_SPARC_DIV32, "DIV32" }, { AV_SPARC_FSMULD, "FSMULD" }, { AV_SPARC_V8PLUS, "V8PLUS" }, { AV_SPARC_POPC, "POPC" }, { AV_SPARC_VIS, "VIS" }, { AV_SPARC_VIS2, "VIS2" }, { AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" }, { AV_SPARC_FMAF, "FMAF" }, { AV_SPARC_FJFMAU, "FJFMAU" }, { AV_SPARC_IMA, "IMA" }, { 0, NULL } }; static const cap_desc_t cap_desc_386[] = { { AV_386_FPU, "FPU" }, { AV_386_TSC, "TSC" }, { AV_386_CX8, "CX8" }, { AV_386_SEP, "SEP" }, { AV_386_AMD_SYSC, "AMD_SYSC" }, { AV_386_CMOV, "CMOV" }, { AV_386_MMX, "MMX" }, { AV_386_AMD_MMX, "AMD_MMX" }, { AV_386_AMD_3DNow, "AMD_3DNow" }, { AV_386_AMD_3DNowx, "AMD_3DNowx" }, { AV_386_FXSR, "FXSR" }, { AV_386_SSE, "SSE" }, { AV_386_SSE2, "SSE2" }, { AV_386_PAUSE, "PAUSE" }, { AV_386_SSE3, "SSE3" }, { AV_386_MON, "MON" }, { AV_386_CX16, "CX16" }, { AV_386_AHF, "AHF" }, { AV_386_TSCP, "TSCP" }, { AV_386_AMD_SSE4A, "AMD_SSE4A" }, { AV_386_POPCNT, "POPCNT" }, { AV_386_AMD_LZCNT, "AMD_LZCNT" }, { AV_386_SSSE3, "SSSE3" }, { AV_386_SSE4_1, "SSE4.1" }, { AV_386_SSE4_2, "SSE4.2" }, { 0, NULL } }; private int doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int mach, int strtab, int *flags, uint16_t *notecount) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1, has_debug_info = 0; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */ char name[50]; ssize_t namesize; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) < CAST(ssize_t, xsh_sizeof)) { if (file_printf(ms, ", missing section headers") == -1) return -1; return 0; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { file_badread(ms); return -1; } name[namesize] = '\0'; if (strcmp(name, ".debug_info") == 0) { has_debug_info = 1; stripped = 0; } if (pread(fd, xsh_addr, xsh_sizeof, off) < CAST(ssize_t, xsh_sizeof)) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if (CAST(uintmax_t, (xsh_size + xsh_offset)) > CAST(uintmax_t, fsize)) { if (file_printf(ms, ", note offset/size %#" INTMAX_T_FORMAT "x+%#" INTMAX_T_FORMAT "x exceeds" " file size %#" INTMAX_T_FORMAT "x", CAST(uintmax_t, xsh_offset), CAST(uintmax_t, xsh_size), CAST(uintmax_t, fsize)) == -1) return -1; return 0; } if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) < CAST(ssize_t, xsh_size)) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= CAST(off_t, xsh_size)) break; noff = donote(ms, nbuf, CAST(size_t, noff), xsh_size, clazz, swap, 4, flags, notecount, fd, 0, 0, 0); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == CAST(off_t, -1)) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof(cap32), sizeof(cap64))]; if ((coff += xcap_sizeof) > CAST(off_t, xsh_size)) break; if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) != CAST(ssize_t, xcap_sizeof)) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } // gnu attributes #endif break; } memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "%#" INT64_T_FORMAT "x = %#" INT64_T_FORMAT "x", CAST(unsigned long long, xcap_tag), CAST(unsigned long long, xcap_val)) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (has_debug_info) { if (file_printf(ms, ", with debug_info") == -1) return -1; } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_hw1)) == -1) return -1; } else { if (file_printf(ms, " hardware capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_hw1)) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_sf1)) == -1) return -1; } return 0; } /* * Look through the program headers of an executable image, searching * for a PT_INTERP section; if one is found, it's dynamically linked, * otherwise it's statically linked. */ private int dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int sh_num, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; char interp[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } interp[0] = '\0'; for ( ; num; num--) { int doread; if (pread(fd, xph_addr, xph_sizeof, off) < CAST(ssize_t, xph_sizeof)) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; doread = 1; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment %#lx", CAST(unsigned long, align)) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: doread = 1; break; default: doread = 0; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } if (doread) { len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } } else len = 0; /* Things we can determine when we seek */ switch (xph_type) { case PT_DYNAMIC: offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = dodynamic(ms, nbuf, offset, CAST(size_t, bufsize), clazz, swap); if (offset == 0) break; } break; case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; memcpy(interp, nbuf, bufsize); } else strlcpy(interp, "*empty*", sizeof(interp)); break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, CAST(size_t, bufsize), clazz, swap, align, flags, notecount, fd, 0, 0, 0); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } protected int file_tryelf(struct magic_set *ms, const struct buffer *b) { int fd = b->fd; const unsigned char *buf = b->fbuf; size_t nbytes = b->flen; union { int32_t l; char c[sizeof(int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE|MAGIC_EXTENSION)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, CAST(off_t, 0), SEEK_SET) == CAST(off_t, -1)) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_89_0
crossvul-cpp_data_good_3376_0
/********************************************************************** regexec.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * 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 AUTHOR 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 AUTHOR 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 "regint.h" #define USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #ifdef USE_CRNL_AS_LINE_TERMINATOR #define ONIGENC_IS_MBC_CRNL(enc,p,end) \ (ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \ ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end)) #endif #ifdef USE_CAPTURE_HISTORY static void history_tree_free(OnigCaptureTreeNode* node); static void history_tree_clear(OnigCaptureTreeNode* node) { int i; if (IS_NOT_NULL(node)) { for (i = 0; i < node->num_childs; i++) { if (IS_NOT_NULL(node->childs[i])) { history_tree_free(node->childs[i]); } } for (i = 0; i < node->allocated; i++) { node->childs[i] = (OnigCaptureTreeNode* )0; } node->num_childs = 0; node->beg = ONIG_REGION_NOTPOS; node->end = ONIG_REGION_NOTPOS; node->group = -1; } } static void history_tree_free(OnigCaptureTreeNode* node) { history_tree_clear(node); xfree(node); } static void history_root_free(OnigRegion* r) { if (IS_NOT_NULL(r->history_root)) { history_tree_free(r->history_root); r->history_root = (OnigCaptureTreeNode* )0; } } static OnigCaptureTreeNode* history_node_new(void) { OnigCaptureTreeNode* node; node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode)); CHECK_NULL_RETURN(node); node->childs = (OnigCaptureTreeNode** )0; node->allocated = 0; node->num_childs = 0; node->group = -1; node->beg = ONIG_REGION_NOTPOS; node->end = ONIG_REGION_NOTPOS; return node; } static int history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child) { #define HISTORY_TREE_INIT_ALLOC_SIZE 8 if (parent->num_childs >= parent->allocated) { int n, i; if (IS_NULL(parent->childs)) { n = HISTORY_TREE_INIT_ALLOC_SIZE; parent->childs = (OnigCaptureTreeNode** )xmalloc(sizeof(OnigCaptureTreeNode*) * n); } else { n = parent->allocated * 2; parent->childs = (OnigCaptureTreeNode** )xrealloc(parent->childs, sizeof(OnigCaptureTreeNode*) * n); } CHECK_NULL_RETURN_MEMERR(parent->childs); for (i = parent->allocated; i < n; i++) { parent->childs[i] = (OnigCaptureTreeNode* )0; } parent->allocated = n; } parent->childs[parent->num_childs] = child; parent->num_childs++; return 0; } static OnigCaptureTreeNode* history_tree_clone(OnigCaptureTreeNode* node) { int i; OnigCaptureTreeNode *clone, *child; clone = history_node_new(); CHECK_NULL_RETURN(clone); clone->beg = node->beg; clone->end = node->end; for (i = 0; i < node->num_childs; i++) { child = history_tree_clone(node->childs[i]); if (IS_NULL(child)) { history_tree_free(clone); return (OnigCaptureTreeNode* )0; } history_tree_add_child(clone, child); } return clone; } extern OnigCaptureTreeNode* onig_get_capture_tree(OnigRegion* region) { return region->history_root; } #endif /* USE_CAPTURE_HISTORY */ extern void onig_region_clear(OnigRegion* region) { int i; for (i = 0; i < region->num_regs; i++) { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } #ifdef USE_CAPTURE_HISTORY history_root_free(region); #endif } extern int onig_region_resize(OnigRegion* region, int n) { region->num_regs = n; if (n < ONIG_NREGION) n = ONIG_NREGION; if (region->allocated == 0) { region->beg = (int* )xmalloc(n * sizeof(int)); region->end = (int* )xmalloc(n * sizeof(int)); if (region->beg == 0 || region->end == 0) return ONIGERR_MEMORY; region->allocated = n; } else if (region->allocated < n) { region->beg = (int* )xrealloc(region->beg, n * sizeof(int)); region->end = (int* )xrealloc(region->end, n * sizeof(int)); if (region->beg == 0 || region->end == 0) return ONIGERR_MEMORY; region->allocated = n; } return 0; } static int onig_region_resize_clear(OnigRegion* region, int n) { int r; r = onig_region_resize(region, n); if (r != 0) return r; onig_region_clear(region); return 0; } extern int onig_region_set(OnigRegion* region, int at, int beg, int end) { if (at < 0) return ONIGERR_INVALID_ARGUMENT; if (at >= region->allocated) { int r = onig_region_resize(region, at + 1); if (r < 0) return r; } region->beg[at] = beg; region->end[at] = end; return 0; } extern void onig_region_init(OnigRegion* region) { region->num_regs = 0; region->allocated = 0; region->beg = (int* )0; region->end = (int* )0; region->history_root = (OnigCaptureTreeNode* )0; } extern OnigRegion* onig_region_new(void) { OnigRegion* r; r = (OnigRegion* )xmalloc(sizeof(OnigRegion)); onig_region_init(r); return r; } extern void onig_region_free(OnigRegion* r, int free_self) { if (r) { if (r->allocated > 0) { if (r->beg) xfree(r->beg); if (r->end) xfree(r->end); r->allocated = 0; } #ifdef USE_CAPTURE_HISTORY history_root_free(r); #endif if (free_self) xfree(r); } } extern void onig_region_copy(OnigRegion* to, OnigRegion* from) { #define RREGC_SIZE (sizeof(int) * from->num_regs) int i; if (to == from) return; if (to->allocated == 0) { if (from->num_regs > 0) { to->beg = (int* )xmalloc(RREGC_SIZE); to->end = (int* )xmalloc(RREGC_SIZE); to->allocated = from->num_regs; } } else if (to->allocated < from->num_regs) { to->beg = (int* )xrealloc(to->beg, RREGC_SIZE); to->end = (int* )xrealloc(to->end, RREGC_SIZE); to->allocated = from->num_regs; } for (i = 0; i < from->num_regs; i++) { to->beg[i] = from->beg[i]; to->end[i] = from->end[i]; } to->num_regs = from->num_regs; #ifdef USE_CAPTURE_HISTORY history_root_free(to); if (IS_NOT_NULL(from->history_root)) { to->history_root = history_tree_clone(from->history_root); } #endif } /** stack **/ #define INVALID_STACK_INDEX -1 /* stack type */ /* used by normal-POP */ #define STK_ALT 0x0001 #define STK_LOOK_BEHIND_NOT 0x0002 #define STK_POS_NOT 0x0003 /* handled by normal-POP */ #define STK_MEM_START 0x0100 #define STK_MEM_END 0x8200 #define STK_REPEAT_INC 0x0300 #define STK_STATE_CHECK_MARK 0x1000 /* avoided by normal-POP */ #define STK_NULL_CHECK_START 0x3000 #define STK_NULL_CHECK_END 0x5000 /* for recursive call */ #define STK_MEM_END_MARK 0x8400 #define STK_POS 0x0500 /* used when POP-POS */ #define STK_STOP_BT 0x0600 /* mark for "(?>...)" */ #define STK_REPEAT 0x0700 #define STK_CALL_FRAME 0x0800 #define STK_RETURN 0x0900 #define STK_VOID 0x0a00 /* for fill a blank */ /* stack type check mask */ #define STK_MASK_POP_USED 0x00ff #define STK_MASK_TO_VOID_TARGET 0x10ff #define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\ (msa).stack_p = (void* )0;\ (msa).options = (arg_option);\ (msa).region = (arg_region);\ (msa).start = (arg_start);\ (msa).best_len = ONIG_MISMATCH;\ (msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\ } while(0) #else #define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\ (msa).stack_p = (void* )0;\ (msa).options = (arg_option);\ (msa).region = (arg_region);\ (msa).start = (arg_start);\ (msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\ } while(0) #endif #ifdef USE_COMBINATION_EXPLOSION_CHECK #define STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE 16 #define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) do { \ if ((state_num) > 0 && str_len >= STATE_CHECK_STRING_THRESHOLD_LEN) {\ unsigned int size = (unsigned int )(((str_len) + 1) * (state_num) + 7) >> 3;\ offset = ((offset) * (state_num)) >> 3;\ if (size > 0 && offset < size && size < STATE_CHECK_BUFF_MAX_SIZE) {\ if (size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) \ (msa).state_check_buff = (void* )xmalloc(size);\ else \ (msa).state_check_buff = (void* )xalloca(size);\ xmemset(((char* )((msa).state_check_buff)+(offset)), 0, \ (size_t )(size - (offset))); \ (msa).state_check_buff_size = size;\ }\ else {\ (msa).state_check_buff = (void* )0;\ (msa).state_check_buff_size = 0;\ }\ }\ else {\ (msa).state_check_buff = (void* )0;\ (msa).state_check_buff_size = 0;\ }\ } while(0) #define MATCH_ARG_FREE(msa) do {\ if ((msa).stack_p) xfree((msa).stack_p);\ if ((msa).state_check_buff_size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) { \ if ((msa).state_check_buff) xfree((msa).state_check_buff);\ }\ } while(0) #else #define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) #define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p) #endif #define ALLOCA_PTR_NUM_LIMIT 50 #define STACK_INIT(stack_num) do {\ if (msa->stack_p) {\ is_alloca = 0;\ alloc_base = msa->stack_p;\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + msa->stack_n;\ }\ else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\ is_alloca = 0;\ alloc_base = (char* )xmalloc(sizeof(OnigStackIndex) * msa->ptr_num\ + sizeof(OnigStackType) * (stack_num));\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + (stack_num);\ }\ else {\ is_alloca = 1;\ alloc_base = (char* )xalloca(sizeof(OnigStackIndex) * msa->ptr_num\ + sizeof(OnigStackType) * (stack_num));\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + (stack_num);\ }\ } while(0); #define STACK_SAVE do{\ msa->stack_n = stk_end - stk_base;\ if (is_alloca != 0) {\ size_t size = sizeof(OnigStackIndex) * msa->ptr_num \ + sizeof(OnigStackType) * msa->stack_n;\ msa->stack_p = xmalloc(size);\ xmemcpy(msa->stack_p, alloc_base, size);\ }\ else {\ msa->stack_p = alloc_base;\ };\ } while(0) #define UPDATE_FOR_STACK_REALLOC do{\ repeat_stk = (OnigStackIndex* )alloc_base;\ mem_start_stk = (OnigStackIndex* )(repeat_stk + reg->num_repeat);\ mem_end_stk = mem_start_stk + num_mem;\ mem_start_stk--; /* for index start from 1 */\ mem_end_stk--; /* for index start from 1 */\ } while(0) static unsigned int MatchStackLimitSize = DEFAULT_MATCH_STACK_LIMIT_SIZE; extern unsigned int onig_get_match_stack_limit_size(void) { return MatchStackLimitSize; } extern int onig_set_match_stack_limit_size(unsigned int size) { MatchStackLimitSize = size; return 0; } static int stack_double(int is_alloca, char** arg_alloc_base, OnigStackType** arg_stk_base, OnigStackType** arg_stk_end, OnigStackType** arg_stk, OnigMatchArg* msa) { unsigned int n; int used; size_t size; size_t new_size; char* alloc_base; char* new_alloc_base; OnigStackType *stk_base, *stk_end, *stk; alloc_base = *arg_alloc_base; stk_base = *arg_stk_base; stk_end = *arg_stk_end; stk = *arg_stk; n = stk_end - stk_base; size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n; n *= 2; new_size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n; if (is_alloca != 0) { new_alloc_base = (char* )xmalloc(new_size); if (IS_NULL(new_alloc_base)) { STACK_SAVE; return ONIGERR_MEMORY; } xmemcpy(new_alloc_base, alloc_base, size); } else { if (MatchStackLimitSize != 0 && n > MatchStackLimitSize) { if ((unsigned int )(stk_end - stk_base) == MatchStackLimitSize) return ONIGERR_MATCH_STACK_LIMIT_OVER; else n = MatchStackLimitSize; } new_alloc_base = (char* )xrealloc(alloc_base, new_size); if (IS_NULL(new_alloc_base)) { STACK_SAVE; return ONIGERR_MEMORY; } } alloc_base = new_alloc_base; used = stk - stk_base; *arg_alloc_base = alloc_base; *arg_stk_base = (OnigStackType* )(alloc_base + (sizeof(OnigStackIndex) * msa->ptr_num)); *arg_stk = *arg_stk_base + used; *arg_stk_end = *arg_stk_base + n; return 0; } #define STACK_ENSURE(n) do {\ if (stk_end - stk < (n)) {\ int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk,\ msa);\ if (r != 0) { STACK_SAVE; return r; } \ is_alloca = 0;\ UPDATE_FOR_STACK_REALLOC;\ }\ } while(0) #define STACK_AT(index) (stk_base + (index)) #define GET_STACK_INDEX(stk) ((stk) - stk_base) #define STACK_PUSH_TYPE(stack_type) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ STACK_INC;\ } while(0) #define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0) #ifdef USE_COMBINATION_EXPLOSION_CHECK #define STATE_CHECK_POS(s,snum) \ (((s) - str) * num_comb_exp_check + ((snum) - 1)) #define STATE_CHECK_VAL(v,snum) do {\ if (state_check_buff != NULL) {\ int x = STATE_CHECK_POS(s,snum);\ (v) = state_check_buff[x/8] & (1<<(x%8));\ }\ else (v) = 0;\ } while(0) #define ELSE_IF_STATE_CHECK_MARK(stk) \ else if ((stk)->type == STK_STATE_CHECK_MARK) { \ int x = STATE_CHECK_POS(stk->u.state.pstr, stk->u.state.state_check);\ state_check_buff[x/8] |= (1<<(x%8)); \ } #define STACK_PUSH(stack_type,pat,s,sprev) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ stk->u.state.state_check = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_ENSURED(stack_type,pat) do {\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.state_check = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_ALT_WITH_STATE_CHECK(pat,s,sprev,snum) do {\ STACK_ENSURE(1);\ stk->type = STK_ALT;\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ stk->u.state.state_check = ((state_check_buff != NULL) ? (snum) : 0);\ STACK_INC;\ } while(0) #define STACK_PUSH_STATE_CHECK(s,snum) do {\ if (state_check_buff != NULL) {\ STACK_ENSURE(1);\ stk->type = STK_STATE_CHECK_MARK;\ stk->u.state.pstr = (s);\ stk->u.state.state_check = (snum);\ STACK_INC;\ }\ } while(0) #else /* USE_COMBINATION_EXPLOSION_CHECK */ #define ELSE_IF_STATE_CHECK_MARK(stk) #define STACK_PUSH(stack_type,pat,s,sprev) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ STACK_INC;\ } while(0) #define STACK_PUSH_ENSURED(stack_type,pat) do {\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ STACK_INC;\ } while(0) #endif /* USE_COMBINATION_EXPLOSION_CHECK */ #define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev) #define STACK_PUSH_POS(s,sprev) STACK_PUSH(STK_POS,NULL_UCHARP,s,sprev) #define STACK_PUSH_POS_NOT(pat,s,sprev) STACK_PUSH(STK_POS_NOT,pat,s,sprev) #define STACK_PUSH_STOP_BT STACK_PUSH_TYPE(STK_STOP_BT) #define STACK_PUSH_LOOK_BEHIND_NOT(pat,s,sprev) \ STACK_PUSH(STK_LOOK_BEHIND_NOT,pat,s,sprev) #define STACK_PUSH_REPEAT(id, pat) do {\ STACK_ENSURE(1);\ stk->type = STK_REPEAT;\ stk->u.repeat.num = (id);\ stk->u.repeat.pcode = (pat);\ stk->u.repeat.count = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_REPEAT_INC(sindex) do {\ STACK_ENSURE(1);\ stk->type = STK_REPEAT_INC;\ stk->u.repeat_inc.si = (sindex);\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_START(mnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_START;\ stk->u.mem.num = (mnum);\ stk->u.mem.pstr = (s);\ stk->u.mem.start = mem_start_stk[mnum];\ stk->u.mem.end = mem_end_stk[mnum];\ mem_start_stk[mnum] = GET_STACK_INDEX(stk);\ mem_end_stk[mnum] = INVALID_STACK_INDEX;\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_END(mnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_END;\ stk->u.mem.num = (mnum);\ stk->u.mem.pstr = (s);\ stk->u.mem.start = mem_start_stk[mnum];\ stk->u.mem.end = mem_end_stk[mnum];\ mem_end_stk[mnum] = GET_STACK_INDEX(stk);\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_END_MARK(mnum) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_END_MARK;\ stk->u.mem.num = (mnum);\ STACK_INC;\ } while(0) #define STACK_GET_MEM_START(mnum, k) do {\ int level = 0;\ k = stk;\ while (k > stk_base) {\ k--;\ if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \ && k->u.mem.num == (mnum)) {\ level++;\ }\ else if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\ if (level == 0) break;\ level--;\ }\ }\ } while(0) #define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\ int level = 0;\ while (k < stk) {\ if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\ if (level == 0) (start) = k->u.mem.pstr;\ level++;\ }\ else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\ level--;\ if (level == 0) {\ (end) = k->u.mem.pstr;\ break;\ }\ }\ k++;\ }\ } while(0) #define STACK_PUSH_NULL_CHECK_START(cnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_NULL_CHECK_START;\ stk->u.null_check.num = (cnum);\ stk->u.null_check.pstr = (s);\ STACK_INC;\ } while(0) #define STACK_PUSH_NULL_CHECK_END(cnum) do {\ STACK_ENSURE(1);\ stk->type = STK_NULL_CHECK_END;\ stk->u.null_check.num = (cnum);\ STACK_INC;\ } while(0) #define STACK_PUSH_CALL_FRAME(pat) do {\ STACK_ENSURE(1);\ stk->type = STK_CALL_FRAME;\ stk->u.call_frame.ret_addr = (pat);\ STACK_INC;\ } while(0) #define STACK_PUSH_RETURN do {\ STACK_ENSURE(1);\ stk->type = STK_RETURN;\ STACK_INC;\ } while(0) #ifdef ONIG_DEBUG #define STACK_BASE_CHECK(p, at) \ if ((p) < stk_base) {\ fprintf(stderr, "at %s\n", at);\ goto stack_error;\ } #else #define STACK_BASE_CHECK(p, at) #endif #define STACK_POP_ONE do {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \ } while(0) #define STACK_POP do {\ switch (pop_level) {\ case STACK_POP_LEVEL_FREE:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ case STACK_POP_LEVEL_MEM_START:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP 2"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ default:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP 3"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ }\ } while(0) #define STACK_POP_TIL_POS_NOT do {\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_TIL_POS_NOT"); \ if (stk->type == STK_POS_NOT) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ } while(0) #define STACK_POP_TIL_LOOK_BEHIND_NOT do {\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_TIL_LOOK_BEHIND_NOT"); \ if (stk->type == STK_LOOK_BEHIND_NOT) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ } while(0) #define STACK_POS_END(k) do {\ k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_POS_END"); \ if (IS_TO_VOID_TARGET(k)) {\ k->type = STK_VOID;\ }\ else if (k->type == STK_POS) {\ k->type = STK_VOID;\ break;\ }\ }\ } while(0) #define STACK_STOP_BT_END do {\ OnigStackType *k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_STOP_BT_END"); \ if (IS_TO_VOID_TARGET(k)) {\ k->type = STK_VOID;\ }\ else if (k->type == STK_STOP_BT) {\ k->type = STK_VOID;\ break;\ }\ }\ } while(0) #define STACK_NULL_CHECK(isnull,id,s) do {\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ (isnull) = (k->u.null_check.pstr == (s));\ break;\ }\ }\ }\ } while(0) #define STACK_NULL_CHECK_REC(isnull,id,s) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_REC"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (level == 0) {\ (isnull) = (k->u.null_check.pstr == (s));\ break;\ }\ else level--;\ }\ }\ else if (k->type == STK_NULL_CHECK_END) {\ level++;\ }\ }\ } while(0) #define STACK_NULL_CHECK_MEMST(isnull,id,s,reg) do {\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (k->u.null_check.pstr != (s)) {\ (isnull) = 0;\ break;\ }\ else {\ UChar* endp;\ (isnull) = 1;\ while (k < stk) {\ if (k->type == STK_MEM_START) {\ if (k->u.mem.end == INVALID_STACK_INDEX) {\ (isnull) = 0; break;\ }\ if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\ endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\ else\ endp = (UChar* )k->u.mem.end;\ if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\ (isnull) = 0; break;\ }\ else if (endp != s) {\ (isnull) = -1; /* empty, but position changed */ \ }\ }\ k++;\ }\ break;\ }\ }\ }\ }\ } while(0) #define STACK_NULL_CHECK_MEMST_REC(isnull,id,s,reg) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST_REC"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (level == 0) {\ if (k->u.null_check.pstr != (s)) {\ (isnull) = 0;\ break;\ }\ else {\ UChar* endp;\ (isnull) = 1;\ while (k < stk) {\ if (k->type == STK_MEM_START) {\ if (k->u.mem.end == INVALID_STACK_INDEX) {\ (isnull) = 0; break;\ }\ if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\ endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\ else\ endp = (UChar* )k->u.mem.end;\ if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\ (isnull) = 0; break;\ }\ else if (endp != s) {\ (isnull) = -1; /* empty, but position changed */ \ }\ }\ k++;\ }\ break;\ }\ }\ else {\ level--;\ }\ }\ }\ else if (k->type == STK_NULL_CHECK_END) {\ if (k->u.null_check.num == (id)) level++;\ }\ }\ } while(0) #define STACK_GET_REPEAT(id, k) do {\ int level = 0;\ k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \ if (k->type == STK_REPEAT) {\ if (level == 0) {\ if (k->u.repeat.num == (id)) {\ break;\ }\ }\ }\ else if (k->type == STK_CALL_FRAME) level--;\ else if (k->type == STK_RETURN) level++;\ }\ } while(0) #define STACK_RETURN(addr) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_RETURN"); \ if (k->type == STK_CALL_FRAME) {\ if (level == 0) {\ (addr) = k->u.call_frame.ret_addr;\ break;\ }\ else level--;\ }\ else if (k->type == STK_RETURN)\ level++;\ }\ } while(0) #define STRING_CMP(s1,s2,len) do {\ while (len-- > 0) {\ if (*s1++ != *s2++) goto fail;\ }\ } while(0) #define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\ if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \ goto fail; \ } while(0) static int string_cmp_ic(OnigEncoding enc, int case_fold_flag, UChar* s1, UChar** ps2, int mblen) { UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN]; UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN]; UChar *p1, *p2, *end1, *s2, *end2; int len1, len2; s2 = *ps2; end1 = s1 + mblen; end2 = s2 + mblen; while (s1 < end1) { len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1); len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2); if (len1 != len2) return 0; p1 = buf1; p2 = buf2; while (len1-- > 0) { if (*p1 != *p2) return 0; p1++; p2++; } } *ps2 = s2; return 1; } #define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\ is_fail = 0;\ while (len-- > 0) {\ if (*s1++ != *s2++) {\ is_fail = 1; break;\ }\ }\ } while(0) #define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\ if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \ is_fail = 1; \ else \ is_fail = 0; \ } while(0) #define IS_EMPTY_STR (str == end) #define ON_STR_BEGIN(s) ((s) == str) #define ON_STR_END(s) ((s) == end) #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #define DATA_ENSURE_CHECK1 (s < right_range) #define DATA_ENSURE_CHECK(n) (s + (n) <= right_range) #define DATA_ENSURE(n) if (s + (n) > right_range) goto fail #else #define DATA_ENSURE_CHECK1 (s < end) #define DATA_ENSURE_CHECK(n) (s + (n) <= end) #define DATA_ENSURE(n) if (s + (n) > end) goto fail #endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */ #ifdef USE_CAPTURE_HISTORY static int make_capture_history_tree(OnigCaptureTreeNode* node, OnigStackType** kp, OnigStackType* stk_top, UChar* str, regex_t* reg) { int n, r; OnigCaptureTreeNode* child; OnigStackType* k = *kp; while (k < stk_top) { if (k->type == STK_MEM_START) { n = k->u.mem.num; if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP && BIT_STATUS_AT(reg->capture_history, n) != 0) { child = history_node_new(); CHECK_NULL_RETURN_MEMERR(child); child->group = n; child->beg = (int )(k->u.mem.pstr - str); r = history_tree_add_child(node, child); if (r != 0) return r; *kp = (k + 1); r = make_capture_history_tree(child, kp, stk_top, str, reg); if (r != 0) return r; k = *kp; child->end = (int )(k->u.mem.pstr - str); } } else if (k->type == STK_MEM_END) { if (k->u.mem.num == node->group) { node->end = (int )(k->u.mem.pstr - str); *kp = k; return 0; } } k++; } return 1; /* 1: root node ending. */ } #endif #ifdef USE_BACKREF_WITH_LEVEL static int mem_is_in_memp(int mem, int num, UChar* memp) { int i; MemNumType m; for (i = 0; i < num; i++) { GET_MEMNUM_INC(m, memp); if (mem == (int )m) return 1; } return 0; } static int backref_match_at_nested_level(regex_t* reg , OnigStackType* top, OnigStackType* stk_base , int ignore_case, int case_fold_flag , int nest, int mem_num, UChar* memp, UChar** s, const UChar* send) { UChar *ss, *p, *pstart, *pend = NULL_UCHARP; int level; OnigStackType* k; level = 0; k = top; k--; while (k >= stk_base) { if (k->type == STK_CALL_FRAME) { level--; } else if (k->type == STK_RETURN) { level++; } else if (level == nest) { if (k->type == STK_MEM_START) { if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) { pstart = k->u.mem.pstr; if (pend != NULL_UCHARP) { if (pend - pstart > send - *s) return 0; /* or goto next_mem; */ p = pstart; ss = *s; if (ignore_case != 0) { if (string_cmp_ic(reg->enc, case_fold_flag, pstart, &ss, (int )(pend - pstart)) == 0) return 0; /* or goto next_mem; */ } else { while (p < pend) { if (*p++ != *ss++) return 0; /* or goto next_mem; */ } } *s = ss; return 1; } } } else if (k->type == STK_MEM_END) { if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) { pend = k->u.mem.pstr; } } } k--; } return 0; } #endif /* USE_BACKREF_WITH_LEVEL */ #ifdef ONIG_DEBUG_STATISTICS #define USE_TIMEOFDAY #ifdef USE_TIMEOFDAY #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif static struct timeval ts, te; #define GETTIME(t) gettimeofday(&(t), (struct timezone* )0) #define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \ (((te).tv_sec - (ts).tv_sec)*1000000)) #else #ifdef HAVE_SYS_TIMES_H #include <sys/times.h> #endif static struct tms ts, te; #define GETTIME(t) times(&(t)) #define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime) #endif static int OpCounter[256]; static int OpPrevCounter[256]; static unsigned long OpTime[256]; static int OpCurr = OP_FINISH; static int OpPrevTarget = OP_FAIL; static int MaxStackDepth = 0; #define MOP_IN(opcode) do {\ if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\ OpCurr = opcode;\ OpCounter[opcode]++;\ GETTIME(ts);\ } while(0) #define MOP_OUT do {\ GETTIME(te);\ OpTime[OpCurr] += TIMEDIFF(te, ts);\ } while(0) extern void onig_statistics_init(void) { int i; for (i = 0; i < 256; i++) { OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0; } MaxStackDepth = 0; } extern int onig_print_statistics(FILE* f) { int r; int i; r = fprintf(f, " count prev time\n"); if (r < 0) return -1; for (i = 0; OnigOpInfo[i].opcode >= 0; i++) { r = fprintf(f, "%8d: %8d: %10ld: %s\n", OpCounter[i], OpPrevCounter[i], OpTime[i], OnigOpInfo[i].name); if (r < 0) return -1; } r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth); if (r < 0) return -1; return 0; } #define STACK_INC do {\ stk++;\ if (stk - stk_base > MaxStackDepth) \ MaxStackDepth = stk - stk_base;\ } while(0) #else #define STACK_INC stk++ #define MOP_IN(opcode) #define MOP_OUT #endif /* matching region of POSIX API */ typedef int regoff_t; typedef struct { regoff_t rm_so; regoff_t rm_eo; } posix_regmatch_t; /* match data(str - end) from position (sstart). */ /* if sstart == str then set sprev to NULL. */ static int match_at(regex_t* reg, const UChar* str, const UChar* end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar* right_range, #endif const UChar* sstart, UChar* sprev, OnigMatchArg* msa) { static UChar FinishCode[] = { OP_FINISH }; int i, n, num_mem, best_len, pop_level; LengthType tlen, tlen2; MemNumType mem; RelAddrType addr; UChar *s, *q, *sbegin; int is_alloca; char *alloc_base; OnigStackType *stk_base, *stk, *stk_end; OnigStackType *stkp; /* used as any purpose. */ OnigStackIndex si; OnigStackIndex *repeat_stk; OnigStackIndex *mem_start_stk, *mem_end_stk; #ifdef USE_COMBINATION_EXPLOSION_CHECK int scv; unsigned char* state_check_buff = msa->state_check_buff; int num_comb_exp_check = reg->num_comb_exp_check; #endif UChar *p = reg->p; OnigOptionType option = reg->options; OnigEncoding encode = reg->enc; OnigCaseFoldType case_fold_flag = reg->case_fold_flag; //n = reg->num_repeat + reg->num_mem * 2; pop_level = reg->stack_pop_level; num_mem = reg->num_mem; STACK_INIT(INIT_MATCH_STACK_SIZE); UPDATE_FOR_STACK_REALLOC; for (i = 1; i <= num_mem; i++) { mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX; } #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n", (int )str, (int )end, (int )sstart, (int )sprev); fprintf(stderr, "size: %d, start offset: %d\n", (int )(end - str), (int )(sstart - str)); #endif STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */ best_len = ONIG_MISMATCH; s = (UChar* )sstart; while (1) { #ifdef ONIG_DEBUG_MATCH { UChar *q, *bp, buf[50]; int len; fprintf(stderr, "%4d> \"", (int )(s - str)); bp = buf; for (i = 0, q = s; i < 7 && q < end; i++) { len = enclen(encode, q); while (len-- > 0) *bp++ = *q++; } if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; } else { xmemcpy(bp, "\"", 1); bp += 1; } *bp = 0; fputs((char* )buf, stderr); for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr); onig_print_compiled_byte_code(stderr, p, NULL, encode); fprintf(stderr, "\n"); } #endif sbegin = s; switch (*p++) { case OP_END: MOP_IN(OP_END); n = s - sstart; if (n > best_len) { OnigRegion* region; #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(option)) { if (n > msa->best_len) { msa->best_len = n; msa->best_s = (UChar* )sstart; } else goto end_best_len; } #endif best_len = n; region = msa->region; if (region) { #ifdef USE_POSIX_API_REGION_OPTION if (IS_POSIX_REGION(msa->options)) { posix_regmatch_t* rmt = (posix_regmatch_t* )region; rmt[0].rm_so = sstart - str; rmt[0].rm_eo = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str; rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS; } } } else { #endif /* USE_POSIX_API_REGION_OPTION */ region->beg[0] = sstart - str; region->end[0] = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str; region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } } #ifdef USE_CAPTURE_HISTORY if (reg->capture_history != 0) { int r; OnigCaptureTreeNode* node; if (IS_NULL(region->history_root)) { region->history_root = node = history_node_new(); CHECK_NULL_RETURN_MEMERR(node); } else { node = region->history_root; history_tree_clear(node); } node->group = 0; node->beg = sstart - str; node->end = s - str; stkp = stk_base; r = make_capture_history_tree(region->history_root, &stkp, stk, (UChar* )str, reg); if (r < 0) { best_len = r; /* error code */ goto finish; } } #endif /* USE_CAPTURE_HISTORY */ #ifdef USE_POSIX_API_REGION_OPTION } /* else IS_POSIX_REGION() */ #endif } /* if (region) */ } /* n > best_len */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE end_best_len: #endif MOP_OUT; if (IS_FIND_CONDITION(option)) { if (IS_FIND_NOT_EMPTY(option) && s == sstart) { best_len = ONIG_MISMATCH; goto fail; /* for retry */ } if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) { goto fail; /* for retry */ } } /* default behavior: return first-matching result. */ goto finish; break; case OP_EXACT1: MOP_IN(OP_EXACT1); DATA_ENSURE(1); if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC); { int len; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) { goto fail; } p++; q++; } } MOP_OUT; break; case OP_EXACT2: MOP_IN(OP_EXACT2); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT3: MOP_IN(OP_EXACT3); DATA_ENSURE(3); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT4: MOP_IN(OP_EXACT4); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT5: MOP_IN(OP_EXACT5); DATA_ENSURE(5); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACTN: MOP_IN(OP_EXACTN); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen); while (tlen-- > 0) { if (*p++ != *s++) goto fail; } sprev = s - 1; MOP_OUT; continue; break; case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC); { int len; UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; GET_LENGTH_INC(tlen, p); endp = p + tlen; while (p < endp) { sprev = s; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) goto fail; p++; q++; } } } MOP_OUT; continue; break; case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3); DATA_ENSURE(6); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 2); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 2; MOP_OUT; continue; break; case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 3); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 3; MOP_OUT; continue; break; case OP_EXACTMBN: MOP_IN(OP_EXACTMBN); GET_LENGTH_INC(tlen, p); /* mb-len */ GET_LENGTH_INC(tlen2, p); /* string len */ tlen2 *= tlen; DATA_ENSURE(tlen2); while (tlen2-- > 0) { if (*p != *s) goto fail; p++; s++; } sprev = s - tlen; MOP_OUT; continue; break; case OP_CCLASS: MOP_IN(OP_CCLASS); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */ MOP_OUT; break; case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB); if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail; cclass_mb: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len; DATA_ENSURE(1); mb_len = enclen(encode, s); DATA_ENSURE(mb_len); ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (! onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (! onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; MOP_OUT; break; case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb; } else { if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); MOP_OUT; break; case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) { s++; GET_LENGTH_INC(tlen, p); p += tlen; goto cc_mb_not_success; } cclass_mb_not: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len = enclen(encode, s); if (! DATA_ENSURE_CHECK(mb_len)) { DATA_ENSURE(1); s = (UChar* )end; p += tlen; goto cc_mb_not_success; } ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; cc_mb_not_success: MOP_OUT; break; case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb_not; } else { if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE); { OnigCodePoint code; void *node; int mb_len; UChar *ss; DATA_ENSURE(1); GET_POINTER_INC(node, p); mb_len = enclen(encode, s); ss = s; s += mb_len; DATA_ENSURE(0); code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail; } MOP_OUT; break; case OP_ANYCHAR: MOP_IN(OP_ANYCHAR); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; s += n; MOP_OUT; break; case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); s += n; MOP_OUT; break; case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } p++; MOP_OUT; break; case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } p++; MOP_OUT; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_STATE_CHECK_ANYCHAR_ML_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_WORD: MOP_IN(OP_WORD); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_NOT_WORD: MOP_IN(OP_NOT_WORD); DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND); if (ON_STR_BEGIN(s)) { DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (! ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) == ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND); if (ON_STR_BEGIN(s)) { if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) != ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; #ifdef USE_WORD_BEGIN_END case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN); if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) { if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) { MOP_OUT; continue; } } goto fail; break; case OP_WORD_END: MOP_IN(OP_WORD_END); if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) { if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) { MOP_OUT; continue; } } goto fail; break; #endif case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF); if (! ON_STR_BEGIN(s)) goto fail; MOP_OUT; continue; break; case OP_END_BUF: MOP_IN(OP_END_BUF); if (! ON_STR_END(s)) goto fail; MOP_OUT; continue; break; case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE); if (ON_STR_BEGIN(s)) { if (IS_NOTBOL(msa->options)) goto fail; MOP_OUT; continue; } else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) { MOP_OUT; continue; } goto fail; break; case OP_END_LINE: MOP_IN(OP_END_LINE); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { MOP_OUT; continue; } #endif goto fail; break; case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) && ON_STR_END(s + enclen(encode, s))) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { UChar* ss = s + enclen(encode, s); ss += enclen(encode, ss); if (ON_STR_END(ss)) { MOP_OUT; continue; } } #endif goto fail; break; case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION); if (s != msa->start) goto fail; MOP_OUT; continue; break; case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_START(mem, s); MOP_OUT; continue; break; case OP_MEMORY_START: MOP_IN(OP_MEMORY_START); GET_MEMNUM_INC(mem, p); mem_start_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_END(mem, s); MOP_OUT; continue; break; case OP_MEMORY_END: MOP_IN(OP_MEMORY_END); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; #ifdef USE_SUBEXP_CALL case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC); GET_MEMNUM_INC(mem, p); STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */ STACK_PUSH_MEM_END(mem, s); mem_start_stk[mem] = GET_STACK_INDEX(stkp); MOP_OUT; continue; break; case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); STACK_GET_MEM_START(mem, stkp); if (BIT_STATUS_AT(reg->bt_mem_start, mem)) mem_start_stk[mem] = GET_STACK_INDEX(stkp); else mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr); STACK_PUSH_MEM_END_MARK(mem); MOP_OUT; continue; break; #endif case OP_BACKREF1: MOP_IN(OP_BACKREF1); mem = 1; goto backref; break; case OP_BACKREF2: MOP_IN(OP_BACKREF2); mem = 2; goto backref; break; case OP_BACKREFN: MOP_IN(OP_BACKREFN); GET_MEMNUM_INC(mem, p); backref: { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP(pstart, s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC); GET_MEMNUM_INC(mem, p); { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP_IC(case_fold_flag, pstart, &s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE(pstart, swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; #ifdef USE_BACKREF_WITH_LEVEL case OP_BACKREF_WITH_LEVEL: { int len; OnigOptionType ic; LengthType level; GET_OPTION_INC(ic, p); GET_LENGTH_INC(level, p); GET_LENGTH_INC(tlen, p); sprev = s; if (backref_match_at_nested_level(reg, stk, stk_base, ic , case_fold_flag, (int )level, (int )tlen, p, &s, end)) { while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * tlen); } else goto fail; MOP_OUT; continue; } break; #endif #if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */ case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH); GET_OPTION_INC(option, p); STACK_PUSH_ALT(p, s, sprev); p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL; MOP_OUT; continue; break; case OP_SET_OPTION: MOP_IN(OP_SET_OPTION); GET_OPTION_INC(option, p); MOP_OUT; continue; break; #endif case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START); GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_PUSH_NULL_CHECK_START(mem, s); MOP_OUT; continue; break; case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK(isnull, mem, s); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n", (int )mem, (int )s); #endif null_check_found: /* empty loop founded, skip next instruction */ switch (*p++) { case OP_JUMP: case OP_PUSH: p += SIZE_RELADDR; break; case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: p += SIZE_MEMNUM; break; default: goto unexpected_bytecode_error; break; } } } MOP_OUT; continue; break; #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK_MEMST(isnull, mem, s, reg); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } } MOP_OUT; continue; break; #endif #ifdef USE_SUBEXP_CALL case OP_NULL_CHECK_END_MEMST_PUSH: MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg); #else STACK_NULL_CHECK_REC(isnull, mem, s); #endif if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } else { STACK_PUSH_NULL_CHECK_END(mem); } } MOP_OUT; continue; break; #endif case OP_JUMP: MOP_IN(OP_JUMP); GET_RELADDR_INC(addr, p); p += addr; MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_PUSH: MOP_IN(OP_PUSH); GET_RELADDR_INC(addr, p); STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; GET_RELADDR_INC(addr, p); STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); MOP_OUT; continue; break; case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP); GET_STATE_CHECK_NUM_INC(mem, p); GET_RELADDR_INC(addr, p); STATE_CHECK_VAL(scv, mem); if (scv) { p += addr; } else { STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); } MOP_OUT; continue; break; case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_STATE_CHECK(s, mem); MOP_OUT; continue; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_POP: MOP_IN(OP_POP); STACK_POP_ONE; MOP_OUT; continue; break; case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1); GET_RELADDR_INC(addr, p); if (*p == *s && DATA_ENSURE_CHECK1) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p += (addr + 1); MOP_OUT; continue; break; case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT); GET_RELADDR_INC(addr, p); if (*p == *s) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p++; MOP_OUT; continue; break; case OP_REPEAT: MOP_IN(OP_REPEAT); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + addr, s, sprev); } } MOP_OUT; continue; break; case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p, s, sprev); p += addr; } } MOP_OUT; continue; break; case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc: stkp->u.repeat.count++; if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) { /* end of repeat. Nothing to do. */ } else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { STACK_PUSH_ALT(p, s, sprev); p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */ } else { p = stkp->u.repeat.pcode; } STACK_PUSH_REPEAT_INC(si); MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc; break; case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc_ng: stkp->u.repeat.count++; if (stkp->u.repeat.count < reg->repeat_range[mem].upper) { if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { UChar* pcode = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); STACK_PUSH_ALT(pcode, s, sprev); } else { p = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); } } else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) { STACK_PUSH_REPEAT_INC(si); } MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc_ng; break; case OP_PUSH_POS: MOP_IN(OP_PUSH_POS); STACK_PUSH_POS(s, sprev); MOP_OUT; continue; break; case OP_POP_POS: MOP_IN(OP_POP_POS); { STACK_POS_END(stkp); s = stkp->u.state.pstr; sprev = stkp->u.state.pstr_prev; } MOP_OUT; continue; break; case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT); GET_RELADDR_INC(addr, p); STACK_PUSH_POS_NOT(p + addr, s, sprev); MOP_OUT; continue; break; case OP_FAIL_POS: MOP_IN(OP_FAIL_POS); STACK_POP_TIL_POS_NOT; goto fail; break; case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT); STACK_PUSH_STOP_BT; MOP_OUT; continue; break; case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT); STACK_STOP_BT_END; MOP_OUT; continue; break; case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND); GET_LENGTH_INC(tlen, p); s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(s)) goto fail; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); MOP_OUT; continue; break; case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT); GET_RELADDR_INC(addr, p); GET_LENGTH_INC(tlen, p); q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(q)) { /* too short case -> success. ex. /(?<!XXX)a/.match("a") If you want to change to fail, replace following line. */ p += addr; /* goto fail; */ } else { STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev); s = q; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); } MOP_OUT; continue; break; case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT); STACK_POP_TIL_LOOK_BEHIND_NOT; goto fail; break; #ifdef USE_SUBEXP_CALL case OP_CALL: MOP_IN(OP_CALL); GET_ABSADDR_INC(addr, p); STACK_PUSH_CALL_FRAME(p); p = reg->p + addr; MOP_OUT; continue; break; case OP_RETURN: MOP_IN(OP_RETURN); STACK_RETURN(p); STACK_PUSH_RETURN; MOP_OUT; continue; break; #endif case OP_FINISH: goto finish; break; fail: MOP_OUT; /* fall */ case OP_FAIL: MOP_IN(OP_FAIL); STACK_POP; p = stk->u.state.pcode; s = stk->u.state.pstr; sprev = stk->u.state.pstr_prev; #ifdef USE_COMBINATION_EXPLOSION_CHECK if (stk->u.state.state_check != 0) { stk->type = STK_STATE_CHECK_MARK; stk++; } #endif MOP_OUT; continue; break; default: goto bytecode_error; } /* end of switch */ sprev = sbegin; } /* end of while(1) */ finish: STACK_SAVE; return best_len; #ifdef ONIG_DEBUG stack_error: STACK_SAVE; return ONIGERR_STACK_BUG; #endif bytecode_error: STACK_SAVE; return ONIGERR_UNDEFINED_BYTECODE; unexpected_bytecode_error: STACK_SAVE; return ONIGERR_UNEXPECTED_BYTECODE; } static UChar* slow_search(OnigEncoding enc, UChar* target, UChar* target_end, const UChar* text, const UChar* text_end, UChar* text_range) { UChar *t, *p, *s, *end; end = (UChar* )text_end; end -= target_end - target - 1; if (end > text_range) end = text_range; s = (UChar* )text; while (s < end) { if (*s == *target) { p = s + 1; t = target + 1; while (t < target_end) { if (*t != *p++) break; t++; } if (t == target_end) return s; } s += enclen(enc, s); } return (UChar* )NULL; } static int str_lower_case_match(OnigEncoding enc, int case_fold_flag, const UChar* t, const UChar* tend, const UChar* p, const UChar* end) { int lowlen; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; while (t < tend) { lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf); q = lowbuf; while (lowlen > 0) { if (*t++ != *q++) return 0; lowlen--; } } return 1; } static UChar* slow_search_ic(OnigEncoding enc, int case_fold_flag, UChar* target, UChar* target_end, const UChar* text, const UChar* text_end, UChar* text_range) { UChar *s, *end; end = (UChar* )text_end; end -= target_end - target - 1; if (end > text_range) end = text_range; s = (UChar* )text; while (s < end) { if (str_lower_case_match(enc, case_fold_flag, target, target_end, s, text_end)) return s; s += enclen(enc, s); } return (UChar* )NULL; } static UChar* slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { UChar *t, *p, *s; s = (UChar* )text_end; s -= (target_end - target); if (s > text_start) s = (UChar* )text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s); while (s >= text) { if (*s == *target) { p = s + 1; t = target + 1; while (t < target_end) { if (*t != *p++) break; t++; } if (t == target_end) return s; } s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } static UChar* slow_search_backward_ic(OnigEncoding enc, int case_fold_flag, UChar* target, UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { UChar *s; s = (UChar* )text_end; s -= (target_end - target); if (s > text_start) s = (UChar* )text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s); while (s >= text) { if (str_lower_case_match(enc, case_fold_flag, target, target_end, s, text_end)) return s; s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } static UChar* bm_search_notrev(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* text_end, const UChar* text_range) { const UChar *s, *se, *t, *p, *end; const UChar *tail; int skip, tlen1; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "bm_search_notrev: text: %d, text_end: %d, text_range: %d\n", (int )text, (int )text_end, (int )text_range); #endif tail = target_end - 1; tlen1 = tail - target; end = text_range; if (end + tlen1 > text_end) end = text_end - tlen1; s = text; if (IS_NULL(reg->int_map)) { while (s < end) { p = se = s + tlen1; t = tail; while (*p == *t) { if (t == target) return (UChar* )s; p--; t--; } skip = reg->map[*se]; t = s; do { s += enclen(reg->enc, s); } while ((s - t) < skip && s < end); } } else { while (s < end) { p = se = s + tlen1; t = tail; while (*p == *t) { if (t == target) return (UChar* )s; p--; t--; } skip = reg->int_map[*se]; t = s; do { s += enclen(reg->enc, s); } while ((s - t) < skip && s < end); } } return (UChar* )NULL; } static UChar* bm_search(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* text_end, const UChar* text_range) { const UChar *s, *t, *p, *end; const UChar *tail; end = text_range + (target_end - target) - 1; if (end > text_end) end = text_end; tail = target_end - 1; s = text + (target_end - target) - 1; if (IS_NULL(reg->int_map)) { while (s < end) { p = s; t = tail; while (*p == *t) { if (t == target) return (UChar* )p; p--; t--; } s += reg->map[*s]; } } else { /* see int_map[] */ while (s < end) { p = s; t = tail; while (*p == *t) { if (t == target) return (UChar* )p; p--; t--; } s += reg->int_map[*s]; } } return (UChar* )NULL; } #ifdef USE_INT_MAP_BACKWARD static int set_bm_backward_skip(UChar* s, UChar* end, OnigEncoding enc ARG_UNUSED, int** skip) { int i, len; if (IS_NULL(*skip)) { *skip = (int* )xmalloc(sizeof(int) * ONIG_CHAR_TABLE_SIZE); if (IS_NULL(*skip)) return ONIGERR_MEMORY; } len = end - s; for (i = 0; i < ONIG_CHAR_TABLE_SIZE; i++) (*skip)[i] = len; for (i = len - 1; i > 0; i--) (*skip)[s[i]] = i; return 0; } static UChar* bm_search_backward(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { const UChar *s, *t, *p; s = text_end - (target_end - target); if (text_start < s) s = text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s); while (s >= text) { p = s; t = target; while (t < target_end && *p == *t) { p++; t++; } if (t == target_end) return (UChar* )s; s -= reg->int_map_backward[*s]; s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s); } return (UChar* )NULL; } #endif static UChar* map_search(OnigEncoding enc, UChar map[], const UChar* text, const UChar* text_range) { const UChar *s = text; while (s < text_range) { if (map[*s]) return (UChar* )s; s += enclen(enc, s); } return (UChar* )NULL; } static UChar* map_search_backward(OnigEncoding enc, UChar map[], const UChar* text, const UChar* adjust_text, const UChar* text_start) { const UChar *s = text_start; while (s >= text) { if (map[*s]) return (UChar* )s; s = onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } extern int onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at, OnigRegion* region, OnigOptionType option) { int r; UChar *prev; OnigMatchArg msa; MATCH_ARG_INIT(msa, reg, option, region, at); #ifdef USE_COMBINATION_EXPLOSION_CHECK { int offset = at - str; STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check); } #endif if (region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { r = onig_region_resize_clear(region, reg->num_mem + 1); } else r = 0; if (r == 0) { if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) { r = ONIGERR_INVALID_WIDE_CHAR_VALUE; goto end; } } prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at); r = match_at(reg, str, end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE end, #endif at, prev, &msa); } end: MATCH_ARG_FREE(msa); return r; } static int forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n", (int )str, (int )end, (int )s, (int )range); #endif p = s; if (reg->dmin > 0) { if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dmin; } else { UChar *q = p + reg->dmin; if (q >= end) return 0; /* fail */ while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM: p = bm_search(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if (p - reg->dmin < s) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dmax == 0) { *low = p; if (low_prev) { if (*low > s) *low_prev = onigenc_get_prev_char_head(reg->enc, s, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } } else { if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; if (*low > s) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s, *low, (const UChar** )low_prev); if (low_prev && IS_NULL(*low_prev)) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : s), *low); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } /* no needs to adjust *high, *high is used as range check only */ *high = p - reg->dmin; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n", (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax); #endif return 1; /* success */ } return 0; /* fail */ } #define BM_BACKWARD_SEARCH_LENGTH_THRESHOLD 100 static int backward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, const UChar* range, UChar* adjrange, UChar** low, UChar** high) { UChar *p; range += reg->dmin; p = s; retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: exact_method: p = slow_search_backward(reg->enc, reg->exact, reg->exact_end, range, adjrange, end, p); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_backward_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, range, adjrange, end, p); break; case ONIG_OPTIMIZE_EXACT_BM: case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: #ifdef USE_INT_MAP_BACKWARD if (IS_NULL(reg->int_map_backward)) { int r; if (s - range < BM_BACKWARD_SEARCH_LENGTH_THRESHOLD) goto exact_method; r = set_bm_backward_skip(reg->exact, reg->exact_end, reg->enc, &(reg->int_map_backward)); if (r) return r; } p = bm_search_backward(reg, reg->exact, reg->exact_end, range, adjrange, end, p); #else goto exact_method; #endif break; case ONIG_OPTIMIZE_MAP: p = map_search_backward(reg->enc, reg->map, range, adjrange, p); break; } if (p) { if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, str, p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(prev)) goto fail; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) { p = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(p)) goto fail; goto retry; } break; } } /* no needs to adjust *high, *high is used as range check only */ if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; *high = p - reg->dmin; *high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high); } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search_range: low: %d, high: %d\n", (int )(*low - str), (int )(*high - str)); #endif return 1; /* success */ } fail: #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search_range: fail.\n"); #endif return 0; /* fail */ } extern int onig_search(regex_t* reg, const UChar* str, const UChar* end, const UChar* start, const UChar* range, OnigRegion* region, OnigOptionType option) { int r; UChar *s, *prev; OnigMatchArg msa; const UChar *orig_start = start; #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar *orig_range = range; #endif #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search (entry point): str: %d, end: %d, start: %d, range: %d\n", (int )str, (int )(end - str), (int )(start - str), (int )(range - str)); #endif if (region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { r = onig_region_resize_clear(region, reg->num_mem + 1); if (r) goto finish_no_msa; } if (start > end || start < str) goto mismatch_no_msa; if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) { r = ONIGERR_INVALID_WIDE_CHAR_VALUE; goto finish_no_msa; } } #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_AND_RETURN_CHECK(upper_range) \ r = match_at(reg, str, end, (upper_range), s, prev, &msa); \ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ if (! IS_FIND_LONGEST(reg->options)) {\ goto match;\ }\ }\ else goto finish; /* error */ \ } #else #define MATCH_AND_RETURN_CHECK(upper_range) \ r = match_at(reg, str, end, (upper_range), s, prev, &msa); \ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ goto match;\ }\ else goto finish; /* error */ \ } #endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */ #else #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_AND_RETURN_CHECK(none) \ r = match_at(reg, str, end, s, prev, &msa);\ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ if (! IS_FIND_LONGEST(reg->options)) {\ goto match;\ }\ }\ else goto finish; /* error */ \ } #else #define MATCH_AND_RETURN_CHECK(none) \ r = match_at(reg, str, end, s, prev, &msa);\ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ goto match;\ }\ else goto finish; /* error */ \ } #endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */ #endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */ /* anchor optimize: resume search range */ if (reg->anchor != 0 && str < end) { UChar *min_semi_end, *max_semi_end; if (reg->anchor & ANCHOR_BEGIN_POSITION) { /* search start-position only */ begin_position: if (range > start) range = start + 1; else range = start; } else if (reg->anchor & ANCHOR_BEGIN_BUF) { /* search str-position only */ if (range > start) { if (start != str) goto mismatch_no_msa; range = str + 1; } else { if (range <= str) { start = str; range = str; } else goto mismatch_no_msa; } } else if (reg->anchor & ANCHOR_END_BUF) { min_semi_end = max_semi_end = (UChar* )end; end_buf: if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin) goto mismatch_no_msa; if (range > start) { if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) { start = min_semi_end - reg->anchor_dmax; if (start < end) start = onigenc_get_right_adjust_char_head(reg->enc, str, start); } if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) { range = max_semi_end - reg->anchor_dmin + 1; } if (start > range) goto mismatch_no_msa; /* If start == range, match with empty at end. Backward search is used. */ } else { if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) { range = min_semi_end - reg->anchor_dmax; } if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) { start = max_semi_end - reg->anchor_dmin; start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start); } if (range > start) goto mismatch_no_msa; } } else if (reg->anchor & ANCHOR_SEMI_END_BUF) { UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1); max_semi_end = (UChar* )end; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) { min_semi_end = pre_end; #ifdef USE_CRNL_AS_LINE_TERMINATOR pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1); if (IS_NOT_NULL(pre_end) && ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) { min_semi_end = pre_end; } #endif if (min_semi_end > str && start <= min_semi_end) { goto end_buf; } } else { min_semi_end = (UChar* )end; goto end_buf; } } else if ((reg->anchor & ANCHOR_ANYCHAR_STAR_ML)) { goto begin_position; } } else if (str == end) { /* empty string */ static const UChar* address_for_empty_string = (UChar* )""; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search: empty string.\n"); #endif if (reg->threshold_len == 0) { start = end = str = address_for_empty_string; s = (UChar* )start; prev = (UChar* )NULL; MATCH_ARG_INIT(msa, reg, option, region, start); #ifdef USE_COMBINATION_EXPLOSION_CHECK msa.state_check_buff = (void* )0; msa.state_check_buff_size = 0; /* NO NEED, for valgrind */ #endif MATCH_AND_RETURN_CHECK(end); goto mismatch; } goto mismatch_no_msa; } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n", (int )(end - str), (int )(start - str), (int )(range - str)); #endif MATCH_ARG_INIT(msa, reg, option, region, orig_start); #ifdef USE_COMBINATION_EXPLOSION_CHECK { int offset = (MIN(start, range) - str); STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check); } #endif s = (UChar* )start; if (range > start) { /* forward search */ if (s > str) prev = onigenc_get_prev_char_head(reg->enc, str, s); else prev = (UChar* )NULL; if (reg->optimize != ONIG_OPTIMIZE_NONE) { UChar *sch_range, *low, *high, *low_prev; sch_range = (UChar* )range; if (reg->dmax != 0) { if (reg->dmax == ONIG_INFINITE_DISTANCE) sch_range = (UChar* )end; else { sch_range += reg->dmax; if (sch_range > end) sch_range = (UChar* )end; } } if ((end - start) < reg->threshold_len) goto mismatch; if (reg->dmax != ONIG_INFINITE_DISTANCE) { do { if (! forward_search_range(reg, str, end, s, sch_range, &low, &high, &low_prev)) goto mismatch; if (s < low) { s = low; prev = low_prev; } while (s <= high) { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); } } while (s < range); goto mismatch; } else { /* check only. */ if (! forward_search_range(reg, str, end, s, sch_range, &low, &high, (UChar** )NULL)) goto mismatch; if ((reg->anchor & ANCHOR_ANYCHAR_STAR) != 0) { do { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); if ((reg->anchor & (ANCHOR_LOOK_BEHIND | ANCHOR_PREC_READ_NOT)) == 0) { while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) { prev = s; s += enclen(reg->enc, s); } } } while (s < range); goto mismatch; } } } do { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); } while (s < range); if (s == range) { /* because empty match with /$/. */ MATCH_AND_RETURN_CHECK(orig_range); } } else { /* backward search */ #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE if (orig_start < end) orig_start += enclen(reg->enc, orig_start); /* is upper range */ #endif if (reg->optimize != ONIG_OPTIMIZE_NONE) { UChar *low, *high, *adjrange, *sch_start; if (range < end) adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range); else adjrange = (UChar* )end; if (reg->dmax != ONIG_INFINITE_DISTANCE && (end - range) >= reg->threshold_len) { do { sch_start = s + reg->dmax; if (sch_start > end) sch_start = (UChar* )end; if (backward_search_range(reg, str, end, sch_start, range, adjrange, &low, &high) <= 0) goto mismatch; if (s > high) s = high; while (s >= low) { prev = onigenc_get_prev_char_head(reg->enc, str, s); MATCH_AND_RETURN_CHECK(orig_start); s = prev; } } while (s >= range); goto mismatch; } else { /* check only. */ if ((end - range) < reg->threshold_len) goto mismatch; sch_start = s; if (reg->dmax != 0) { if (reg->dmax == ONIG_INFINITE_DISTANCE) sch_start = (UChar* )end; else { sch_start += reg->dmax; if (sch_start > end) sch_start = (UChar* )end; else sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, start, sch_start); } } if (backward_search_range(reg, str, end, sch_start, range, adjrange, &low, &high) <= 0) goto mismatch; } } do { prev = onigenc_get_prev_char_head(reg->enc, str, s); MATCH_AND_RETURN_CHECK(orig_start); s = prev; } while (s >= range); } mismatch: #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(reg->options)) { if (msa.best_len >= 0) { s = msa.best_s; goto match; } } #endif r = ONIG_MISMATCH; finish: MATCH_ARG_FREE(msa); /* If result is mismatch and no FIND_NOT_EMPTY option, then the region is not set in match_at(). */ if (IS_FIND_NOT_EMPTY(reg->options) && region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { onig_region_clear(region); } #ifdef ONIG_DEBUG if (r != ONIG_MISMATCH) fprintf(stderr, "onig_search: error %d\n", r); #endif return r; mismatch_no_msa: r = ONIG_MISMATCH; finish_no_msa: #ifdef ONIG_DEBUG if (r != ONIG_MISMATCH) fprintf(stderr, "onig_search: error %d\n", r); #endif return r; match: MATCH_ARG_FREE(msa); return s - str; } extern int onig_scan(regex_t* reg, const UChar* str, const UChar* end, OnigRegion* region, OnigOptionType option, int (*scan_callback)(int, int, OnigRegion*, void*), void* callback_arg) { int r; int n; int rs; const UChar* start; if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING); } n = 0; start = str; while (1) { r = onig_search(reg, str, end, start, end, region, option); if (r >= 0) { rs = scan_callback(n, r, region, callback_arg); n++; if (rs != 0) return rs; if (region->end[0] == start - str) start++; else start = str + region->end[0]; if (start > end) break; } else if (r == ONIG_MISMATCH) { break; } else { /* error */ return r; } } return n; } extern OnigEncoding onig_get_encoding(regex_t* reg) { return reg->enc; } extern OnigOptionType onig_get_options(regex_t* reg) { return reg->options; } extern OnigCaseFoldType onig_get_case_fold_flag(regex_t* reg) { return reg->case_fold_flag; } extern OnigSyntaxType* onig_get_syntax(regex_t* reg) { return reg->syntax; } extern int onig_number_of_captures(regex_t* reg) { return reg->num_mem; } extern int onig_number_of_capture_histories(regex_t* reg) { #ifdef USE_CAPTURE_HISTORY int i, n; n = 0; for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) { if (BIT_STATUS_AT(reg->capture_history, i) != 0) n++; } return n; #else return 0; #endif } extern void onig_copy_encoding(OnigEncoding to, OnigEncoding from) { *to = *from; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3376_0
crossvul-cpp_data_bad_925_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % 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/property.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* Forward declarations. */ static ThresholdMap *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image,const size_t width, % const size_t height,const double bias,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o bias: the mean bias. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ 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); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_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,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property,exception); return(BilevelImage(image,QuantumRange*threshold/100.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImage method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % % o exception: return any errors or warnings in this structure. % % Aside: You can get the same results as operator using LevelImages() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); /* Bilevel threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < GetPixelInfoChannel(&threshold,channel)) q[i]=(Quantum) 0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImage method is: % % MagickBooleanType ClampImage(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 MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception) { #define ClampImageTag "Clamp/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) ClampPixel(q->red); q->green=(double) ClampPixel(q->green); q->blue=(double) ClampPixel(q->blue); q->alpha=(double) ClampPixel(q->alpha); q++; } return(SyncImage(image,exception)); } /* Clamp image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampPixel((MagickRealType) q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() loads and searches one or more threshold map files for the % map matching the given name or alias. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); } #endif return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename, const char *map_id,ExceptionInfo *exception) { char *p; const char *attribute, *content; double value; register ssize_t i; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); map=(ThresholdMap *) NULL; thresholds=NewXMLTree(xml,exception); if (thresholds == (XMLTreeInfo *) NULL) return(map); for (threshold=GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { attribute=GetXMLTreeAttribute(threshold,"map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); for (i=0; i < (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { const char *alias, *content, *map; XMLTreeInfo *description, *threshold, *thresholds; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); threshold=GetXMLTreeChild(thresholds,"threshold"); for ( ; threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { map=GetXMLTreeAttribute(threshold,"map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias=GetXMLTreeAttribute(threshold,"alias"); description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; char token[MagickPathExtent]; const char *p; double levels[CompositePixelChannel]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; ThresholdMap *map; 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); if (threshold_map == (const char *) NULL) return(MagickTrue); p=(char *) threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MagickPathExtent-1)) break; token[p-threshold_map]=(*p); p++; } token[p-threshold_map]='\0'; map=GetThresholdMap(token,exception); if (map == (ThresholdMap *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } for (i=0; i < MaxPixelChannels; i++) levels[i]=2.0; p=strchr((char *) threshold_map,','); if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0)) { GetNextToken(p,&p,MagickPathExtent,token); for (i=0; (i < MaxPixelChannels); i++) levels[i]=StringToDouble(token,(char **) NULL); for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); levels[i]=StringToDouble(token,(char **) NULL); } } for (i=0; i < MaxPixelChannels; i++) if (fabs(levels[i]) >= 1) levels[i]-=1.0; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; ssize_t n; n=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t level, threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(levels[n]) < MagickEpsilon) { n++; continue; } threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1)); level=threshold/(map->divisor-1); threshold-=level*(map->divisor-1); q[i]=ClampToQuantum((double) (level+(threshold >= map->levels[(x % map->width)+map->width*(y % map->height)]))* QuantumRange/levels[n]); n++; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImage method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon,ExceptionInfo *exception) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red), epsilon); q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green), epsilon); q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue), epsilon); q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha), epsilon); q++; } return(SyncImage(image,exception)); } /* Perceptible image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PerceptibleThreshold(q[i],epsilon); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImage(Image *image, % const char *thresholds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low,high: Specify the high and low thresholds. These values range from % 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const double min_threshold, const double max_threshold,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&threshold); /* Random threshold image. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] < min_threshold) threshold=min_threshold; else if ((double) q[i] > max_threshold) threshold=max_threshold; else threshold=(double) (QuantumRange* GetPseudoRandomValue(random_info[id])); q[i]=(double) q[i] <= threshold ? 0 : QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n g e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RangeThresholdImage() applies soft and hard thresholding. % % The format of the RangeThresholdImage method is: % % MagickBooleanType RangeThresholdImage(Image *image, % const double low_black,const double low_white,const double high_white, % const double high_black,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low_black: Define the minimum black threshold value. % % o low_white: Define the minimum white threshold value. % % o high_white: Define the maximum white threshold value. % % o high_black: Define the maximum black threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RangeThresholdImage(Image *image, const double low_black,const double low_white,const double high_white, const double high_black,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Range threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < low_black) q[i]=0; else if ((pixel >= low_black) && (pixel < low_white)) q[i]=ClampToQuantum(QuantumRange* PerceptibleReciprocal(low_white-low_black)*(pixel-low_black)); else if ((pixel >= low_white) && (pixel <= high_white)) q[i]=QuantumRange; else if ((pixel > high_white) && (pixel <= high_black)) q[i]=ClampToQuantum(QuantumRange*PerceptibleReciprocal( high_black-high_white)*(high_black-pixel)); else if (pixel > high_black) q[i]=0; else q[i]=0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel > GetPixelInfoChannel(&threshold,channel)) q[i]=QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_925_0
crossvul-cpp_data_bad_5307_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V IIIII FFFFF FFFFF % % V V I F F % % V V I FFF FFF % % V V I F F % % V IIIII F F % % % % % % Read/Write Khoros Visualization 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/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/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" /* Forward declarations. */ static MagickBooleanType WriteVIFFImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s V I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsVIFF() returns MagickTrue if the image format type, identified by the % magick string, is VIFF. % % The format of the IsVIFF method is: % % MagickBooleanType IsVIFF(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 IsVIFF(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\253\001",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadVIFFImage() reads a Khoros Visualization 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 ReadVIFFImage method is: % % Image *ReadVIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadVIFFImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); 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-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) 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++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; 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++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); 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; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterVIFFImage() adds properties for the VIFF 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 RegisterVIFFImage method is: % % size_t RegisterVIFFImage(void) % */ ModuleExport size_t RegisterVIFFImage(void) { MagickInfo *entry; entry=SetMagickInfo("VIFF"); entry->decoder=(DecodeImageHandler *) ReadVIFFImage; entry->encoder=(EncodeImageHandler *) WriteVIFFImage; entry->magick=(IsImageFormatHandler *) IsVIFF; entry->description=ConstantString("Khoros Visualization image"); entry->module=ConstantString("VIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("XV"); entry->decoder=(DecodeImageHandler *) ReadVIFFImage; entry->encoder=(EncodeImageHandler *) WriteVIFFImage; entry->description=ConstantString("Khoros Visualization image"); entry->module=ConstantString("VIFF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterVIFFImage() removes format registrations made by the % VIFF module from the list of supported formats. % % The format of the UnregisterVIFFImage method is: % % UnregisterVIFFImage(void) % */ ModuleExport void UnregisterVIFFImage(void) { (void) UnregisterMagickInfo("VIFF"); (void) UnregisterMagickInfo("XV"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteVIFFImage() writes an image to a file in the VIFF image format. % % The format of the WriteVIFFImage method is: % % MagickBooleanType WriteVIFFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteVIFFImage(const ImageInfo *image_info, Image *image) { #define VFF_CM_genericRGB 15 #define VFF_CM_NONE 0 #define VFF_DEP_IEEEORDER 0x2 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 typedef struct _ViffInfo { char identifier, file_type, release, version, machine_dependency, reserve[3], comment[512]; size_t rows, columns, subrows; int x_offset, y_offset; unsigned int x_bits_per_pixel, y_bits_per_pixel, location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels, packets; MemoryInfo *pixel_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register ssize_t i; register unsigned char *q; ssize_t y; unsigned char *pixels; ViffInfo viff_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) ResetMagickMemory(&viff_info,0,sizeof(ViffInfo)); scene=0; do { /* Initialize VIFF image structure. */ (void) TransformImageColorspace(image,sRGBColorspace); DisableMSCWarning(4310) viff_info.identifier=(char) 0xab; RestoreMSCWarning viff_info.file_type=1; viff_info.release=1; viff_info.version=3; viff_info.machine_dependency=VFF_DEP_IEEEORDER; /* IEEE byte ordering */ *viff_info.comment='\0'; value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) (void) CopyMagickString(viff_info.comment,value,MagickMin(strlen(value), 511)+1); viff_info.rows=image->columns; viff_info.columns=image->rows; viff_info.subrows=0; viff_info.x_offset=(~0); viff_info.y_offset=(~0); viff_info.x_bits_per_pixel=0; viff_info.y_bits_per_pixel=0; viff_info.location_type=VFF_LOC_IMPLICIT; viff_info.location_dimension=0; viff_info.number_of_images=1; viff_info.data_encode_scheme=VFF_DES_RAW; viff_info.map_scheme=VFF_MS_NONE; viff_info.map_storage_type=VFF_MAPTYP_NONE; viff_info.map_rows=0; viff_info.map_columns=0; viff_info.map_subrows=0; viff_info.map_enable=1; /* no colormap */ viff_info.maps_per_cycle=0; number_pixels=(MagickSizeType) image->columns*image->rows; if (image->storage_class == DirectClass) { /* Full color VIFF raster. */ viff_info.number_data_bands=image->matte ? 4U : 3U; viff_info.color_space_model=VFF_CM_genericRGB; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=viff_info.number_data_bands*number_pixels; } else { viff_info.number_data_bands=1; viff_info.color_space_model=VFF_CM_NONE; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=number_pixels; if (SetImageGray(image,&image->exception) == MagickFalse) { /* Colormapped VIFF raster. */ viff_info.map_scheme=VFF_MS_ONEPERBAND; viff_info.map_storage_type=VFF_MAPTYP_1_BYTE; viff_info.map_rows=3; viff_info.map_columns=(unsigned int) image->colors; } else if (image->colors <= 2) { /* Monochrome VIFF raster. */ viff_info.data_storage_type=VFF_TYP_BIT; packets=((image->columns+7) >> 3)*image->rows; } } /* Write VIFF image header (pad to 1024 bytes). */ (void) WriteBlob(image,sizeof(viff_info.identifier),(unsigned char *) &viff_info.identifier); (void) WriteBlob(image,sizeof(viff_info.file_type),(unsigned char *) &viff_info.file_type); (void) WriteBlob(image,sizeof(viff_info.release),(unsigned char *) &viff_info.release); (void) WriteBlob(image,sizeof(viff_info.version),(unsigned char *) &viff_info.version); (void) WriteBlob(image,sizeof(viff_info.machine_dependency), (unsigned char *) &viff_info.machine_dependency); (void) WriteBlob(image,sizeof(viff_info.reserve),(unsigned char *) viff_info.reserve); (void) WriteBlob(image,512,(unsigned char *) viff_info.comment); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_offset); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_offset); viff_info.x_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_bits_per_pixel); viff_info.y_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_bits_per_pixel); (void) WriteBlobMSBLong(image,viff_info.location_type); (void) WriteBlobMSBLong(image,viff_info.location_dimension); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_of_images); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_data_bands); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_encode_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_enable); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.maps_per_cycle); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.color_space_model); for (i=0; i < 420; i++) (void) WriteBlobByte(image,'\0'); /* Convert MIFF to VIFF raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) packets,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); q=pixels; if (image->storage_class == DirectClass) { /* Convert DirectClass packet to VIFF RGB pixel. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q=ScaleQuantumToChar(GetPixelRed(p)); *(q+number_pixels)=ScaleQuantumToChar(GetPixelGreen(p)); *(q+number_pixels*2)=ScaleQuantumToChar(GetPixelBlue(p)); if (image->matte != MagickFalse) *(q+number_pixels*3)=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; q++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (SetImageGray(image,&image->exception) == MagickFalse) { unsigned char *viff_colormap; /* Dump colormap to file. */ viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 3*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=viff_colormap; for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].red); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].green); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].blue); (void) WriteBlob(image,3*image->colors,viff_colormap); viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); /* Convert PseudoClass packet to VIFF colormapped pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->colors <= 2) { ssize_t x, y; register unsigned char bit, byte; /* Convert PseudoClass image to a VIFF monochrome image. */ (void) SetImageType(image,BilevelType); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } } if (bit != 0) *q++=byte >> (8-bit); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else { /* Convert PseudoClass packet to VIFF grayscale pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) ClampToQuantum(GetPixelLuma(image,p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } (void) WriteBlob(image,(size_t) packets,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5307_0
crossvul-cpp_data_bad_3197_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % 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/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(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 IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded pixel % packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t extent) { register const unsigned char *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; while (((size_t) (p-compressed_pixels) < length) && ((size_t) (q-pixels) < extent)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte>. */ if (((size_t) (p-compressed_pixels) >= length)) break; count=(*p++); if (count > 0) { if (((size_t) (p-compressed_pixels) >= length)) break; byte=(*p++); } while ((count >= 0) && ((size_t) (q-pixels) < extent)) { *q++=byte; count--; } } } return(((size_t) (q-pixels) == extent) ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN 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 ReadSUNImage method is: % % Image *ReadSUNImage(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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, pixels_length, quantum; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth != 1) && (sun_info.depth != 8) && (sun_info.depth != 24) && (sun_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum(sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: break; } image->matte=sun_info.depth == 32 ? MagickTrue : MagickFalse; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (sun_info.length == 0) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) (image->columns*image->rows); if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8UL*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length, sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } quantum=sun_info.depth == 1 ? 15 : 7; bytes_per_line+=quantum; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum)) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } bytes_per_line>>=4; if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } pixels_length=height*bytes_per_line; sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length, sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } ResetMagickMemory(sun_pixels,0,pixels_length*sizeof(*sun_pixels)); if (sun_info.type == RT_ENCODED) { status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } else { if (sun_info.length > pixels_length) { sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); } (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) 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-7); x+=8) { for (bit=7; bit >= 0; bit--) SetPixelIndex(indexes+x+7-bit,((*p) & (0x01 << bit) ? 0x00 : 0x01)); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) SetPixelIndex(indexes+x+7-bit,(*p) & (0x01 << bit) ? 0x00 : 0x01); p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { 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++) { SetPixelIndex(indexes+x,ConstrainColormapIndex(image,*p)); p++; } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->matte != MagickFalse) bytes_per_pixel++; 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++) { if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (sun_info.type == RT_STANDARD) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); } else { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); } if (image->colors != 0) { SetPixelRed(q,image->colormap[(ssize_t) GetPixelRed(q)].red); SetPixelGreen(q,image->colormap[(ssize_t) GetPixelGreen(q)].green); SetPixelBlue(q,image->colormap[(ssize_t) GetPixelBlue(q)].blue); } q++; } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->matte ? 32U : 24U; sun_info.length=(unsigned int) ((image->matte ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (SetImageMonochrome(image,&image->exception)) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->matte != MagickFalse) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ 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; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) *q++=ScaleQuantumToChar(GetPixelAlpha(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); p++; } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (SetImageMonochrome(image,&image->exception)) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p++; } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].red)); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].blue)); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(indexes+x)); p++; } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3197_0
crossvul-cpp_data_good_139_0
/* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */ #if 0 http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set #endif #include <string.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> static RDESContext desctx; typedef struct _cpu_const_tag { const char *const key; ut8 type; ut32 value; ut8 size; } CPU_CONST; #define CPU_CONST_NONE 0 #define CPU_CONST_PARAM 1 #define CPU_CONST_REG 2 typedef struct _cpu_model_tag { const char *const model; int pc; char *inherit; struct _cpu_model_tag *inherit_cpu_p; CPU_CONST *consts[10]; } CPU_MODEL; typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu); typedef struct _opcodes_tag_ { const char *const name; int mask; int selector; inst_handler_t handler; int cycles; int size; ut64 type; } OPCODE_DESC; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu); #define CPU_MODEL_DECL(model, pc, consts) \ { \ model, \ pc, \ consts \ } #define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits)))) #define CPU_PC_MASK(cpu) MASK((cpu)->pc) #define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0)) #define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu) #define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T } #define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK } #define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu) #define INST_INVALID { *fail = 1; return; } #define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } } #define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__) #define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s)) // Following IO definitions are valid for: // ATmega8 // ATmega88 CPU_CONST cpu_reg_common[] = { { "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) }, { "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) }, { "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) }, { "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_common[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_xmega128a4u[] = { { "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_5_bits[] = { { "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_7_bits[] = { { "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_MODEL cpu_models[] = { { .model = "ATmega640", .pc = 15, .consts = { cpu_reg_common, cpu_memsize_m640_m1280m_m1281_m2560_m2561, cpu_pagesize_7_bits, NULL }, }, { .model = "ATxmega128a4u", .pc = 17, .consts = { cpu_reg_common, cpu_memsize_xmega128a4u, cpu_pagesize_7_bits, NULL } }, { .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega88", .pc = 8, .inherit = "ATmega8" }, // CPU_MODEL_DECL ("ATmega168", 13, 512, 512), // last model is the default AVR - ATmega8 forever! { .model = "ATmega8", .pc = 13, .consts = { cpu_reg_common, cpu_memsize_common, cpu_pagesize_5_bits, NULL } }, }; static CPU_MODEL *get_cpu_model(char *model); static CPU_MODEL *__get_cpu_model_recursive(char *model) { CPU_MODEL *cpu = NULL; for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) { if (!strcasecmp (model, cpu->model)) { break; } } // fix inheritance tree if (cpu->inherit && !cpu->inherit_cpu_p) { cpu->inherit_cpu_p = get_cpu_model (cpu->inherit); if (!cpu->inherit_cpu_p) { eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit); } } return cpu; } static CPU_MODEL *get_cpu_model(char *model) { static CPU_MODEL *cpu = NULL; // cached value? if (cpu && !strcasecmp (model, cpu->model)) return cpu; // do the real search cpu = __get_cpu_model_recursive (model); return cpu; } static ut32 const_get_value(CPU_CONST *c) { return c ? MASK (c->size * 8) & c->value : 0; } static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem->key; citem++) { if (!strcmp (c, citem->key) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_name (cpu->inherit_cpu_p, type, c); eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c); return NULL; } static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) { char *t = r_anal_esil_pop (esil); if (!t || !r_anal_esil_get_parm (esil, t, v)) { free (t); return false; } free (t); return true; } static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem && citem->key; citem++) { if (citem->value == (MASK (citem->size * 8) & v) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_value (cpu->inherit_cpu_p, type, v); return NULL; } static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) { RStrBuf *r = r_strbuf_new (""); CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port); if (c != NULL) { r_strbuf_set (r, c->key); if (write) { r_strbuf_append (r, ",="); } } else { r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : ""); } return r; } static void __generic_bitop_flags(RAnalOp *op) { ESIL_A ("0,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S } static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) { if (ireg) { // preincrement index register if (prepostdec < 0) { ESIL_A ("1,%c,-,%c,=,", ireg, ireg); } // set register index address ESIL_A ("%c,", ireg); // add offset if (offset != 0) { ESIL_A ("%d,+,", offset); } } else { ESIL_A ("%d,", offset); } if (use_ramp) { ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd'); } // set SRAM base address ESIL_A ("_%s,+,", mem); // read/write from SRAM ESIL_A ("%s[1],", st ? "=" : ""); // postincrement index register if (ireg && prepostdec > 0) { ESIL_A ("1,%c,+,%c,=,", ireg, ireg); } } static void __generic_pop(RAnalOp *op, int sz) { if (sz > 1) { ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1) ESIL_A ("[%d],", sz); // read value ESIL_A ("%d,sp,+=,", sz); // sp += item_size } else { ESIL_A ("1,sp,+=," // increment stack pointer "sp,_ram,+,[1],"); // load SRAM[sp] } } static void __generic_push(RAnalOp *op, int sz) { ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp) if (sz > 1) { ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz' } ESIL_A ("=[%d],", sz); // store value in stack ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer } static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) { __generic_add_update_flags(op, 'r', d, 'r', r); } static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&," "%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N if (carry) ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z else ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&," "%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) { __generic_sub_update_flags(op, 'r', d, 'r', r, carry); } static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) { __generic_sub_update_flags(op, 'r', d, 'k', k, carry); } INST_HANDLER (adc) { // ADC Rd, Rr // ROL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (add) { // ADD Rd, Rr // LSL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr // FLAGS: ESIL_A ("r%d,0x80,&,!," // V "0,RPICK,0x8000,&,!,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!,!," // C "0,RPICK,0x8000,&,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (and) { // AND Rd, Rr // TST Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (andi) { // ANDI Rd, K // CBR Rd, K (= ANDI Rd, 1-K) if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f); op->val = k; ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (asr) { // ASR Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7 ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (bclr) { // BCLR s // CLC // CLH // CLI // CLN // CLR // CLS // CLT // CLV // CLZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s); } INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } INST_HANDLER (brbx) { // BRBC s, k // BRBS s, k // BRBC/S 0: BRCC BRCS // BRSH BRLO // BRBC/S 1: BREQ BRNE // BRBC/S 2: BRPL BRMI // BRBC/S 3: BRVC BRVS // BRBC/S 4: BRGE BRLT // BRBC/S 5: BRHC BRHS // BRBC/S 6: BRTC BRTS // BRBC/S 7: BRID BRIE int s = buf[0] & 0x7; op->jump = op->addr + ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2)) | (buf[1] & 0x2 ? ~((int) 0x7f) : 0)) + 2; op->fail = op->addr + op->size; op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s) ESIL_A (buf[1] & 0x4 ? "!," // BRBC => branch if cleared : "!,!,"); // BRBS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (break) { // BREAK ESIL_A ("BREAK"); } INST_HANDLER (bset) { // BSET s // SEC // SEH // SEI // SEN // SER // SES // SET // SEV // SEZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("%d,1,<<,sreg,|=,", s); } INST_HANDLER (bst) { // BST Rd, b if (len < 2) { return; } ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r buf[0] & 0x7); // b } INST_HANDLER (call) { // CALL k if (len < 4) { return; } op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->fail = op->addr + op->size; op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // AT*mega optimizes one cycle } ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (cbi) { // CBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->family = R_ANAL_OP_FAMILY_IO; op->type2 = 1; op->val = a; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (com) { // COM Rd int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd // FLAGS: ESIL_A ("0,cf,=,"); // C __generic_bitop_flags (op); // ...rest... } INST_HANDLER (cp) { // CP Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) } INST_HANDLER (cpc) { // CPC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) } INST_HANDLER (cpi) { // CPI Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); ESIL_A ("%d,r%d,-,", k, d); // Rd - k __generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry) } INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (dec) { // DEC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("-1,r%d,+,", d); // --Rd // FLAGS: ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (des) { // DES k if (desctx.round < 16) { //DES op->type = R_ANAL_OP_TYPE_CRYPTO; op->cycles = 1; //redo this r_strbuf_setf (&op->esil, "%d,des", desctx.round); } } INST_HANDLER (eijmp) { // EIJMP ut64 z, eind; // read z and eind for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = ((eind << 16) + z) << 1; // jump ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,"); // cycles op->cycles = 2; } INST_HANDLER (eicall) { // EICALL // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard EIJMP INST_CALL (eijmp); // fix cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4; } INST_HANDLER (elpm) { // ELPM // ELPM Rd // ELPM Rd, Z+ int d = ((buf[1] & 0xfe) == 0x90) ? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd : 0; // R0 ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z ESIL_A ("r%d,=,", d); // Rd = [1] if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) { ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z) } } INST_HANDLER (eor) { // EOR Rd, Rr // CLR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (fmul) { // FMUL Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmuls) { // FMULS Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmulsu) { // FMULSU Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d", r); // unsigned Rr ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (ijmp) { // IJMP k ut64 z; // read z for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = z << 1; op->cycles = 2; ESIL_A ("1,z,<<,pc,=,"); // jump! } INST_HANDLER (icall) { // ICALL k // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard IJMP INST_CALL (ijmp); // fix cycles if (!STR_BEGINS (cpu->model, "ATxmega")) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } INST_HANDLER (inc) { // INC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("1,r%d,+,", d); // ++Rd // FLAGS: ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (jmp) { // JMP k op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->cycles = 3; ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (lac) { // LAC Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (las) { // LAS Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,|,", d); // 0: (Z) | Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (lat) { // LAT Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (ld) { // LD Rd, X // LD Rd, X+ // LD Rd, -X // read memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post incremented : 0, // no increment 0, // offset always 0 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[0] & 0x3) == 0 ? 2 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z // LD Rd, Y+ LD Rd, Z+ // LD Rd, -Y LD Rd, -Z // LD Rd, Y+q LD Rd, Z+q // calculate offset (this value only has sense in some opcodes, // but we are optimistic and we calculate it always) int offset = (buf[1] & 0x20) | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7); // read memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? offset : 0, // offset or not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[1] & 0x10) == 0 ? (!offset ? 1 : 3) // LDD : (buf[0] & 0x3) == 0 ? 1 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldi) { // LDI Rd, K int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4); int d = ((buf[0] >> 4) & 0xf) + 16; op->val = k; ESIL_A ("0x%x,r%d,=,", k, d); } INST_HANDLER (lds) { // LDS Rd, k if (len < 4) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; // load value from RAMPD:k __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } #if 0 INST_HANDLER (lds16) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x30) | ((buf[1] << 4) & 0x40) | (~(buf[1] << 4) & 0x80); op->ptr = k; // load value from @k __generic_ld_st (op, "ram", 0, 0, 0, k, 0); ESIL_A ("r%d,=,", d); } #endif INST_HANDLER (lpm) { // LPM // LPM Rd, Z // LPM Rd, Z+ ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]); // read program memory __generic_ld_st ( op, "prog", 'z', // index register Y/Z 1, // use RAMP* registers (ins & 0xfe0f) == 0x9005 ? 1 // post incremented : 0, // no increment 0, // not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", (ins == 0x95c8) ? 0 // LPM (r0) : ((buf[0] >> 4) & 0xf) // LPM Rd | ((buf[1] & 0x1) << 4)); } INST_HANDLER (lsr) { // LSR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1) ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (mov) { // MOV Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,=,", r, d); } INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr int d = (buf[0] & 0xf0) >> 3; int r = (buf[0] & 0x0f) << 1; ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1); } INST_HANDLER (mul) { // MUL Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (muls) { // MULS Rd, Rr int d = (buf[0] >> 4 & 0x0f) + 16; int r = (buf[0] & 0x0f) + 16; ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (mulsu) { // MULSU Rd, Rr int d = (buf[0] >> 4 & 0x07) + 16; int r = (buf[0] & 0x07) + 16; ESIL_A ("r%d,", r); // unsigned Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (neg) { // NEG Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd) ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N ESIL_A ("DUP,!,zf,=,"); // Z ESIL_A ("DUP,!,!,cf,=,"); // C ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (nop) { // NOP ESIL_A (",,"); } INST_HANDLER (or) { // OR Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (ori) { // ORI Rd, K // SBR Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); op->val = k; ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (out) { // OUT A, Rr int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_dst = __generic_io_dest (a, 1, cpu); op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst)); r_strbuf_free (io_dst); } INST_HANDLER (pop) { // POP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); __generic_pop (op, 1); ESIL_A ("r%d,=,", d); // store in Rd } INST_HANDLER (push) { // PUSH Rr int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("r%d,", r); // load Rr __generic_push (op, 1); // push it into stack // cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 1 // AT*mega optimizes one cycle : 2; } INST_HANDLER (rcall) { // RCALL k // target address op->jump = (op->addr + (((((buf[1] & 0xf) << 8) | buf[0]) << 1) | (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0))) + 2) & CPU_PC_MASK (cpu); op->fail = op->addr + op->size; // esil ESIL_A ("pc,"); // esil already points to next // instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! // cycles if (!strncasecmp (cpu->model, "ATtiny", 6)) { op->cycles = 4; // ATtiny is always slow } else { // PC size decides required runtime! op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // ATxmega optimizes one cycle } } } INST_HANDLER (ret) { // RET op->eob = true; // esil __generic_pop (op, CPU_PC_SIZE (cpu)); ESIL_A ("pc,=,"); // jump! // cycles if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit op->cycles++; // (i.e. a 22-bit bus), add one extra cycle } } INST_HANDLER (reti) { // RETI //XXX: There are not privileged instructions in ATMEL/AVR op->family = R_ANAL_OP_FAMILY_PRIV; // first perform a standard 'ret' INST_CALL (ret); // RETI: The I-bit is cleared by hardware after an interrupt // has occurred, and is set by the RETI instruction to enable // subsequent interrupts ESIL_A ("1,if,=,"); } INST_HANDLER (rjmp) { // RJMP k op->jump = (op->addr #ifdef _MSC_VER #pragma message ("anal_avr.c: WARNING: Probably broken on windows") + ((((( buf[1] & 0xf) << 9) | (buf[0] << 1))) | (buf[1] & 0x8 ? ~(0x1fff) : 0)) #else + ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1))) | (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0)) #endif + 2) & CPU_PC_MASK (cpu); ESIL_A ("%"PFMT64d",pc,=,", op->jump); } INST_HANDLER (ror) { // ROR Rd int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7) ESIL_A ("r%d,1,&,cf,=,", d); // C ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (sbc) { // SBC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C) __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbci) { // SBCI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sub) { // SUB Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k) __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (subi) { // SUBI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbi) { // SBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (sbix) { // SBIC A, b // SBIS A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RAnalOp next_op; RStrBuf *io_port; op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBIC => branch if 0 : "!,!,"); // SBIS => branch if 1 ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp r_strbuf_free (io_port); } INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr) ESIL_A ("r%d,0x80,&,!,!," // V "0,RPICK,0x8000,&,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!," // C "0,RPICK,0x8000,&,!,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (sbrx) { // SBRC Rr, b // SBRS Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op = {0}; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (sleep) { // SLEEP ESIL_A ("BREAK"); } INST_HANDLER (spm) { // SPM Z+ ut64 spmcsr; // read SPM Control Register (SPMCR) r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL); // clear SPMCSR ESIL_A ("0x7c,spmcsr,&=,"); // decide action depending on the old value of SPMCSR switch (spmcsr & 0x7f) { case 0x03: // PAGE ERASE // invoke SPM_CLEAR_PAGE (erases target page writing // the 0xff value ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_ERASE,"); // do magic break; case 0x01: // FILL TEMPORARY BUFFER ESIL_A ("r1,r0,"); // push data ESIL_A ("z,"); // push target address ESIL_A ("SPM_PAGE_FILL,"); // do magic break; case 0x05: // WRITE PAGE ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_WRITE,"); // do magic break; default: eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n", (unsigned int) spmcsr); } op->cycles = 1; // This is truly false. Datasheets do not publish how // many cycles this instruction uses in all its // operation modes and I am pretty sure that this value // can vary substantially from one MCU type to another. // So... one cycle is fine. } INST_HANDLER (st) { // ST X, Rr // ST X+, Rr // ST -X, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post increment : 0, // no increment 0, // offset always 0 1); // store operation (st) // // cycles // op->cycles = buf[0] & 0x3 == 0 // ? 2 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (std) { // ST Y, Rr ST Z, Rr // ST Y+, Rr ST Z+, Rr // ST -Y, Rr ST -Z, Rr // ST Y+q, Rr ST Z+q, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? (buf[1] & 0x20) // offset | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7) : 0, // no offset 1); // load operation (!st) // // cycles // op->cycles = // buf[1] & 0x1 == 0 // ? !(offset ? 1 : 3) // LDD // : buf[0] & 0x3 == 0 // ? 1 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (swap) { // SWAP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf ESIL_A ("|,", d); // S[0] | S[1] ESIL_A ("r%d,=,", d); // Rd = result } OPCODE_DESC opcodes[] = { // op mask select cycles size type INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ... INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+ INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+ INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+ INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+ INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A //INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr INST_LAST }; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) { CPU_MODEL *cpu; ut64 offset; // init op if (!op) { return 2; } // select cpu info cpu = get_cpu_model (anal->cpu); // set memory layout registers if (anal->esil) { offset = 0; r_anal_esil_reg_write (anal->esil, "_prog", offset); offset += (1 << cpu->pc); r_anal_esil_reg_write (anal->esil, "_io", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start")); r_anal_esil_reg_write (anal->esil, "_sram", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size")); r_anal_esil_reg_write (anal->esil, "_eeprom", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size")); r_anal_esil_reg_write (anal->esil, "_page", offset); } // process opcode avr_op_analyze (anal, op, addr, buf, len, cpu); return op->size; } static int avr_custom_des (RAnalEsil *esil) { ut64 key, encrypt, text,des_round; ut32 key_lo, key_hi, buf_lo, buf_hi; if (!esil || !esil->anal || !esil->anal->reg) { return false; } if (!__esil_pop_argument (esil, &des_round)) { return false; } r_anal_esil_reg_read (esil, "hf", &encrypt, NULL); r_anal_esil_reg_read (esil, "deskey", &key, NULL); r_anal_esil_reg_read (esil, "text", &text, NULL); key_lo = key & UT32_MAX; key_hi = key >> 32; buf_lo = text & UT32_MAX; buf_hi = text >> 32; if (des_round != desctx.round) { desctx.round = des_round; } if (!desctx.round) { int i; //generating all round keys r_des_permute_key (&key_lo, &key_hi); for (i = 0; i < 16; i++) { r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi); } r_des_permute_block0 (&buf_lo, &buf_hi); } if (encrypt) { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]); } else { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]); } if (desctx.round == 15) { r_des_permute_block1 (&buf_hi, &buf_lo); desctx.round = 0; } else { desctx.round++; } r_anal_esil_reg_write (esil, "text", text); return true; } // ESIL operation SPM_PAGE_ERASE static int avr_custom_spm_page_erase(RAnalEsil *esil) { CPU_MODEL *cpu; ut8 c; ut64 addr, page_size_bits, i; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument(esil, &addr)) { return false; } // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align base address to page_size_bits addr &= ~(MASK (page_size_bits)); // perform erase //eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); c = 0xff; for (i = 0; i < (1ULL << page_size_bits); i++) { r_anal_esil_mem_write ( esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1); } return true; } // ESIL operation SPM_PAGE_FILL static int avr_custom_spm_page_fill(RAnalEsil *esil) { CPU_MODEL *cpu; ut64 addr, page_size_bits, i; ut8 r0, r1; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address, r0, r1 if (!__esil_pop_argument(esil, &addr)) { return false; } if (!__esil_pop_argument (esil, &i)) { return false; } r0 = i; if (!__esil_pop_argument (esil, &i)) { return false; } r1 = i; // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align and crop base address addr &= (MASK (page_size_bits) ^ 1); // perform write to temporary page //eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr); r_anal_esil_mem_write (esil, addr++, &r0, 1); r_anal_esil_mem_write (esil, addr++, &r1, 1); return true; } // ESIL operation SPM_PAGE_WRITE static int avr_custom_spm_page_write(RAnalEsil *esil) { CPU_MODEL *cpu; char *t = NULL; ut64 addr, page_size_bits, tmp_page; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument (esil, &addr)) { return false; } // get details about current MCU and fix input address and base address // of the internal temporary page cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL); // align base address to page_size_bits addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu)); // perform writing //eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); if (!(t = malloc (1 << page_size_bits))) { eprintf ("Cannot alloc a buffer for copying the temporary page.\n"); return false; } r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits); r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits); return true; } static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) { CPU_MODEL *cpu; if (!esil || !esil->anal) { return 0; } // select cpu info cpu = get_cpu_model (esil->anal->cpu); // crop registers and force certain values if (!strcmp (name, "pc")) { *val &= CPU_PC_MASK (cpu); } else if (!strcmp (name, "pcl")) { if (cpu->pc < 8) { *val &= MASK (8); } } else if (!strcmp (name, "pch")) { *val = cpu->pc > 8 ? *val & MASK (cpu->pc - 8) : 0; } return 0; } static int esil_avr_init(RAnalEsil *esil) { if (!esil) { return false; } desctx.round = 0; r_anal_esil_set_op (esil, "des", avr_custom_des); r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase); r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill); r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write); esil->cb.hook_reg_write = esil_avr_hook_reg_write; return true; } static int esil_avr_fini(RAnalEsil *esil) { return true; } static int set_reg_profile(RAnal *anal) { const char *p = "=PC pcl\n" "=SP sp\n" // explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html // and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file "=A0 r25\n" "=A1 r24\n" "=A2 r23\n" "=A3 r22\n" "=R0 r24\n" #if 0 PC: 16- or 22-bit program counter SP: 8- or 16-bit stack pointer SREG: 8-bit status register RAMPX, RAMPY, RAMPZ, RAMPD and EIND: #endif // 8bit registers x 32 "gpr r0 .8 0 0\n" "gpr r1 .8 1 0\n" "gpr r2 .8 2 0\n" "gpr r3 .8 3 0\n" "gpr r4 .8 4 0\n" "gpr r5 .8 5 0\n" "gpr r6 .8 6 0\n" "gpr r7 .8 7 0\n" "gpr text .64 0 0\n" "gpr r8 .8 8 0\n" "gpr r9 .8 9 0\n" "gpr r10 .8 10 0\n" "gpr r11 .8 11 0\n" "gpr r12 .8 12 0\n" "gpr r13 .8 13 0\n" "gpr r14 .8 14 0\n" "gpr r15 .8 15 0\n" "gpr deskey .64 8 0\n" "gpr r16 .8 16 0\n" "gpr r17 .8 17 0\n" "gpr r18 .8 18 0\n" "gpr r19 .8 19 0\n" "gpr r20 .8 20 0\n" "gpr r21 .8 21 0\n" "gpr r22 .8 22 0\n" "gpr r23 .8 23 0\n" "gpr r24 .8 24 0\n" "gpr r25 .8 25 0\n" "gpr r26 .8 26 0\n" "gpr r27 .8 27 0\n" "gpr r28 .8 28 0\n" "gpr r29 .8 29 0\n" "gpr r30 .8 30 0\n" "gpr r31 .8 31 0\n" // 16 bit overlapped registers for 16 bit math "gpr r17:r16 .16 16 0\n" "gpr r19:r18 .16 18 0\n" "gpr r21:r20 .16 20 0\n" "gpr r23:r22 .16 22 0\n" "gpr r25:r24 .16 24 0\n" "gpr r27:r26 .16 26 0\n" "gpr r29:r28 .16 28 0\n" "gpr r31:r30 .16 30 0\n" // 16 bit overlapped registers for memory addressing "gpr x .16 26 0\n" "gpr y .16 28 0\n" "gpr z .16 30 0\n" // program counter // NOTE: program counter size in AVR depends on the CPU model. It seems that // the PC may range from 16 bits to 22 bits. "gpr pc .32 32 0\n" "gpr pcl .16 32 0\n" "gpr pch .16 34 0\n" // special purpose registers "gpr sp .16 36 0\n" "gpr spl .8 36 0\n" "gpr sph .8 37 0\n" // status bit register (SREG) "gpr sreg .8 38 0\n" "gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts. "gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero. "gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result. "gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow. "gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison. "gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic. "gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit. "gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled. // 8bit segment registers to be added to X, Y, Z to get 24bit offsets "gpr rampx .8 39 0\n" "gpr rampy .8 40 0\n" "gpr rampz .8 41 0\n" "gpr rampd .8 42 0\n" "gpr eind .8 43 0\n" // memory mapping emulator registers // _prog // the program flash. It has its own address space. // _ram // _io // start of the data addres space. It is the same address of IO, // because IO is the first memory space addressable in the AVR. // _sram // start of the SRAM (this offset depends on IO size, and it is // inside the _ram address space) // _eeprom // this is another address space, outside ram and flash // _page // this is the temporary page used by the SPM instruction. This // memory is not directly addressable and it is used internally by // the CPU when autoflashing. "gpr _prog .32 44 0\n" "gpr _page .32 48 0\n" "gpr _eeprom .32 52 0\n" "gpr _ram .32 56 0\n" "gpr _io .32 56 0\n" "gpr _sram .32 60 0\n" // other important MCU registers // spmcsr/spmcr // Store Program Memory Control and Status Register (SPMCSR) "gpr spmcsr .8 64 0\n" ; return r_reg_set_profile_string (anal->reg, p); } static int archinfo(RAnal *anal, int q) { if (q == R_ANAL_ARCHINFO_ALIGN) return 2; if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE) return 4; if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE) return 2; return 2; // XXX } static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) { RAnalOp *op = NULL; ut8 *ret = NULL; int idx; if (!(op = r_anal_op_new ())) { return NULL; } if (!(ret = malloc (size))) { r_anal_op_free (op); return NULL; } memset (ret, 0xff, size); CPU_MODEL *cpu = get_cpu_model (anal->cpu); for (idx = 0; idx + 1 < size; idx += op->size) { OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu); if (op->size < 1) { break; } if (!opcode_desc) { // invalid instruction continue; } // the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching // (things like memory offsets or jump addresses) if (op->size == 4) { ret[idx + 2] = 0; ret[idx + 3] = 0; } if (op->ptr != UT64_MAX || op->jump != UT64_MAX) { ret[idx] = opcode_desc->mask; ret[idx + 1] = opcode_desc->mask >> 8; } } r_anal_op_free (op); return ret; } RAnalPlugin r_anal_plugin_avr = { .name = "avr", .desc = "AVR code analysis plugin", .license = "LGPL3", .arch = "avr", .esil = true, .archinfo = archinfo, .bits = 8 | 16, // 24 big regs conflicts .op = &avr_op, .set_reg_profile = &set_reg_profile, .esil_init = esil_avr_init, .esil_fini = esil_avr_fini, .anal_mask = anal_mask_avr, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_avr, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_139_0
crossvul-cpp_data_good_264_0
/* * Copyright: (c) 2000 United States Government as represented by the * Secretary of the Navy. 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. * 3. The names of the authors may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: AFS RX printer */ /* * This code unmangles RX packets. RX is the mutant form of RPC that AFS * uses to communicate between clients and servers. * * In this code, I mainly concern myself with decoding the AFS calls, not * with the guts of RX, per se. * * Bah. If I never look at rx_packet.h again, it will be too soon. * * Ken Hornstein <kenh@cmf.nrl.navy.mil> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #define FS_RX_PORT 7000 #define CB_RX_PORT 7001 #define PROT_RX_PORT 7002 #define VLDB_RX_PORT 7003 #define KAUTH_RX_PORT 7004 #define VOL_RX_PORT 7005 #define ERROR_RX_PORT 7006 /* Doesn't seem to be used */ #define BOS_RX_PORT 7007 #define AFSNAMEMAX 256 #define AFSOPAQUEMAX 1024 #define PRNAMEMAX 64 #define VLNAMEMAX 65 #define KANAMEMAX 64 #define BOSNAMEMAX 256 #define PRSFS_READ 1 /* Read files */ #define PRSFS_WRITE 2 /* Write files */ #define PRSFS_INSERT 4 /* Insert files into a directory */ #define PRSFS_LOOKUP 8 /* Lookup files into a directory */ #define PRSFS_DELETE 16 /* Delete files */ #define PRSFS_LOCK 32 /* Lock files */ #define PRSFS_ADMINISTER 64 /* Change ACL's */ struct rx_header { nd_uint32_t epoch; nd_uint32_t cid; nd_uint32_t callNumber; nd_uint32_t seq; nd_uint32_t serial; nd_uint8_t type; #define RX_PACKET_TYPE_DATA 1 #define RX_PACKET_TYPE_ACK 2 #define RX_PACKET_TYPE_BUSY 3 #define RX_PACKET_TYPE_ABORT 4 #define RX_PACKET_TYPE_ACKALL 5 #define RX_PACKET_TYPE_CHALLENGE 6 #define RX_PACKET_TYPE_RESPONSE 7 #define RX_PACKET_TYPE_DEBUG 8 #define RX_PACKET_TYPE_PARAMS 9 #define RX_PACKET_TYPE_VERSION 13 nd_uint8_t flags; #define RX_CLIENT_INITIATED 1 #define RX_REQUEST_ACK 2 #define RX_LAST_PACKET 4 #define RX_MORE_PACKETS 8 #define RX_FREE_PACKET 16 #define RX_SLOW_START_OK 32 #define RX_JUMBO_PACKET 32 nd_uint8_t userStatus; nd_uint8_t securityIndex; nd_uint16_t spare; /* How clever: even though the AFS */ nd_uint16_t serviceId; /* header files indicate that the */ }; /* serviceId is first, it's really */ /* encoded _after_ the spare field */ /* I wasted a day figuring that out! */ #define NUM_RX_FLAGS 7 #define RX_MAXACKS 255 struct rx_ackPacket { uint16_t bufferSpace; /* Number of packet buffers available */ uint16_t maxSkew; /* Max diff between ack'd packet and */ /* highest packet received */ uint32_t firstPacket; /* The first packet in ack list */ uint32_t previousPacket; /* Previous packet recv'd (obsolete) */ uint32_t serial; /* # of packet that prompted the ack */ uint8_t reason; /* Reason for acknowledgement */ uint8_t nAcks; /* Number of acknowledgements */ uint8_t acks[RX_MAXACKS]; /* Up to RX_MAXACKS acknowledgements */ }; /* * Values for the acks array */ #define RX_ACK_TYPE_NACK 0 /* Don't have this packet */ #define RX_ACK_TYPE_ACK 1 /* I have this packet */ static const struct tok rx_types[] = { { RX_PACKET_TYPE_DATA, "data" }, { RX_PACKET_TYPE_ACK, "ack" }, { RX_PACKET_TYPE_BUSY, "busy" }, { RX_PACKET_TYPE_ABORT, "abort" }, { RX_PACKET_TYPE_ACKALL, "ackall" }, { RX_PACKET_TYPE_CHALLENGE, "challenge" }, { RX_PACKET_TYPE_RESPONSE, "response" }, { RX_PACKET_TYPE_DEBUG, "debug" }, { RX_PACKET_TYPE_PARAMS, "params" }, { RX_PACKET_TYPE_VERSION, "version" }, { 0, NULL }, }; static const struct double_tok { int flag; /* Rx flag */ int packetType; /* Packet type */ const char *s; /* Flag string */ } rx_flags[] = { { RX_CLIENT_INITIATED, 0, "client-init" }, { RX_REQUEST_ACK, 0, "req-ack" }, { RX_LAST_PACKET, 0, "last-pckt" }, { RX_MORE_PACKETS, 0, "more-pckts" }, { RX_FREE_PACKET, 0, "free-pckt" }, { RX_SLOW_START_OK, RX_PACKET_TYPE_ACK, "slow-start" }, { RX_JUMBO_PACKET, RX_PACKET_TYPE_DATA, "jumbogram" } }; static const struct tok fs_req[] = { { 130, "fetch-data" }, { 131, "fetch-acl" }, { 132, "fetch-status" }, { 133, "store-data" }, { 134, "store-acl" }, { 135, "store-status" }, { 136, "remove-file" }, { 137, "create-file" }, { 138, "rename" }, { 139, "symlink" }, { 140, "link" }, { 141, "makedir" }, { 142, "rmdir" }, { 143, "oldsetlock" }, { 144, "oldextlock" }, { 145, "oldrellock" }, { 146, "get-stats" }, { 147, "give-cbs" }, { 148, "get-vlinfo" }, { 149, "get-vlstats" }, { 150, "set-vlstats" }, { 151, "get-rootvl" }, { 152, "check-token" }, { 153, "get-time" }, { 154, "nget-vlinfo" }, { 155, "bulk-stat" }, { 156, "setlock" }, { 157, "extlock" }, { 158, "rellock" }, { 159, "xstat-ver" }, { 160, "get-xstat" }, { 161, "dfs-lookup" }, { 162, "dfs-flushcps" }, { 163, "dfs-symlink" }, { 220, "residency" }, { 65536, "inline-bulk-status" }, { 65537, "fetch-data-64" }, { 65538, "store-data-64" }, { 65539, "give-up-all-cbs" }, { 65540, "get-caps" }, { 65541, "cb-rx-conn-addr" }, { 0, NULL }, }; static const struct tok cb_req[] = { { 204, "callback" }, { 205, "initcb" }, { 206, "probe" }, { 207, "getlock" }, { 208, "getce" }, { 209, "xstatver" }, { 210, "getxstat" }, { 211, "initcb2" }, { 212, "whoareyou" }, { 213, "initcb3" }, { 214, "probeuuid" }, { 215, "getsrvprefs" }, { 216, "getcellservdb" }, { 217, "getlocalcell" }, { 218, "getcacheconf" }, { 65536, "getce64" }, { 65537, "getcellbynum" }, { 65538, "tellmeaboutyourself" }, { 0, NULL }, }; static const struct tok pt_req[] = { { 500, "new-user" }, { 501, "where-is-it" }, { 502, "dump-entry" }, { 503, "add-to-group" }, { 504, "name-to-id" }, { 505, "id-to-name" }, { 506, "delete" }, { 507, "remove-from-group" }, { 508, "get-cps" }, { 509, "new-entry" }, { 510, "list-max" }, { 511, "set-max" }, { 512, "list-entry" }, { 513, "change-entry" }, { 514, "list-elements" }, { 515, "same-mbr-of" }, { 516, "set-fld-sentry" }, { 517, "list-owned" }, { 518, "get-cps2" }, { 519, "get-host-cps" }, { 520, "update-entry" }, { 521, "list-entries" }, { 530, "list-super-groups" }, { 0, NULL }, }; static const struct tok vldb_req[] = { { 501, "create-entry" }, { 502, "delete-entry" }, { 503, "get-entry-by-id" }, { 504, "get-entry-by-name" }, { 505, "get-new-volume-id" }, { 506, "replace-entry" }, { 507, "update-entry" }, { 508, "setlock" }, { 509, "releaselock" }, { 510, "list-entry" }, { 511, "list-attrib" }, { 512, "linked-list" }, { 513, "get-stats" }, { 514, "probe" }, { 515, "get-addrs" }, { 516, "change-addr" }, { 517, "create-entry-n" }, { 518, "get-entry-by-id-n" }, { 519, "get-entry-by-name-n" }, { 520, "replace-entry-n" }, { 521, "list-entry-n" }, { 522, "list-attrib-n" }, { 523, "linked-list-n" }, { 524, "update-entry-by-name" }, { 525, "create-entry-u" }, { 526, "get-entry-by-id-u" }, { 527, "get-entry-by-name-u" }, { 528, "replace-entry-u" }, { 529, "list-entry-u" }, { 530, "list-attrib-u" }, { 531, "linked-list-u" }, { 532, "regaddr" }, { 533, "get-addrs-u" }, { 534, "list-attrib-n2" }, { 0, NULL }, }; static const struct tok kauth_req[] = { { 1, "auth-old" }, { 21, "authenticate" }, { 22, "authenticate-v2" }, { 2, "change-pw" }, { 3, "get-ticket-old" }, { 23, "get-ticket" }, { 4, "set-pw" }, { 5, "set-fields" }, { 6, "create-user" }, { 7, "delete-user" }, { 8, "get-entry" }, { 9, "list-entry" }, { 10, "get-stats" }, { 11, "debug" }, { 12, "get-pw" }, { 13, "get-random-key" }, { 14, "unlock" }, { 15, "lock-status" }, { 0, NULL }, }; static const struct tok vol_req[] = { { 100, "create-volume" }, { 101, "delete-volume" }, { 102, "restore" }, { 103, "forward" }, { 104, "end-trans" }, { 105, "clone" }, { 106, "set-flags" }, { 107, "get-flags" }, { 108, "trans-create" }, { 109, "dump" }, { 110, "get-nth-volume" }, { 111, "set-forwarding" }, { 112, "get-name" }, { 113, "get-status" }, { 114, "sig-restore" }, { 115, "list-partitions" }, { 116, "list-volumes" }, { 117, "set-id-types" }, { 118, "monitor" }, { 119, "partition-info" }, { 120, "reclone" }, { 121, "list-one-volume" }, { 122, "nuke" }, { 123, "set-date" }, { 124, "x-list-volumes" }, { 125, "x-list-one-volume" }, { 126, "set-info" }, { 127, "x-list-partitions" }, { 128, "forward-multiple" }, { 65536, "convert-ro" }, { 65537, "get-size" }, { 65538, "dump-v2" }, { 0, NULL }, }; static const struct tok bos_req[] = { { 80, "create-bnode" }, { 81, "delete-bnode" }, { 82, "set-status" }, { 83, "get-status" }, { 84, "enumerate-instance" }, { 85, "get-instance-info" }, { 86, "get-instance-parm" }, { 87, "add-superuser" }, { 88, "delete-superuser" }, { 89, "list-superusers" }, { 90, "list-keys" }, { 91, "add-key" }, { 92, "delete-key" }, { 93, "set-cell-name" }, { 94, "get-cell-name" }, { 95, "get-cell-host" }, { 96, "add-cell-host" }, { 97, "delete-cell-host" }, { 98, "set-t-status" }, { 99, "shutdown-all" }, { 100, "restart-all" }, { 101, "startup-all" }, { 102, "set-noauth-flag" }, { 103, "re-bozo" }, { 104, "restart" }, { 105, "start-bozo-install" }, { 106, "uninstall" }, { 107, "get-dates" }, { 108, "exec" }, { 109, "prune" }, { 110, "set-restart-time" }, { 111, "get-restart-time" }, { 112, "start-bozo-log" }, { 113, "wait-all" }, { 114, "get-instance-strings" }, { 115, "get-restricted" }, { 116, "set-restricted" }, { 0, NULL }, }; static const struct tok ubik_req[] = { { 10000, "vote-beacon" }, { 10001, "vote-debug-old" }, { 10002, "vote-sdebug-old" }, { 10003, "vote-getsyncsite" }, { 10004, "vote-debug" }, { 10005, "vote-sdebug" }, { 10006, "vote-xdebug" }, { 10007, "vote-xsdebug" }, { 20000, "disk-begin" }, { 20001, "disk-commit" }, { 20002, "disk-lock" }, { 20003, "disk-write" }, { 20004, "disk-getversion" }, { 20005, "disk-getfile" }, { 20006, "disk-sendfile" }, { 20007, "disk-abort" }, { 20008, "disk-releaselocks" }, { 20009, "disk-truncate" }, { 20010, "disk-probe" }, { 20011, "disk-writev" }, { 20012, "disk-interfaceaddr" }, { 20013, "disk-setversion" }, { 0, NULL }, }; #define VOTE_LOW 10000 #define VOTE_HIGH 10007 #define DISK_LOW 20000 #define DISK_HIGH 20013 static const struct tok cb_types[] = { { 1, "exclusive" }, { 2, "shared" }, { 3, "dropped" }, { 0, NULL }, }; static const struct tok ubik_lock_types[] = { { 1, "read" }, { 2, "write" }, { 3, "wait" }, { 0, NULL }, }; static const char *voltype[] = { "read-write", "read-only", "backup" }; static const struct tok afs_fs_errors[] = { { 101, "salvage volume" }, { 102, "no such vnode" }, { 103, "no such volume" }, { 104, "volume exist" }, { 105, "no service" }, { 106, "volume offline" }, { 107, "voline online" }, { 108, "diskfull" }, { 109, "diskquota exceeded" }, { 110, "volume busy" }, { 111, "volume moved" }, { 112, "AFS IO error" }, { 0xffffff9c, "restarting fileserver" }, /* -100, sic! */ { 0, NULL } }; /* * Reasons for acknowledging a packet */ static const struct tok rx_ack_reasons[] = { { 1, "ack requested" }, { 2, "duplicate packet" }, { 3, "out of sequence" }, { 4, "exceeds window" }, { 5, "no buffer space" }, { 6, "ping" }, { 7, "ping response" }, { 8, "delay" }, { 9, "idle" }, { 0, NULL }, }; /* * Cache entries we keep around so we can figure out the RX opcode * numbers for replies. This allows us to make sense of RX reply packets. */ struct rx_cache_entry { uint32_t callnum; /* Call number (net order) */ struct in_addr client; /* client IP address (net order) */ struct in_addr server; /* server IP address (net order) */ int dport; /* server port (host order) */ u_short serviceId; /* Service identifier (net order) */ uint32_t opcode; /* RX opcode (host order) */ }; #define RX_CACHE_SIZE 64 static struct rx_cache_entry rx_cache[RX_CACHE_SIZE]; static int rx_cache_next = 0; static int rx_cache_hint = 0; static void rx_cache_insert(netdissect_options *, const u_char *, const struct ip *, int); static int rx_cache_find(const struct rx_header *, const struct ip *, int, int32_t *); static void fs_print(netdissect_options *, const u_char *, int); static void fs_reply_print(netdissect_options *, const u_char *, int, int32_t); static void acl_print(netdissect_options *, u_char *, int, u_char *); static void cb_print(netdissect_options *, const u_char *, int); static void cb_reply_print(netdissect_options *, const u_char *, int, int32_t); static void prot_print(netdissect_options *, const u_char *, int); static void prot_reply_print(netdissect_options *, const u_char *, int, int32_t); static void vldb_print(netdissect_options *, const u_char *, int); static void vldb_reply_print(netdissect_options *, const u_char *, int, int32_t); static void kauth_print(netdissect_options *, const u_char *, int); static void kauth_reply_print(netdissect_options *, const u_char *, int, int32_t); static void vol_print(netdissect_options *, const u_char *, int); static void vol_reply_print(netdissect_options *, const u_char *, int, int32_t); static void bos_print(netdissect_options *, const u_char *, int); static void bos_reply_print(netdissect_options *, const u_char *, int, int32_t); static void ubik_print(netdissect_options *, const u_char *); static void ubik_reply_print(netdissect_options *, const u_char *, int, int32_t); static void rx_ack_print(netdissect_options *, const u_char *, int); static int is_ubik(uint32_t); /* * Handle the rx-level packet. See if we know what port it's going to so * we can peek at the afs call inside */ void rx_print(netdissect_options *ndo, register const u_char *bp, int length, int sport, int dport, const u_char *bp2) { register const struct rx_header *rxh; int i; int32_t opcode; if (ndo->ndo_snapend - bp < (int)sizeof (struct rx_header)) { ND_PRINT((ndo, " [|rx] (%d)", length)); return; } rxh = (const struct rx_header *) bp; ND_PRINT((ndo, " rx %s", tok2str(rx_types, "type %d", rxh->type))); if (ndo->ndo_vflag) { int firstflag = 0; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, " cid %08x call# %d", (int) EXTRACT_32BITS(&rxh->cid), (int) EXTRACT_32BITS(&rxh->callNumber))); ND_PRINT((ndo, " seq %d ser %d", (int) EXTRACT_32BITS(&rxh->seq), (int) EXTRACT_32BITS(&rxh->serial))); if (ndo->ndo_vflag > 2) ND_PRINT((ndo, " secindex %d serviceid %hu", (int) rxh->securityIndex, EXTRACT_16BITS(&rxh->serviceId))); if (ndo->ndo_vflag > 1) for (i = 0; i < NUM_RX_FLAGS; i++) { if (rxh->flags & rx_flags[i].flag && (!rx_flags[i].packetType || rxh->type == rx_flags[i].packetType)) { if (!firstflag) { firstflag = 1; ND_PRINT((ndo, " ")); } else { ND_PRINT((ndo, ",")); } ND_PRINT((ndo, "<%s>", rx_flags[i].s)); } } } /* * Try to handle AFS calls that we know about. Check the destination * port and make sure it's a data packet. Also, make sure the * seq number is 1 (because otherwise it's a continuation packet, * and we can't interpret that). Also, seems that reply packets * do not have the client-init flag set, so we check for that * as well. */ if (rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1 && rxh->flags & RX_CLIENT_INITIATED) { /* * Insert this call into the call cache table, so we * have a chance to print out replies */ rx_cache_insert(ndo, bp, (const struct ip *) bp2, dport); switch (dport) { case FS_RX_PORT: /* AFS file service */ fs_print(ndo, bp, length); break; case CB_RX_PORT: /* AFS callback service */ cb_print(ndo, bp, length); break; case PROT_RX_PORT: /* AFS protection service */ prot_print(ndo, bp, length); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_print(ndo, bp, length); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_print(ndo, bp, length); break; case VOL_RX_PORT: /* AFS Volume service */ vol_print(ndo, bp, length); break; case BOS_RX_PORT: /* AFS BOS service */ bos_print(ndo, bp, length); break; default: ; } /* * If it's a reply (client-init is _not_ set, but seq is one) * then look it up in the cache. If we find it, call the reply * printing functions Note that we handle abort packets here, * because printing out the return code can be useful at times. */ } else if (((rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1) || rxh->type == RX_PACKET_TYPE_ABORT) && (rxh->flags & RX_CLIENT_INITIATED) == 0 && rx_cache_find(rxh, (const struct ip *) bp2, sport, &opcode)) { switch (sport) { case FS_RX_PORT: /* AFS file service */ fs_reply_print(ndo, bp, length, opcode); break; case CB_RX_PORT: /* AFS callback service */ cb_reply_print(ndo, bp, length, opcode); break; case PROT_RX_PORT: /* AFS PT service */ prot_reply_print(ndo, bp, length, opcode); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_reply_print(ndo, bp, length, opcode); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_reply_print(ndo, bp, length, opcode); break; case VOL_RX_PORT: /* AFS Volume service */ vol_reply_print(ndo, bp, length, opcode); break; case BOS_RX_PORT: /* AFS BOS service */ bos_reply_print(ndo, bp, length, opcode); break; default: ; } /* * If it's an RX ack packet, then use the appropriate ack decoding * function (there isn't any service-specific information in the * ack packet, so we can use one for all AFS services) */ } else if (rxh->type == RX_PACKET_TYPE_ACK) rx_ack_print(ndo, bp, length); ND_PRINT((ndo, " (%d)", length)); } /* * Insert an entry into the cache. Taken from print-nfs.c */ static void rx_cache_insert(netdissect_options *ndo, const u_char *bp, const struct ip *ip, int dport) { struct rx_cache_entry *rxent; const struct rx_header *rxh = (const struct rx_header *) bp; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) return; rxent = &rx_cache[rx_cache_next]; if (++rx_cache_next >= RX_CACHE_SIZE) rx_cache_next = 0; rxent->callnum = EXTRACT_32BITS(&rxh->callNumber); UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t)); UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t)); rxent->dport = dport; rxent->serviceId = EXTRACT_16BITS(&rxh->serviceId); rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header)); } /* * Lookup an entry in the cache. Also taken from print-nfs.c * * Note that because this is a reply, we're looking at the _source_ * port. */ static int rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport, int32_t *opcode) { int i; struct rx_cache_entry *rxent; uint32_t clip; uint32_t sip; UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t)); UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t)); /* Start the search where we last left off */ i = rx_cache_hint; do { rxent = &rx_cache[i]; if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) && rxent->client.s_addr == clip && rxent->server.s_addr == sip && rxent->serviceId == EXTRACT_16BITS(&rxh->serviceId) && rxent->dport == sport) { /* We got a match! */ rx_cache_hint = i; *opcode = rxent->opcode; return(1); } if (++i >= RX_CACHE_SIZE) i = 0; } while (i != rx_cache_hint); /* Our search failed */ return(0); } /* * These extrememly grody macros handle the printing of various AFS stuff. */ #define FIDOUT() { unsigned long n1, n2, n3; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \ n1 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n2 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n3 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " fid %d/%d/%d", (int) n1, (int) n2, (int) n3)); \ } #define STROUT(MAX) { unsigned int _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = EXTRACT_32BITS(bp); \ if (_i > (MAX)) \ goto trunc; \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " \"")); \ if (fn_printn(ndo, bp, _i, ndo->ndo_snapend)) \ goto trunc; \ ND_PRINT((ndo, "\"")); \ bp += ((_i + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t); \ } #define INTOUT() { int _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = (int) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %d", _i)); \ } #define UINTOUT() { unsigned long _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %lu", _i)); \ } #define UINT64OUT() { uint64_t _i; \ ND_TCHECK2(bp[0], sizeof(uint64_t)); \ _i = EXTRACT_64BITS(bp); \ bp += sizeof(uint64_t); \ ND_PRINT((ndo, " %" PRIu64, _i)); \ } #define DATEOUT() { time_t _t; struct tm *tm; char str[256]; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _t = (time_t) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ tm = localtime(&_t); \ strftime(str, 256, "%Y/%m/%d %H:%M:%S", tm); \ ND_PRINT((ndo, " %s", str)); \ } #define STOREATTROUT() { unsigned long mask, _i; \ ND_TCHECK2(bp[0], (sizeof(int32_t)*6)); \ mask = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask) ND_PRINT((ndo, " StoreStatus")); \ if (mask & 1) { ND_PRINT((ndo, " date")); DATEOUT(); } \ else bp += sizeof(int32_t); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 2) ND_PRINT((ndo, " owner %lu", _i)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 4) ND_PRINT((ndo, " group %lu", _i)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 8) ND_PRINT((ndo, " mode %lo", _i & 07777)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 16) ND_PRINT((ndo, " segsize %lu", _i)); \ /* undocumented in 3.3 docu */ \ if (mask & 1024) ND_PRINT((ndo, " fsync")); \ } #define UBIK_VERSIONOUT() {int32_t epoch; int32_t counter; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 2); \ epoch = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ counter = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %d.%d", epoch, counter)); \ } #define AFSUUIDOUT() {uint32_t temp; int _i; \ ND_TCHECK2(bp[0], 11*sizeof(uint32_t)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, " %08x", temp)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%04x", temp)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%04x", temp)); \ for (_i = 0; _i < 8; _i++) { \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%02x", (unsigned char) temp)); \ } \ } /* * This is the sickest one of all */ #define VECOUT(MAX) { u_char *sp; \ u_char s[AFSNAMEMAX]; \ int k; \ if ((MAX) + 1 > sizeof(s)) \ goto trunc; \ ND_TCHECK2(bp[0], (MAX) * sizeof(int32_t)); \ sp = s; \ for (k = 0; k < (MAX); k++) { \ *sp++ = (u_char) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ } \ s[(MAX)] = '\0'; \ ND_PRINT((ndo, " \"")); \ fn_print(ndo, s, NULL); \ ND_PRINT((ndo, "\"")); \ } #define DESTSERVEROUT() { unsigned long n1, n2, n3; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \ n1 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n2 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n3 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " server %d:%d:%d", (int) n1, (int) n2, (int) n3)); \ } /* * Handle calls to the AFS file service (fs) */ static void fs_print(netdissect_options *ndo, register const u_char *bp, int length) { int fs_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afsint.xg */ fs_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " fs call %s", tok2str(fs_req, "op#%d", fs_op))); /* * Print out arguments to some of the AFS calls. This stuff is * all from afsint.xg */ bp += sizeof(struct rx_header) + 4; /* * Sigh. This is gross. Ritchie forgive me. */ switch (fs_op) { case 130: /* Fetch data */ FIDOUT(); ND_PRINT((ndo, " offset")); UINTOUT(); ND_PRINT((ndo, " length")); UINTOUT(); break; case 131: /* Fetch ACL */ case 132: /* Fetch Status */ case 143: /* Old set lock */ case 144: /* Old extend lock */ case 145: /* Old release lock */ case 156: /* Set lock */ case 157: /* Extend lock */ case 158: /* Release lock */ FIDOUT(); break; case 135: /* Store status */ FIDOUT(); STOREATTROUT(); break; case 133: /* Store data */ FIDOUT(); STOREATTROUT(); ND_PRINT((ndo, " offset")); UINTOUT(); ND_PRINT((ndo, " length")); UINTOUT(); ND_PRINT((ndo, " flen")); UINTOUT(); break; case 134: /* Store ACL */ { char a[AFSOPAQUEMAX+1]; FIDOUT(); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); i = min(AFSOPAQUEMAX, i); strncpy(a, (const char *) bp, i); a[i] = '\0'; acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i); break; } case 137: /* Create file */ case 141: /* MakeDir */ FIDOUT(); STROUT(AFSNAMEMAX); STOREATTROUT(); break; case 136: /* Remove file */ case 142: /* Remove directory */ FIDOUT(); STROUT(AFSNAMEMAX); break; case 138: /* Rename file */ ND_PRINT((ndo, " old")); FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " new")); FIDOUT(); STROUT(AFSNAMEMAX); break; case 139: /* Symlink */ FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " link to")); STROUT(AFSNAMEMAX); break; case 140: /* Link */ FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " link to")); FIDOUT(); break; case 148: /* Get volume info */ STROUT(AFSNAMEMAX); break; case 149: /* Get volume stats */ case 150: /* Set volume stats */ ND_PRINT((ndo, " volid")); UINTOUT(); break; case 154: /* New get volume info */ ND_PRINT((ndo, " volname")); STROUT(AFSNAMEMAX); break; case 155: /* Bulk stat */ case 65536: /* Inline bulk stat */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { FIDOUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); break; } case 65537: /* Fetch data 64 */ FIDOUT(); ND_PRINT((ndo, " offset")); UINT64OUT(); ND_PRINT((ndo, " length")); UINT64OUT(); break; case 65538: /* Store data 64 */ FIDOUT(); STOREATTROUT(); ND_PRINT((ndo, " offset")); UINT64OUT(); ND_PRINT((ndo, " length")); UINT64OUT(); ND_PRINT((ndo, " flen")); UINT64OUT(); break; case 65541: /* CallBack rx conn address */ ND_PRINT((ndo, " addr")); UINTOUT(); default: ; } return; trunc: ND_PRINT((ndo, " [|fs]")); } /* * Handle replies to the AFS file service */ static void fs_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { unsigned long i; const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afsint.xg */ ND_PRINT((ndo, " fs reply %s", tok2str(fs_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) { switch (opcode) { case 131: /* Fetch ACL */ { char a[AFSOPAQUEMAX+1]; ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); i = min(AFSOPAQUEMAX, i); strncpy(a, (const char *) bp, i); a[i] = '\0'; acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i); break; } case 137: /* Create file */ case 141: /* MakeDir */ ND_PRINT((ndo, " new")); FIDOUT(); break; case 151: /* Get root volume */ ND_PRINT((ndo, " root volume")); STROUT(AFSNAMEMAX); break; case 153: /* Get time */ DATEOUT(); break; default: ; } } else if (rxh->type == RX_PACKET_TYPE_ABORT) { /* * Otherwise, just print out the return code */ ND_TCHECK2(bp[0], sizeof(int32_t)); i = (int) EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " error %s", tok2str(afs_fs_errors, "#%d", i))); } else { ND_PRINT((ndo, " strange fs reply of type %d", rxh->type)); } return; trunc: ND_PRINT((ndo, " [|fs]")); } /* * Print out an AFS ACL string. An AFS ACL is a string that has the * following format: * * <positive> <negative> * <uid1> <aclbits1> * .... * * "positive" and "negative" are integers which contain the number of * positive and negative ACL's in the string. The uid/aclbits pair are * ASCII strings containing the UID/PTS record and and a ascii number * representing a logical OR of all the ACL permission bits */ static void acl_print(netdissect_options *ndo, u_char *s, int maxsize, u_char *end) { int pos, neg, acl; int n, i; char *user; char fmt[1024]; if ((user = (char *)malloc(maxsize)) == NULL) return; if (sscanf((char *) s, "%d %d\n%n", &pos, &neg, &n) != 2) goto finish; s += n; if (s > end) goto finish; /* * This wacky order preserves the order used by the "fs" command */ #define ACLOUT(acl) \ ND_PRINT((ndo, "%s%s%s%s%s%s%s", \ acl & PRSFS_READ ? "r" : "", \ acl & PRSFS_LOOKUP ? "l" : "", \ acl & PRSFS_INSERT ? "i" : "", \ acl & PRSFS_DELETE ? "d" : "", \ acl & PRSFS_WRITE ? "w" : "", \ acl & PRSFS_LOCK ? "k" : "", \ acl & PRSFS_ADMINISTER ? "a" : "")); for (i = 0; i < pos; i++) { snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1); if (sscanf((char *) s, fmt, user, &acl, &n) != 2) goto finish; s += n; ND_PRINT((ndo, " +{")); fn_print(ndo, (u_char *)user, NULL); ND_PRINT((ndo, " ")); ACLOUT(acl); ND_PRINT((ndo, "}")); if (s > end) goto finish; } for (i = 0; i < neg; i++) { snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1); if (sscanf((char *) s, fmt, user, &acl, &n) != 2) goto finish; s += n; ND_PRINT((ndo, " -{")); fn_print(ndo, (u_char *)user, NULL); ND_PRINT((ndo, " ")); ACLOUT(acl); ND_PRINT((ndo, "}")); if (s > end) goto finish; } finish: free(user); return; } #undef ACLOUT /* * Handle calls to the AFS callback service */ static void cb_print(netdissect_options *ndo, register const u_char *bp, int length) { int cb_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ cb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " cb call %s", tok2str(cb_req, "op#%d", cb_op))); bp += sizeof(struct rx_header) + 4; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ switch (cb_op) { case 204: /* Callback */ { unsigned long j, t; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { FIDOUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); ND_TCHECK_32BITS(bp); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (j != 0) ND_PRINT((ndo, ";")); for (i = 0; i < j; i++) { ND_PRINT((ndo, " ver")); INTOUT(); ND_PRINT((ndo, " expires")); DATEOUT(); ND_TCHECK2(bp[0], 4); t = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(cb_types, "type %d", t); } break; } case 214: { ND_PRINT((ndo, " afsuuid")); AFSUUIDOUT(); break; } default: ; } return; trunc: ND_PRINT((ndo, " [|cb]")); } /* * Handle replies to the AFS Callback Service */ static void cb_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ ND_PRINT((ndo, " cb reply %s", tok2str(cb_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 213: /* InitCallBackState3 */ AFSUUIDOUT(); break; default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|cb]")); } /* * Handle calls to the AFS protection database server */ static void prot_print(netdissect_options *ndo, register const u_char *bp, int length) { unsigned long i; int pt_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from ptserver/ptint.xg */ pt_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " pt")); if (is_ubik(pt_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(pt_req, "op#%d", pt_op))); /* * Decode some of the arguments to the PT calls */ bp += sizeof(struct rx_header) + 4; switch (pt_op) { case 500: /* I New User */ STROUT(PRNAMEMAX); ND_PRINT((ndo, " id")); INTOUT(); ND_PRINT((ndo, " oldid")); INTOUT(); break; case 501: /* Where is it */ case 506: /* Delete */ case 508: /* Get CPS */ case 512: /* List entry */ case 514: /* List elements */ case 517: /* List owned */ case 518: /* Get CPS2 */ case 519: /* Get host CPS */ case 530: /* List super groups */ ND_PRINT((ndo, " id")); INTOUT(); break; case 502: /* Dump entry */ ND_PRINT((ndo, " pos")); INTOUT(); break; case 503: /* Add to group */ case 507: /* Remove from group */ case 515: /* Is a member of? */ ND_PRINT((ndo, " uid")); INTOUT(); ND_PRINT((ndo, " gid")); INTOUT(); break; case 504: /* Name to ID */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); /* * Who designed this chicken-shit protocol? * * Each character is stored as a 32-bit * integer! */ for (i = 0; i < j; i++) { VECOUT(PRNAMEMAX); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 505: /* Id to name */ { unsigned long j; ND_PRINT((ndo, " ids:")); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (j = 0; j < i; j++) INTOUT(); if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 509: /* New entry */ STROUT(PRNAMEMAX); ND_PRINT((ndo, " flag")); INTOUT(); ND_PRINT((ndo, " oid")); INTOUT(); break; case 511: /* Set max */ ND_PRINT((ndo, " id")); INTOUT(); ND_PRINT((ndo, " gflag")); INTOUT(); break; case 513: /* Change entry */ ND_PRINT((ndo, " id")); INTOUT(); STROUT(PRNAMEMAX); ND_PRINT((ndo, " oldid")); INTOUT(); ND_PRINT((ndo, " newid")); INTOUT(); break; case 520: /* Update entry */ ND_PRINT((ndo, " id")); INTOUT(); STROUT(PRNAMEMAX); break; default: ; } return; trunc: ND_PRINT((ndo, " [|pt]")); } /* * Handle replies to the AFS protection service */ static void prot_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; unsigned long i; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ptserver/ptint.xg. Check to see if it's a * Ubik call, however. */ ND_PRINT((ndo, " pt")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(pt_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 504: /* Name to ID */ { unsigned long j; ND_PRINT((ndo, " ids:")); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (j = 0; j < i; j++) INTOUT(); if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 505: /* ID to name */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); /* * Who designed this chicken-shit protocol? * * Each character is stored as a 32-bit * integer! */ for (i = 0; i < j; i++) { VECOUT(PRNAMEMAX); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 508: /* Get CPS */ case 514: /* List elements */ case 517: /* List owned */ case 518: /* Get CPS2 */ case 519: /* Get host CPS */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { INTOUT(); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 510: /* List max */ ND_PRINT((ndo, " maxuid")); INTOUT(); ND_PRINT((ndo, " maxgid")); INTOUT(); break; default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|pt]")); } /* * Handle calls to the AFS volume location database service */ static void vldb_print(netdissect_options *ndo, register const u_char *bp, int length) { int vldb_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from vlserver/vldbint.xg */ vldb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " vldb")); if (is_ubik(vldb_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(vldb_req, "op#%d", vldb_op))); /* * Decode some of the arguments to the VLDB calls */ bp += sizeof(struct rx_header) + 4; switch (vldb_op) { case 501: /* Create new volume */ case 517: /* Create entry N */ VECOUT(VLNAMEMAX); break; case 502: /* Delete entry */ case 503: /* Get entry by ID */ case 507: /* Update entry */ case 508: /* Set lock */ case 509: /* Release lock */ case 518: /* Get entry by ID N */ ND_PRINT((ndo, " volid")); INTOUT(); ND_TCHECK2(bp[0], sizeof(int32_t)); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (i <= 2) ND_PRINT((ndo, " type %s", voltype[i])); break; case 504: /* Get entry by name */ case 519: /* Get entry by name N */ case 524: /* Update entry by name */ case 527: /* Get entry by name U */ STROUT(VLNAMEMAX); break; case 505: /* Get new vol id */ ND_PRINT((ndo, " bump")); INTOUT(); break; case 506: /* Replace entry */ case 520: /* Replace entry N */ ND_PRINT((ndo, " volid")); INTOUT(); ND_TCHECK2(bp[0], sizeof(int32_t)); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (i <= 2) ND_PRINT((ndo, " type %s", voltype[i])); VECOUT(VLNAMEMAX); break; case 510: /* List entry */ case 521: /* List entry N */ ND_PRINT((ndo, " index")); INTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|vldb]")); } /* * Handle replies to the AFS volume location database service */ static void vldb_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; unsigned long i; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from vlserver/vldbint.xg. Check to see if it's a * Ubik call, however. */ ND_PRINT((ndo, " vldb")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(vldb_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 510: /* List entry */ ND_PRINT((ndo, " count")); INTOUT(); ND_PRINT((ndo, " nextindex")); INTOUT(); /*FALLTHROUGH*/ case 503: /* Get entry by id */ case 504: /* Get entry by name */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_TCHECK2(bp[0], sizeof(int32_t)); bp += sizeof(int32_t); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 8; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); if (i < nservers) ND_PRINT((ndo, " %s", intoa(((const struct in_addr *) bp)->s_addr))); bp += sizeof(int32_t); } ND_PRINT((ndo, " partitions")); for (i = 0; i < 8; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 8 * sizeof(int32_t)); bp += 8 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } break; case 505: /* Get new volume ID */ ND_PRINT((ndo, " newvol")); UINTOUT(); break; case 521: /* List entry */ case 529: /* List entry U */ ND_PRINT((ndo, " count")); INTOUT(); ND_PRINT((ndo, " nextindex")); INTOUT(); /*FALLTHROUGH*/ case 518: /* Get entry by ID N */ case 519: /* Get entry by name N */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); if (i < nservers) ND_PRINT((ndo, " %s", intoa(((const struct in_addr *) bp)->s_addr))); bp += sizeof(int32_t); } ND_PRINT((ndo, " partitions")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 13 * sizeof(int32_t)); bp += 13 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } break; case 526: /* Get entry by ID U */ case 527: /* Get entry by name U */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 13; i++) { if (i < nservers) { ND_PRINT((ndo, " afsuuid")); AFSUUIDOUT(); } else { ND_TCHECK2(bp[0], 44); bp += 44; } } ND_TCHECK2(bp[0], 4 * 13); bp += 4 * 13; ND_PRINT((ndo, " partitions")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 13 * sizeof(int32_t)); bp += 13 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|vldb]")); } /* * Handle calls to the AFS Kerberos Authentication service */ static void kauth_print(netdissect_options *ndo, register const u_char *bp, int length) { int kauth_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from kauth/kauth.rg */ kauth_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " kauth")); if (is_ubik(kauth_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(kauth_req, "op#%d", kauth_op))); /* * Decode some of the arguments to the KA calls */ bp += sizeof(struct rx_header) + 4; switch (kauth_op) { case 1: /* Authenticate old */ case 21: /* Authenticate */ case 22: /* Authenticate-V2 */ case 2: /* Change PW */ case 5: /* Set fields */ case 6: /* Create user */ case 7: /* Delete user */ case 8: /* Get entry */ case 14: /* Unlock */ case 15: /* Lock status */ ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); break; case 3: /* GetTicket-old */ case 23: /* GetTicket */ { int i; ND_PRINT((ndo, " kvno")); INTOUT(); ND_PRINT((ndo, " domain")); STROUT(KANAMEMAX); ND_TCHECK2(bp[0], sizeof(int32_t)); i = (int) EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); bp += i; ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); break; } case 4: /* Set Password */ ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); ND_PRINT((ndo, " kvno")); INTOUT(); break; case 12: /* Get password */ ND_PRINT((ndo, " name")); STROUT(KANAMEMAX); break; default: ; } return; trunc: ND_PRINT((ndo, " [|kauth]")); } /* * Handle replies to the AFS Kerberos Authentication Service */ static void kauth_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from kauth/kauth.rg */ ND_PRINT((ndo, " kauth")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(kauth_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) /* Well, no, not really. Leave this for later */ ; else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|kauth]")); } /* * Handle calls to the AFS Volume location service */ static void vol_print(netdissect_options *ndo, register const u_char *bp, int length) { int vol_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ vol_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " vol call %s", tok2str(vol_req, "op#%d", vol_op))); bp += sizeof(struct rx_header) + 4; switch (vol_op) { case 100: /* Create volume */ ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " parent")); UINTOUT(); break; case 101: /* Delete volume */ case 107: /* Get flags */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 102: /* Restore */ ND_PRINT((ndo, " totrans")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 103: /* Forward */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); DESTSERVEROUT(); ND_PRINT((ndo, " desttrans")); INTOUT(); break; case 104: /* End trans */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 105: /* Clone */ ND_PRINT((ndo, " trans")); UINTOUT(); ND_PRINT((ndo, " purgevol")); UINTOUT(); ND_PRINT((ndo, " newtype")); UINTOUT(); ND_PRINT((ndo, " newname")); STROUT(AFSNAMEMAX); break; case 106: /* Set flags */ ND_PRINT((ndo, " trans")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 108: /* Trans create */ ND_PRINT((ndo, " vol")); UINTOUT(); ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 109: /* Dump */ case 655537: /* Get size */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); break; case 110: /* Get n-th volume */ ND_PRINT((ndo, " index")); UINTOUT(); break; case 111: /* Set forwarding */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " newsite")); UINTOUT(); break; case 112: /* Get name */ case 113: /* Get status */ ND_PRINT((ndo, " tid")); break; case 114: /* Signal restore */ ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " pid")); UINTOUT(); ND_PRINT((ndo, " cloneid")); UINTOUT(); break; case 116: /* List volumes */ ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 117: /* Set id types */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " pid")); UINTOUT(); ND_PRINT((ndo, " clone")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); break; case 119: /* Partition info */ ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); break; case 120: /* Reclone */ ND_PRINT((ndo, " tid")); UINTOUT(); break; case 121: /* List one volume */ case 122: /* Nuke volume */ case 124: /* Extended List volumes */ case 125: /* Extended List one volume */ case 65536: /* Convert RO to RW volume */ ND_PRINT((ndo, " partid")); UINTOUT(); ND_PRINT((ndo, " volid")); UINTOUT(); break; case 123: /* Set date */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " date")); DATEOUT(); break; case 126: /* Set info */ ND_PRINT((ndo, " tid")); UINTOUT(); break; case 128: /* Forward multiple */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); { unsigned long i, j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { DESTSERVEROUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 65538: /* Dump version 2 */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|vol]")); } /* * Handle replies to the AFS Volume Service */ static void vol_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ ND_PRINT((ndo, " vol reply %s", tok2str(vol_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) { switch (opcode) { case 100: /* Create volume */ ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " trans")); UINTOUT(); break; case 104: /* End transaction */ UINTOUT(); break; case 105: /* Clone */ ND_PRINT((ndo, " newvol")); UINTOUT(); break; case 107: /* Get flags */ UINTOUT(); break; case 108: /* Transaction create */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 110: /* Get n-th volume */ ND_PRINT((ndo, " volume")); UINTOUT(); ND_PRINT((ndo, " partition")); UINTOUT(); break; case 112: /* Get name */ STROUT(AFSNAMEMAX); break; case 113: /* Get status */ ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " nextuniq")); UINTOUT(); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " parentid")); UINTOUT(); ND_PRINT((ndo, " clone")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); ND_PRINT((ndo, " restore")); UINTOUT(); ND_PRINT((ndo, " maxquota")); UINTOUT(); ND_PRINT((ndo, " minquota")); UINTOUT(); ND_PRINT((ndo, " owner")); UINTOUT(); ND_PRINT((ndo, " create")); DATEOUT(); ND_PRINT((ndo, " access")); DATEOUT(); ND_PRINT((ndo, " update")); DATEOUT(); ND_PRINT((ndo, " expire")); DATEOUT(); ND_PRINT((ndo, " backup")); DATEOUT(); ND_PRINT((ndo, " copy")); DATEOUT(); break; case 115: /* Old list partitions */ break; case 116: /* List volumes */ case 121: /* List one volume */ { unsigned long i, j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { ND_PRINT((ndo, " name")); VECOUT(32); ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " type")); bp += sizeof(int32_t) * 21; if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; default: ; } } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|vol]")); } /* * Handle calls to the AFS BOS service */ static void bos_print(netdissect_options *ndo, register const u_char *bp, int length) { int bos_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from bozo/bosint.xg */ bos_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " bos call %s", tok2str(bos_req, "op#%d", bos_op))); /* * Decode some of the arguments to the BOS calls */ bp += sizeof(struct rx_header) + 4; switch (bos_op) { case 80: /* Create B node */ ND_PRINT((ndo, " type")); STROUT(BOSNAMEMAX); ND_PRINT((ndo, " instance")); STROUT(BOSNAMEMAX); break; case 81: /* Delete B node */ case 83: /* Get status */ case 85: /* Get instance info */ case 87: /* Add super user */ case 88: /* Delete super user */ case 93: /* Set cell name */ case 96: /* Add cell host */ case 97: /* Delete cell host */ case 104: /* Restart */ case 106: /* Uninstall */ case 108: /* Exec */ case 112: /* Getlog */ case 114: /* Get instance strings */ STROUT(BOSNAMEMAX); break; case 82: /* Set status */ case 98: /* Set T status */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " status")); INTOUT(); break; case 86: /* Get instance parm */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " num")); INTOUT(); break; case 84: /* Enumerate instance */ case 89: /* List super users */ case 90: /* List keys */ case 91: /* Add key */ case 92: /* Delete key */ case 95: /* Get cell host */ INTOUT(); break; case 105: /* Install */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " size")); INTOUT(); ND_PRINT((ndo, " flags")); INTOUT(); ND_PRINT((ndo, " date")); INTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|bos]")); } /* * Handle replies to the AFS BOS Service */ static void bos_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ ND_PRINT((ndo, " bos reply %s", tok2str(bos_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) /* Well, no, not really. Leave this for later */ ; else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|bos]")); } /* * Check to see if this is a Ubik opcode. */ static int is_ubik(uint32_t opcode) { if ((opcode >= VOTE_LOW && opcode <= VOTE_HIGH) || (opcode >= DISK_LOW && opcode <= DISK_HIGH)) return(1); else return(0); } /* * Handle Ubik opcodes to any one of the replicated database services */ static void ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ /* Every function that calls this function first makes a bounds check * for (sizeof(rx_header) + 4) bytes, so long as it remains this way * the line below will not over-read. */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no")); ND_PRINT((ndo, " votestart")); DATEOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, " site")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_TCHECK_32BITS(bp); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, "type %d", temp); break; case 20003: /* Write */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, " file")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " oldversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " newversion")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|ubik]")); } /* * Handle Ubik replies to any one of the replicated database services */ static void ubik_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the ubik call we're invoking. This table was gleaned * from ubik/ubik_int.xg */ ND_PRINT((ndo, " ubik reply %s", tok2str(ubik_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, print out the arguments to the Ubik calls */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 10000: /* Beacon */ ND_PRINT((ndo, " vote no")); break; case 20004: /* Get version */ ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; default: ; } /* * Otherwise, print out "yes" it it was a beacon packet (because * that's how yes votes are returned, go figure), otherwise * just print out the error code. */ else switch (opcode) { case 10000: /* Beacon */ ND_PRINT((ndo, " vote yes until")); DATEOUT(); break; default: ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|ubik]")); } /* * Handle RX ACK packets. */ static void rx_ack_print(netdissect_options *ndo, register const u_char *bp, int length) { const struct rx_ackPacket *rxa; int i, start, last; uint32_t firstPacket; if (length < (int)sizeof(struct rx_header)) return; bp += sizeof(struct rx_header); /* * This may seem a little odd .... the rx_ackPacket structure * contains an array of individual packet acknowledgements * (used for selective ack/nack), but since it's variable in size, * we don't want to truncate based on the size of the whole * rx_ackPacket structure. */ ND_TCHECK2(bp[0], sizeof(struct rx_ackPacket) - RX_MAXACKS); rxa = (const struct rx_ackPacket *) bp; bp += (sizeof(struct rx_ackPacket) - RX_MAXACKS); /* * Print out a few useful things from the ack packet structure */ if (ndo->ndo_vflag > 2) ND_PRINT((ndo, " bufspace %d maxskew %d", (int) EXTRACT_16BITS(&rxa->bufferSpace), (int) EXTRACT_16BITS(&rxa->maxSkew))); firstPacket = EXTRACT_32BITS(&rxa->firstPacket); ND_PRINT((ndo, " first %d serial %d reason %s", firstPacket, EXTRACT_32BITS(&rxa->serial), tok2str(rx_ack_reasons, "#%d", (int) rxa->reason))); /* * Okay, now we print out the ack array. The way _this_ works * is that we start at "first", and step through the ack array. * If we have a contiguous range of acks/nacks, try to * collapse them into a range. * * If you're really clever, you might have noticed that this * doesn't seem quite correct. Specifically, due to structure * padding, sizeof(struct rx_ackPacket) - RX_MAXACKS won't actually * yield the start of the ack array (because RX_MAXACKS is 255 * and the structure will likely get padded to a 2 or 4 byte * boundary). However, this is the way it's implemented inside * of AFS - the start of the extra fields are at * sizeof(struct rx_ackPacket) - RX_MAXACKS + nAcks, which _isn't_ * the exact start of the ack array. Sigh. That's why we aren't * using bp, but instead use rxa->acks[]. But nAcks gets added * to bp after this, so bp ends up at the right spot. Go figure. */ if (rxa->nAcks != 0) { ND_TCHECK2(bp[0], rxa->nAcks); /* * Sigh, this is gross, but it seems to work to collapse * ranges correctly. */ for (i = 0, start = last = -2; i < rxa->nAcks; i++) if (rxa->acks[i] == RX_ACK_TYPE_ACK) { /* * I figured this deserved _some_ explanation. * First, print "acked" and the packet seq * number if this is the first time we've * seen an acked packet. */ if (last == -2) { ND_PRINT((ndo, " acked %d", firstPacket + i)); start = i; } /* * Otherwise, if there is a skip in * the range (such as an nacked packet in * the middle of some acked packets), * then print the current packet number * seperated from the last number by * a comma. */ else if (last != i - 1) { ND_PRINT((ndo, ",%d", firstPacket + i)); start = i; } /* * We always set last to the value of * the last ack we saw. Conversely, start * is set to the value of the first ack * we saw in a range. */ last = i; /* * Okay, this bit a code gets executed when * we hit a nack ... in _this_ case we * want to print out the range of packets * that were acked, so we need to print * the _previous_ packet number seperated * from the first by a dash (-). Since we * already printed the first packet above, * just print the final packet. Don't * do this if there will be a single-length * range. */ } else if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); /* * So, what's going on here? We ran off the end of the * ack list, and if we got a range we need to finish it up. * So we need to determine if the last packet in the list * was an ack (if so, then last will be set to it) and * we need to see if the last range didn't start with the * last packet (because if it _did_, then that would mean * that the packet number has already been printed and * we don't need to print it again). */ if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); /* * Same as above, just without comments */ for (i = 0, start = last = -2; i < rxa->nAcks; i++) if (rxa->acks[i] == RX_ACK_TYPE_NACK) { if (last == -2) { ND_PRINT((ndo, " nacked %d", firstPacket + i)); start = i; } else if (last != i - 1) { ND_PRINT((ndo, ",%d", firstPacket + i)); start = i; } last = i; } else if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); bp += rxa->nAcks; } /* * These are optional fields; depending on your version of AFS, * you may or may not see them */ #define TRUNCRET(n) if (ndo->ndo_snapend - bp + 1 <= n) return; if (ndo->ndo_vflag > 1) { TRUNCRET(4); ND_PRINT((ndo, " ifmtu")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " maxmtu")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " rwind")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " maxpackets")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|ack]")); } #undef TRUNCRET
./CrossVul/dataset_final_sorted/CWE-125/c/good_264_0
crossvul-cpp_data_good_5296_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is: % % Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } CheckNumberCompactPixels; compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q), exception),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.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); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5296_0
crossvul-cpp_data_bad_2690_0
/* * Copyright (c) 2004 - Michael Richardson <mcr@xelerance.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Extensible Authentication Protocol (EAP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #define EAP_FRAME_TYPE_PACKET 0 #define EAP_FRAME_TYPE_START 1 #define EAP_FRAME_TYPE_LOGOFF 2 #define EAP_FRAME_TYPE_KEY 3 #define EAP_FRAME_TYPE_ENCAP_ASF_ALERT 4 struct eap_frame_t { unsigned char version; unsigned char type; unsigned char length[2]; }; static const struct tok eap_frame_type_values[] = { { EAP_FRAME_TYPE_PACKET, "EAP packet" }, { EAP_FRAME_TYPE_START, "EAPOL start" }, { EAP_FRAME_TYPE_LOGOFF, "EAPOL logoff" }, { EAP_FRAME_TYPE_KEY, "EAPOL key" }, { EAP_FRAME_TYPE_ENCAP_ASF_ALERT, "Encapsulated ASF alert" }, { 0, NULL} }; /* RFC 3748 */ struct eap_packet_t { unsigned char code; unsigned char id; unsigned char length[2]; }; #define EAP_REQUEST 1 #define EAP_RESPONSE 2 #define EAP_SUCCESS 3 #define EAP_FAILURE 4 static const struct tok eap_code_values[] = { { EAP_REQUEST, "Request" }, { EAP_RESPONSE, "Response" }, { EAP_SUCCESS, "Success" }, { EAP_FAILURE, "Failure" }, { 0, NULL} }; #define EAP_TYPE_NO_PROPOSED 0 #define EAP_TYPE_IDENTITY 1 #define EAP_TYPE_NOTIFICATION 2 #define EAP_TYPE_NAK 3 #define EAP_TYPE_MD5_CHALLENGE 4 #define EAP_TYPE_OTP 5 #define EAP_TYPE_GTC 6 #define EAP_TYPE_TLS 13 /* RFC 2716 */ #define EAP_TYPE_SIM 18 /* RFC 4186 */ #define EAP_TYPE_TTLS 21 /* draft-funk-eap-ttls-v0-01.txt */ #define EAP_TYPE_AKA 23 /* RFC 4187 */ #define EAP_TYPE_FAST 43 /* RFC 4851 */ #define EAP_TYPE_EXPANDED_TYPES 254 #define EAP_TYPE_EXPERIMENTAL 255 static const struct tok eap_type_values[] = { { EAP_TYPE_NO_PROPOSED, "No proposed" }, { EAP_TYPE_IDENTITY, "Identity" }, { EAP_TYPE_NOTIFICATION, "Notification" }, { EAP_TYPE_NAK, "Nak" }, { EAP_TYPE_MD5_CHALLENGE, "MD5-challenge" }, { EAP_TYPE_OTP, "OTP" }, { EAP_TYPE_GTC, "GTC" }, { EAP_TYPE_TLS, "TLS" }, { EAP_TYPE_SIM, "SIM" }, { EAP_TYPE_TTLS, "TTLS" }, { EAP_TYPE_AKA, "AKA" }, { EAP_TYPE_FAST, "FAST" }, { EAP_TYPE_EXPANDED_TYPES, "Expanded types" }, { EAP_TYPE_EXPERIMENTAL, "Experimental" }, { 0, NULL} }; #define EAP_TLS_EXTRACT_BIT_L(x) (((x)&0x80)>>7) /* RFC 2716 - EAP TLS bits */ #define EAP_TLS_FLAGS_LEN_INCLUDED (1 << 7) #define EAP_TLS_FLAGS_MORE_FRAGMENTS (1 << 6) #define EAP_TLS_FLAGS_START (1 << 5) static const struct tok eap_tls_flags_values[] = { { EAP_TLS_FLAGS_LEN_INCLUDED, "L bit" }, { EAP_TLS_FLAGS_MORE_FRAGMENTS, "More fragments bit"}, { EAP_TLS_FLAGS_START, "Start bit"}, { 0, NULL} }; #define EAP_TTLS_VERSION(x) ((x)&0x07) /* EAP-AKA and EAP-SIM - RFC 4187 */ #define EAP_AKA_CHALLENGE 1 #define EAP_AKA_AUTH_REJECT 2 #define EAP_AKA_SYNC_FAILURE 4 #define EAP_AKA_IDENTITY 5 #define EAP_SIM_START 10 #define EAP_SIM_CHALLENGE 11 #define EAP_AKA_NOTIFICATION 12 #define EAP_AKA_REAUTH 13 #define EAP_AKA_CLIENT_ERROR 14 static const struct tok eap_aka_subtype_values[] = { { EAP_AKA_CHALLENGE, "Challenge" }, { EAP_AKA_AUTH_REJECT, "Auth reject" }, { EAP_AKA_SYNC_FAILURE, "Sync failure" }, { EAP_AKA_IDENTITY, "Identity" }, { EAP_SIM_START, "Start" }, { EAP_SIM_CHALLENGE, "Challenge" }, { EAP_AKA_NOTIFICATION, "Notification" }, { EAP_AKA_REAUTH, "Reauth" }, { EAP_AKA_CLIENT_ERROR, "Client error" }, { 0, NULL} }; /* * Print EAP requests / responses */ void eap_print(netdissect_options *ndo, register const u_char *cp, u_int length) { const struct eap_frame_t *eap; const u_char *tptr; u_int tlen, type, subtype; int count=0, len; tptr = cp; tlen = length; eap = (const struct eap_frame_t *)cp; ND_TCHECK(*eap); /* in non-verbose mode just lets print the basic info */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); return; } ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); tptr += sizeof(const struct eap_frame_t); tlen -= sizeof(const struct eap_frame_t); switch (eap->type) { case EAP_FRAME_TYPE_PACKET: type = *(tptr); len = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, ", %s (%u), id %u, len %u", tok2str(eap_code_values, "unknown", type), type, *(tptr+1), len)); ND_TCHECK2(*tptr, len); if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */ subtype = *(tptr+4); ND_PRINT((ndo, "\n\t\t Type %s (%u)", tok2str(eap_type_values, "unknown", *(tptr+4)), *(tptr + 4))); switch (subtype) { case EAP_TYPE_IDENTITY: if (len - 5 > 0) { ND_PRINT((ndo, ", Identity: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NOTIFICATION: if (len - 5 > 0) { ND_PRINT((ndo, ", Notification: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NAK: count = 5; /* * one or more octets indicating * the desired authentication * type one octet per type */ while (count < len) { ND_PRINT((ndo, " %s (%u),", tok2str(eap_type_values, "unknown", *(tptr+count)), *(tptr + count))); count++; } break; case EAP_TYPE_TTLS: ND_PRINT((ndo, " TTLSv%u", EAP_TTLS_VERSION(*(tptr + 5)))); /* fall through */ case EAP_TYPE_TLS: ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } break; case EAP_TYPE_FAST: ND_PRINT((ndo, " FASTv%u", EAP_TTLS_VERSION(*(tptr + 5)))); ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } /* FIXME - TLV attributes follow */ break; case EAP_TYPE_AKA: case EAP_TYPE_SIM: ND_PRINT((ndo, " subtype [%s] 0x%02x,", tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)), *(tptr + 5))); /* FIXME - TLV attributes follow */ break; case EAP_TYPE_MD5_CHALLENGE: case EAP_TYPE_OTP: case EAP_TYPE_GTC: case EAP_TYPE_EXPANDED_TYPES: case EAP_TYPE_EXPERIMENTAL: default: break; } } break; case EAP_FRAME_TYPE_LOGOFF: case EAP_FRAME_TYPE_ENCAP_ASF_ALERT: default: break; } return; trunc: ND_PRINT((ndo, "\n\t[|EAP]")); } /* * Local Variables: * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2690_0
crossvul-cpp_data_bad_5297_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR L EEEEE % % R R L E % % RRRR L EEE % % R R L E % % R R LLLLL EEEEE % % % % % % Read URT RLE Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 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/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s R L E % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsRLE() returns MagickTrue if the image format type, identified by the % magick string, is RLE. % % The format of the ReadRLEImage method is: % % MagickBooleanType IsRLE(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 IsRLE(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\122\314",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d R L E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadRLEImage() reads a run-length encoded Utah Raster Toolkit % 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 ReadRLEImage method is: % % Image *ReadRLEImage(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 *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4); pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r R L E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterRLEImage() adds attributes for the RLE image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterRLEImage method is: % % size_t RegisterRLEImage(void) % */ ModuleExport size_t RegisterRLEImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("RLE","RLE","Utah Run length encoded image"); entry->decoder=(DecodeImageHandler *) ReadRLEImage; entry->magick=(IsImageFormatHandler *) IsRLE; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r R L E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterRLEImage() removes format registrations made by the % RLE module from the list of supported formats. % % The format of the UnregisterRLEImage method is: % % UnregisterRLEImage(void) % */ ModuleExport void UnregisterRLEImage(void) { (void) UnregisterMagickInfo("RLE"); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5297_0
crossvul-cpp_data_good_923_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % 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/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; 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); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const Image *image,const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p++; } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(image,histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property); return(BilevelImage(image,QuantumRange*threshold/100.0)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if ((channel & SyncChannels) != 0) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); q++; } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex( indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attribute, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *) NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(map); for (threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { attribute=GetXMLTreeAttribute(threshold, "map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold, "alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } /* The map has been found -- allocate a Threshold Map to return */ map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; /* Assign basic attributeibutes. */ attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels, "divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array. */ content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { char *p; register ssize_t i; /* Parse levels into integer array. */ for (i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; 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); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,ClampToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } if (SyncCacheViewAuthenticPixels(image_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,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImageChannel method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon) % MagickBooleanType PerceptibleImageChannel(Image *image, % const ChannelType channel,const double epsilon) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon) { MagickBooleanType status; status=PerceptibleImageChannel(image,DefaultChannels,epsilon); return(status); } MagickExport MagickBooleanType PerceptibleImageChannel(Image *image, const ChannelType channel,const double epsilon) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); q++; } return(SyncImage(image)); } /* Perceptible image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x), epsilon)); q++; } if (SyncCacheViewAuthenticPixels(image_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,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { IndexPacket index; MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_923_0
crossvul-cpp_data_bad_3293_0
/* radare2 - LGPL - Copyright 2017 - pancake, cgvwzq */ #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include "wasm.h" // Consume functions static size_t consume_u32 (ut8 *buf, ut8 *max, ut32 *out, ut32 *offset) { size_t n; if (!buf || !max || !out) { return 0; } if (!(n = read_u32_leb128 (buf, max, out)) || n > 5) { return 0; } if (offset) { *offset += n; } return n; } static size_t consume_s32 (ut8 *buf, ut8 *max, st32 *out, ut32 *offset) { size_t n; if (!buf || !max || !out) { return 0; } if (!(n = read_i32_leb128 (buf, max, out)) || n > 5) { return 0; } if (offset) { *offset += n; } return n; } static size_t consume_u8 (ut8 *buf, ut8 *max, ut8 *out, ut32 *offset) { size_t n; ut32 tmp; if (!(n = consume_u32 (buf, max, &tmp, offset)) || n > 1) { return 0; } *out = tmp & 0x7f; return 1; } static size_t consume_s8 (ut8 *buf, ut8 *max, st8 *out, ut32 *offset) { size_t n; ut32 tmp; if (!(n = consume_u32 (buf, max, &tmp, offset)) || n > 1) { return 0; } *out = (st8)(tmp & 0x7f); return 1; } static size_t consume_str (ut8 *buf, ut8 *max, size_t sz, char *out, ut32 *offset) { if (!buf || !max || !out || !sz) { return 0; } if (!(buf + sz < max)) { return 0; } strncpy ((char*)out, (char*)buf, R_MIN (R_BIN_WASM_STRING_LENGTH-1, sz)); if (offset) *offset += sz; return sz; } static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { // TODO: calc the expresion with the bytcode (ESIL?) i += 1; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; } static size_t consume_locals (ut8 *buf, ut8 *max, ut32 count, RBinWasmCodeEntry *out, ut32 *offset) { ut32 i = 0, j = 0; if (count < 1) return 0; // memory leak if (!(out->locals = (struct r_bin_wasm_local_entry_t*) malloc (sizeof(struct r_bin_wasm_local_entry_t) * count))) { return 0; } while (buf + i < max && j < count) { if (!(consume_u32 (buf + i, max, &out->locals[j].count, &i))) { free (out->locals); return 0; } if (!(consume_s8 (buf + i, max, (st8*)&out->locals[j].type, &i))) { free (out->locals); return 0; } j += 1; } if (offset) *offset += i; return j; } static size_t consume_limits (ut8 *buf, ut8 *max, struct r_bin_wasm_resizable_limits_t *out, ut32 *offset) { ut32 i = 0; if (!(consume_u8 (buf + i, max, &out->flags, &i))) return 0; if (!(consume_u32 (buf + i, max, &out->initial, &i))) return 0; if (out->flags && (!(consume_u32 (buf + i, max, &out->maximum, &i)))) return 0; if (offset) *offset += i; return i; } // Utils static RList *r_bin_wasm_get_sections_by_id (RList *sections, ut8 id) { RBinWasmSection *sec = NULL; RList *ret = NULL; RListIter *iter = NULL; // memory leak if (!(ret = r_list_new ())) { return NULL; } r_list_foreach (sections, iter, sec) { if (sec->id == id) { r_list_append(ret, sec); } } return ret; } #define R_BIN_WASM_VALUETYPETOSTRING(p, type, i) {\ switch(type) {\ case R_BIN_WASM_VALUETYPE_i32:\ strcpy(p, "i32");\ break;\ case R_BIN_WASM_VALUETYPE_i64:\ strcpy(p, "i64");\ break;\ case R_BIN_WASM_VALUETYPE_f32:\ strcpy(p, "f32");\ break;\ case R_BIN_WASM_VALUETYPE_f64:\ strcpy(p, "f64");\ break;\ }\ i+= 3;\ } static char *r_bin_wasm_type_entry_to_string (RBinWasmTypeEntry *ptr) { if (!ptr || ptr->to_str) { return NULL; } char *ret; int p, i = 0, sz; sz = (ptr->param_count + ptr->return_count) * 5 + 9; // memory leak if (!(ret = (char*) malloc (sz * sizeof(char)))) { return NULL; } strcpy (ret + i, "("); i++; for (p = 0; p < ptr->param_count; p++ ) { R_BIN_WASM_VALUETYPETOSTRING (ret+i, ptr->param_types[p], i); // i+=3 if (p < ptr->param_count - 1) { strcpy (ret+i, ", "); i += 2; } } strcpy (ret + i, ") -> ("); i += 6; if (ptr->return_count == 1) { R_BIN_WASM_VALUETYPETOSTRING (ret + i, ptr->return_type, i); } strcpy (ret + i, ")"); return ret; } // Parsing static RList *r_bin_wasm_get_type_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmTypeEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmTypeEntry))) { return ret; } if (!(consume_u8 (buf + i, buf + len, &ptr->form, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->param_count, &i))) { free (ptr); return ret; } if (!(i + ptr->param_count < len)) { free (ptr); return ret; } int j; for (j = 0; j < ptr->param_count; j++) { if (!(consume_s8 (buf + i, buf + len, (st8*)&ptr->param_types[j], &i))) { free (ptr); return ret; } } if (!(consume_s8 (buf + i, buf + len, &ptr->return_count, &i))) { free (ptr); return ret; } if (ptr->return_count > 1) { free(ptr); return ret; } if (ptr->return_count == 1) { if (!(consume_s8 (buf + i, buf + len, (st8*)&ptr->return_type, &i))) { free(ptr); return ret; } } ptr->to_str = r_bin_wasm_type_entry_to_string (ptr); r_list_append (ret, ptr); r += 1; } return ret; } static RList *r_bin_wasm_get_import_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmImportEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmImportEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->module_len, &i))) { goto culvert; } if (!(consume_str (buf + i, buf + len, ptr->module_len, ptr->module_str, &i))) { goto culvert; } if (!(consume_u32 (buf + i, buf + len, &ptr->field_len, &i))) { goto culvert; } if (!(consume_str (buf + i, buf + len, ptr->field_len, ptr->field_str, &i))) { goto culvert; } if (!(consume_u8 (buf + i, buf + len, &ptr->kind, &i))) { goto culvert; } switch (ptr->kind) { case 0: // Function if (!(consume_u32 (buf + i, buf + len, &ptr->type_f, &i))) { goto sewer; } break; case 1: // Table if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_t.elem_type, &i))) { goto sewer; // varint7 } if (!(consume_limits (buf + i, buf + len, &ptr->type_t.limits, &i))) { goto sewer; } break; case 2: // Memory if (!(consume_limits (buf + i, buf + len, &ptr->type_m.limits, &i))) { goto sewer; } break; case 3: // Global if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.content_type, &i))) { goto sewer; // varint7 } if (!(consume_u8 (buf + i, buf + len, (ut8*)&ptr->type_g.mutability, &i))) { goto sewer; // varuint1 } break; default: goto sewer; } r_list_append (ret, ptr); r++; } return ret; sewer: ret = NULL; culvert: free (ptr); return ret; } static RList *r_bin_wasm_get_export_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmExportEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmExportEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->field_len, &i))) { free (ptr); return ret; } if (!(consume_str (buf + i, buf + len, ptr->field_len, ptr->field_str, &i))) { free (ptr); return ret; } if (!(consume_u8 (buf + i, buf + len, &ptr->kind, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } r_list_append (ret, ptr); r++; } return ret; } static RList *r_bin_wasm_get_code_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmCodeEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, j = 0, r = 0; size_t n = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmCodeEntry))) { return ret; } if (!(n = consume_u32 (buf + i, buf + len, &ptr->body_size, &i))) { free (ptr); return ret; } if (!(i + ptr->body_size - 1 < len)) { free (ptr); return ret; } j = i; if (!(n = consume_u32 (buf + i, buf + len, &ptr->local_count, &i))) { free (ptr); return ret; } if ((n = consume_locals (buf + i, buf + len, ptr->local_count,ptr, &i)) < ptr->local_count) { free (ptr); return ret; } ptr->code = sec->payload_data + i; ptr->len = ptr->body_size - (i - j); i += ptr->len - 1; // consume bytecode if (!(consume_u8 (buf + i, buf + len, &ptr->byte, &i))) { free (ptr); return ret; } if (ptr->byte != R_BIN_WASM_END_OF_CODE) { free (ptr); return ret; } // search 'r' in function_space, if present get signature from types // if export get name r_list_append (ret, ptr); r += 1; } return ret; } static RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmDataEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; size_t n = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmDataEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } ptr->offset.len = n; if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { free (ptr); return ret; } ptr->data = sec->payload_data + i; r_list_append (ret, ptr); r += 1; } return ret; } static RBinWasmStartEntry *r_bin_wasm_get_start (RBinWasmObj *bin, RBinWasmSection *sec) { RBinWasmStartEntry *ptr; if (!(ptr = R_NEW0 (RBinWasmStartEntry))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 i = 0; if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return NULL; } return ptr; } static RList *r_bin_wasm_get_memory_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmMemoryEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmMemoryEntry))) { return ret; } if (!(consume_limits (buf + i, buf + len, &ptr->limits, &i))) { free (ptr); return ret; } r_list_append (ret, ptr); r += 1; } return ret; } static RList *r_bin_wasm_get_table_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmTableEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmTableEntry))) { return ret; } if (!(consume_u8 (buf + i, buf + len, &ptr->element_type, &i))) { free (ptr); return ret; } if (!(consume_limits (buf + i, buf + len, &ptr->limits, &i))) { free (ptr); return ret; } r_list_append (ret, ptr); r += 1; } return ret; } static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; int buflen = bin->buf->length; if (sec->payload_data + 32 > buflen) { return NULL; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; } static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { free (ptr); return ret; } ut32 j = 0; while (i < len && j < ptr->num_elem ) { // TODO: allocate space and fill entry ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; } // Public functions RBinWasmObj *r_bin_wasm_init (RBinFile *arch) { RBinWasmObj *bin = R_NEW0 (RBinWasmObj); if (!bin) { return NULL; } if (!(bin->buf = r_buf_new ())) { free (bin); return NULL; } bin->size = (ut32)arch->buf->length; if (!r_buf_set_bytes (bin->buf, arch->buf->buf, bin->size)) { r_bin_wasm_destroy (arch); free (bin); return NULL; } bin->g_sections = r_bin_wasm_get_sections (bin); // TODO: recursive invocation more natural with streamed parsing // but dependency problems when sections are disordered (against spec) bin->g_types = r_bin_wasm_get_types (bin); bin->g_imports = r_bin_wasm_get_imports (bin); bin->g_exports = r_bin_wasm_get_exports (bin); bin->g_tables = r_bin_wasm_get_tables (bin); bin->g_memories = r_bin_wasm_get_memories (bin); bin->g_globals = r_bin_wasm_get_globals (bin); bin->g_codes = r_bin_wasm_get_codes (bin); bin->g_datas = r_bin_wasm_get_datas (bin); // entrypoint from Start section bin->entrypoint = r_bin_wasm_get_entrypoint (bin); return bin; } void r_bin_wasm_destroy (RBinFile *arch) { RBinWasmObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return; } bin = arch->o->bin_obj; r_buf_free (bin->buf); r_list_free (bin->g_sections); r_list_free (bin->g_types); r_list_free (bin->g_imports); r_list_free (bin->g_exports); r_list_free (bin->g_tables); r_list_free (bin->g_memories); r_list_free (bin->g_globals); r_list_free (bin->g_codes); r_list_free (bin->g_datas); free (bin->g_start); free (bin); arch->o->bin_obj = NULL; } RList *r_bin_wasm_get_sections (RBinWasmObj *bin) { RList *ret = NULL; RBinWasmSection *ptr = NULL; if (!bin) { return NULL; } if (bin->g_sections) { return bin->g_sections; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf; ut32 len = bin->size, i = 8; // skip magic bytes + version while (i < len) { //r_buf_read_* api but it makes sense going through the array directly if (!(ptr = R_NEW0 (RBinWasmSection))) { return ret; } if (!(consume_u8 (buf + i, buf + len, &ptr->id, &i))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { free(ptr); return NULL; } ptr->count = 0; ptr->offset = i; switch (ptr->id) { case R_BIN_WASM_SECTION_CUSTOM: //eprintf("custom section: 0x%x, ", i); if (!(consume_u32 (buf + i, buf + len, &ptr->name_len, &i))) { free(ptr); return ret; } if (!(consume_str (buf + i, buf + len, ptr->name_len, ptr->name, &i))) { free(ptr); return ret; } //eprintf("%s\n", ptr->name); break; case R_BIN_WASM_SECTION_TYPE: //eprintf("section type: 0x%x, ", i); strcpy (ptr->name, "type"); ptr->name_len = 4; break; case R_BIN_WASM_SECTION_IMPORT: //eprintf("section import: 0x%x, ", i); strcpy (ptr->name, "import"); ptr->name_len = 6; break; case R_BIN_WASM_SECTION_FUNCTION: //eprintf("section function: 0x%x, ", i); strcpy (ptr->name, "function"); ptr->name_len = 8; break; case R_BIN_WASM_SECTION_TABLE: //eprintf("section table: 0x%x, ", i); strcpy (ptr->name, "table"); ptr->name_len = 5; break; case R_BIN_WASM_SECTION_MEMORY: //eprintf("section memory: 0x%x, ", i); strcpy (ptr->name, "memory"); ptr->name_len = 6; break; case R_BIN_WASM_SECTION_GLOBAL: //eprintf("section global: 0x%x, ", i); strcpy (ptr->name, "global"); ptr->name_len = 6; break; case R_BIN_WASM_SECTION_EXPORT: //eprintf("section export: 0x%x, ", i); strcpy (ptr->name, "export"); ptr->name_len = 6; break; case R_BIN_WASM_SECTION_START: //eprintf("section start: 0x%x\n", i); strcpy (ptr->name, "start"); ptr->name_len = 5; break; case R_BIN_WASM_SECTION_ELEMENT: //eprintf("section element: 0x%x, ", i); strncpy (ptr->name, "element", R_BIN_WASM_STRING_LENGTH); ptr->name_len = 7; break; case R_BIN_WASM_SECTION_CODE: //eprintf("section code: 0x%x, ", i); strncpy (ptr->name, "code", R_BIN_WASM_STRING_LENGTH); ptr->name_len = 4; break; case R_BIN_WASM_SECTION_DATA: //eprintf("section data: 0x%x, ", i); strncpy (ptr->name, "data", R_BIN_WASM_STRING_LENGTH); ptr->name_len = 4; break; default: eprintf("unkown section id: %d\n", ptr->id); i += ptr->size - 1; // next continue; } if (ptr->id != R_BIN_WASM_SECTION_START && ptr->id != R_BIN_WASM_SECTION_CUSTOM) { if (!(consume_u32 (buf + i, buf + len, &ptr->count, &i))) { free (ptr); return ret; } //eprintf("count %d\n", ptr->count); } ptr->payload_data = i; ptr->payload_len = ptr->size - (i - ptr->offset); r_list_append (ret, ptr); i += ptr->payload_len; // next } bin->g_sections = ret; return ret; } ut32 r_bin_wasm_get_entrypoint (RBinWasmObj *bin) { RList *secs = NULL; RBinWasmStartEntry *start = NULL; RBinWasmSection *sec = NULL; RBinWasmCodeEntry *func = NULL; if (!bin || !bin->g_sections) { return 0; } if (bin->entrypoint) { return bin->entrypoint; } if (bin->g_start) { start = bin->g_start; } else if (!(secs = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_START))) { return 0; } else if (!(sec = (RBinWasmSection*) r_list_first (secs))) { return 0; } else { start = r_bin_wasm_get_start (bin, sec); bin->g_start = start; } if (!start) { return 0; } // FIX: entrypoint can be also an import func = r_list_get_n (r_bin_wasm_get_codes (bin), start->index); return (ut32)func? func->code: 0; } RList *r_bin_wasm_get_imports (RBinWasmObj *bin) { RBinWasmSection *import = NULL; RList *imports = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_imports) { return bin->g_imports; } if (!(imports = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_IMPORT))) { return r_list_new(); } // support for multiple import sections against spec if (!(import = (RBinWasmSection*) r_list_first (imports))) { return r_list_new(); } return bin->g_imports = r_bin_wasm_get_import_entries (bin, import); } RList *r_bin_wasm_get_exports (RBinWasmObj *bin) { RBinWasmSection *export = NULL; RList *exports = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_exports) { return bin->g_exports; } if (!(exports= r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_EXPORT))) { return r_list_new(); } // support for multiple export sections against spec if (!(export = (RBinWasmSection*) r_list_first (exports))) { return r_list_new(); } bin->g_exports = r_bin_wasm_get_export_entries (bin, export); return bin->g_exports; } RList *r_bin_wasm_get_types (RBinWasmObj *bin) { RBinWasmSection *type = NULL; RList *types = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_types) { return bin->g_types; } if (!(types = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_TYPE))) { return r_list_new(); } // support for multiple export sections against spec if (!(type = (RBinWasmSection*) r_list_first (types))) { return r_list_new(); } bin->g_types = r_bin_wasm_get_type_entries (bin, type); return bin->g_types; } RList *r_bin_wasm_get_tables (RBinWasmObj *bin) { RBinWasmSection *table = NULL; RList *tables = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_tables) { return bin->g_tables; } if (!(tables = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_TABLE))) { return r_list_new(); } // support for multiple export sections against spec if (!(table = (RBinWasmSection*) r_list_first (tables))) { r_list_free (tables); return r_list_new(); } bin->g_tables = r_bin_wasm_get_table_entries (bin, table); r_list_free (tables); return bin->g_tables; } RList *r_bin_wasm_get_memories (RBinWasmObj *bin) { RBinWasmSection *memory; RList *memories; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_memories) { return bin->g_memories; } if (!(memories = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_MEMORY))) { return r_list_new(); } // support for multiple export sections against spec if (!(memory = (RBinWasmSection*) r_list_first (memories))) { return r_list_new(); } bin->g_memories = r_bin_wasm_get_memory_entries (bin, memory); return bin->g_memories; } RList *r_bin_wasm_get_globals (RBinWasmObj *bin) { RBinWasmSection *global = NULL; RList *globals = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_globals) { return bin->g_globals; } if (!(globals = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_GLOBAL))) { return r_list_new(); } // support for multiple export sections against spec if (!(global = (RBinWasmSection*) r_list_first (globals))) { return r_list_new(); } bin->g_globals = r_bin_wasm_get_global_entries (bin, global); return bin->g_globals; } RList *r_bin_wasm_get_elements (RBinWasmObj *bin) { RBinWasmSection *element = NULL; RList *elements = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_elements) { return bin->g_elements; } if (!(elements = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_ELEMENT))) { return r_list_new(); } // support for multiple export sections against spec if (!(element = (RBinWasmSection*) r_list_first (elements))) { return r_list_new(); } bin->g_elements = r_bin_wasm_get_element_entries (bin, element); return bin->g_elements; } RList *r_bin_wasm_get_codes (RBinWasmObj *bin) { RBinWasmSection *code = NULL;; RList *codes = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_codes) { return bin->g_codes; } if (!(codes = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_CODE))) { return r_list_new(); } // support for multiple export sections against spec if (!(code = (RBinWasmSection*) r_list_first (codes))) { return r_list_new(); } bin->g_codes = r_bin_wasm_get_code_entries (bin, code); return bin->g_codes; } RList *r_bin_wasm_get_datas (RBinWasmObj *bin) { RBinWasmSection *data = NULL; RList *datas = NULL; if (!bin || !bin->g_sections) { return NULL; } if (bin->g_datas) { return bin->g_datas; } if (!(datas = r_bin_wasm_get_sections_by_id (bin->g_sections, R_BIN_WASM_SECTION_DATA))) { return r_list_new(); } // support for multiple export sections against spec if (!(data = (RBinWasmSection*) r_list_first (datas))) { return r_list_new(); } bin->g_datas = r_bin_wasm_get_data_entries (bin, data); return bin->g_datas; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3293_0
crossvul-cpp_data_bad_2612_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/transform.h" #include "magick/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelPackets all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketOpacity(pixelpacket) \ (pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketOpacity((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed((pixel), \ ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelGreen(pixel) \ (SetPixelGreen((pixel), \ ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelBlue(pixel) \ (SetPixelBlue((pixel), \ ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelOpacity(pixel) \ (SetPixelOpacity((pixel), \ ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBO(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelOpacity((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \ (pixelpacket).opacity=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketOpacity((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xc0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xc0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02Opacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \ SetPixelOpacity((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBO(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02Opacity((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xe0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xe0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelBlue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \ & 0xe0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelRGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03PixelGreen((pixel)); \ LBR03PixelBlue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \ (pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketOpacity((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xf0; \ SetPixelRed((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xf0; \ SetPixelGreen((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \ SetPixelBlue((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelOpacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \ SetPixelOpacity((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBO(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelOpacity((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelPacket mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const PixelPacket *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p++; } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without loss of info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { Image *image; image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError, message,"`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { Image *image; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. */ LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; int i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; /* copy chunk->data to profile */ s=chunk->data; for (i=0; i < (ssize_t) chunk->size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); /* Return one of the following: */ /* return(-n); chunk had an error */ /* return(0); did not recognize */ /* return(n); success */ return(1); } return(0); /* Did not recognize */ } #endif #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; LongPixelPacket transparent_color; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; ssize_t ping_rowbytes, y; register unsigned char *p; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif image=mng_info->image; if (logging != MagickFalse) { (void)LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->matte=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->matte, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.opacity=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) InheritException(exception,&image->exception); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { /* Ignore the iCCP chunk */ png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for exIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1); png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED #if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); #endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); /* Read and check IHDR chunk data */ png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->x_resolution=(double) x_resolution; image->y_resolution=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) x_resolution/100.0; image->y_resolution=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) if (mng_info->global_trns_length) { if (mng_info->global_trns_length > mng_info->global_plte_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n" " bkgd_scale=%d. ping_background=(%d,%d,%d).", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.opacity=OpaqueOpacity; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->matte=MagickFalse; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.opacity= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", ping_trans_color->gray,transparent_color.opacity); } transparent_color.red=transparent_color.opacity; transparent_color.green=transparent_color.opacity; transparent_color.blue=transparent_color.opacity; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = 65535/((1UL << ping_file_depth)-1); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MaxTextExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MaxTextExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method",msg); if (number_colors != 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; else { if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); } if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelOpacity(q) != OpaqueOpacity)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q++; } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? MagickTrue : MagickFalse; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->matte ? 2 : 1)*sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; /* In image.h, OpaqueOpacity is 0 * TransparentOpacity is QuantumRange * In a PNG datastream, Opaque is QuantumRange * and Transparent is 0. */ alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) size_t quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { alpha=*p++; SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; p++; q++; } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*r++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->matte=found_transparent_pixel; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } if (image->storage_class == PseudoClass) { MagickBooleanType matte; matte=image->matte; image->matte=MagickFalse; (void) SyncImage(image); image->matte=matte; } png_read_end(ping,end_info); if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->matte=MagickTrue; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].opacity = ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x])); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.opacity) { image->colormap[x].opacity = (Quantum) TransparentOpacity; } } } (void) SyncImage(image); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue) { SetPixelOpacity(q,TransparentOpacity); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelOpacity(q)=(Quantum) OpaqueOpacity; } #endif q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } if ((ping_color_type == PNG_COLOR_TYPE_GRAY) || (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*value)); if (value == (char *) NULL) png_error(ping,"Memory allocation failed"); *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, &image->exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->matte to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->matte != MagickFalse) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleMatteType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteMatteType); else (void) SetImageType(image,TrueColorMatteType); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType); else (void) SetImageType(image,TrueColorType); } #endif /* Set more properties for identify to retrieve */ { char msg[MaxTextExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MaxTextExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MaxTextExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg); } (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found"); /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg); if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MaxTextExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % To do: Enforce the previous paragraph. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n",mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* To do: use a "LocaleInteger:()" function here. */ /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { Image *jpeg_image; ImageInfo *jpeg_image_info; int unique_filenames; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; unique_filenames=0; status=MagickTrue; transparent=image_info->type==GrayscaleMatteType || image_info->type==TrueColorMatteType || image->matte != MagickFalse; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for opacity."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); status=SeparateImageChannel(jpeg_image,OpacityChannel); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=NegateImage(jpeg_image,MagickFalse); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_image->matte=MagickFalse; jpeg_image_info->type=GrayscaleType; jpeg_image->quality=jng_alpha_quality; (void) SetImageType(jpeg_image,GrayscaleType); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorMatteType && image_info->type != TrueColorType && SetImageGray(image,&image->exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode opacity as a grayscale PNG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); length=0; (void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written"); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode opacity as a grayscale JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating JPEG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->x_resolution && image->y_resolution && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { const char *option; Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->matte) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->matte) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if (next_image->matte || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->matte != MagickFalse) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,&image->exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->x_resolution != next_image->next->x_resolution) || (next_image->y_resolution != next_image->next->y_resolution)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=1UL*image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->x_resolution && image->y_resolution && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && (image->matte || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_eXIf=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2612_0
crossvul-cpp_data_bad_3208_0
/* * Yerase's TNEF Stream Reader Library * Copyright (C) 2003 Randall E. Hand * * 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 * * You can contact me at randall.hand@gmail.com for questions or assistance */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <limits.h> #include "ytnef.h" #include "tnef-errors.h" #include "mapi.h" #include "mapidefs.h" #include "mapitags.h" #include "config.h" #define RTF_PREBUF "{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}{\\f0\\fnil \\froman \\fswiss \\fmodern \\fscript \\fdecor MS Sans SerifSymbolArialTimes New RomanCourier{\\colortbl\\red0\\green0\\blue0\n\r\\par \\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx" #define DEBUG(lvl, curlvl, msg) \ if ((lvl) >= (curlvl)) \ printf("DEBUG(%i/%i): %s\n", curlvl, lvl, msg); #define DEBUG1(lvl, curlvl, msg, var1) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1); \ printf("\n"); \ } #define DEBUG2(lvl, curlvl, msg, var1, var2) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1, var2); \ printf("\n"); \ } #define DEBUG3(lvl, curlvl, msg, var1, var2, var3) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1, var2,var3); \ printf("\n"); \ } #define MIN(x,y) (((x)<(y))?(x):(y)) #define ALLOCCHECK(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(-1); } } #define ALLOCCHECK_CHAR(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(NULL); } } #define SIZECHECK(x) { if ((((char *)d - (char *)data) + x) > size) { printf("Corrupted file detected at %s : %i\n", __FILE__, __LINE__); return(-1); } } int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p); void SetFlip(void); int TNEFDefaultHandler STD_ARGLIST; int TNEFAttachmentFilename STD_ARGLIST; int TNEFAttachmentSave STD_ARGLIST; int TNEFDetailedPrint STD_ARGLIST; int TNEFHexBreakdown STD_ARGLIST; int TNEFBody STD_ARGLIST; int TNEFRendData STD_ARGLIST; int TNEFDateHandler STD_ARGLIST; int TNEFPriority STD_ARGLIST; int TNEFVersion STD_ARGLIST; int TNEFMapiProperties STD_ARGLIST; int TNEFIcon STD_ARGLIST; int TNEFSubjectHandler STD_ARGLIST; int TNEFFromHandler STD_ARGLIST; int TNEFRecipTable STD_ARGLIST; int TNEFAttachmentMAPI STD_ARGLIST; int TNEFSentFor STD_ARGLIST; int TNEFMessageClass STD_ARGLIST; int TNEFMessageID STD_ARGLIST; int TNEFParentID STD_ARGLIST; int TNEFOriginalMsgClass STD_ARGLIST; int TNEFCodePage STD_ARGLIST; BYTE *TNEFFileContents = NULL; DWORD TNEFFileContentsSize; BYTE *TNEFFileIcon = NULL; DWORD TNEFFileIconSize; int IsCompressedRTF(variableLength *p); TNEFHandler TNEFList[] = { {attNull, "Null", TNEFDefaultHandler}, {attFrom, "From", TNEFFromHandler}, {attSubject, "Subject", TNEFSubjectHandler}, {attDateSent, "Date Sent", TNEFDateHandler}, {attDateRecd, "Date Received", TNEFDateHandler}, {attMessageStatus, "Message Status", TNEFDefaultHandler}, {attMessageClass, "Message Class", TNEFMessageClass}, {attMessageID, "Message ID", TNEFMessageID}, {attParentID, "Parent ID", TNEFParentID}, {attConversationID, "Conversation ID", TNEFDefaultHandler}, {attBody, "Body", TNEFBody}, {attPriority, "Priority", TNEFPriority}, {attAttachData, "Attach Data", TNEFAttachmentSave}, {attAttachTitle, "Attach Title", TNEFAttachmentFilename}, {attAttachMetaFile, "Attach Meta-File", TNEFIcon}, {attAttachCreateDate, "Attachment Create Date", TNEFDateHandler}, {attAttachModifyDate, "Attachment Modify Date", TNEFDateHandler}, {attDateModified, "Date Modified", TNEFDateHandler}, {attAttachTransportFilename, "Attachment Transport name", TNEFDefaultHandler}, {attAttachRenddata, "Attachment Display info", TNEFRendData}, {attMAPIProps, "MAPI Properties", TNEFMapiProperties}, {attRecipTable, "Recip Table", TNEFRecipTable}, {attAttachment, "Attachment", TNEFAttachmentMAPI}, {attTnefVersion, "TNEF Version", TNEFVersion}, {attOemCodepage, "OEM CodePage", TNEFCodePage}, {attOriginalMessageClass, "Original Message Class", TNEFOriginalMsgClass}, {attOwner, "Owner", TNEFDefaultHandler}, {attSentFor, "Sent For", TNEFSentFor}, {attDelegate, "Delegate", TNEFDefaultHandler}, {attDateStart, "Date Start", TNEFDateHandler}, {attDateEnd, "Date End", TNEFDateHandler}, {attAidOwner, "Aid Owner", TNEFDefaultHandler}, {attRequestRes, "Request Response", TNEFDefaultHandler} }; WORD SwapWord(BYTE *p, int size) { union BYTES2WORD { WORD word; BYTE bytes[sizeof(WORD)]; }; union BYTES2WORD converter; converter.word = 0; int i = 0; int correct = size > sizeof(WORD) ? sizeof(WORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.word; } DWORD SwapDWord(BYTE *p, int size) { union BYTES2DWORD { DWORD dword; BYTE bytes[sizeof(DWORD)]; }; union BYTES2DWORD converter; converter.dword = 0; int i = 0; int correct = size > sizeof(DWORD) ? sizeof(DWORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.dword; } DDWORD SwapDDWord(BYTE *p, int size) { union BYTES2DDWORD { DDWORD ddword; BYTE bytes[sizeof(DDWORD)]; }; union BYTES2DDWORD converter; converter.ddword = 0; int i = 0; int correct = size > sizeof(DDWORD) ? sizeof(DDWORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.ddword; } /* convert 16-bit unicode to UTF8 unicode */ char *to_utf8(size_t len, char *buf) { int i, j = 0; /* worst case length */ if (len > 10000) { // deal with this by adding an arbitrary limit printf("suspecting a corrupt file in UTF8 conversion\n"); exit(-1); } char *utf8 = malloc(3 * len / 2 + 1); for (i = 0; i < len - 1; i += 2) { unsigned int c = SwapWord((BYTE *)buf + i, 2); if (c <= 0x007f) { utf8[j++] = 0x00 | ((c & 0x007f) >> 0); } else if (c < 0x07ff) { utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); utf8[j++] = 0x80 | ((c & 0x003f) >> 0); } else { utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); utf8[j++] = 0x80 | ((c & 0x003f) >> 0); } } /* just in case the original was not null terminated */ utf8[j++] = '\0'; return utf8; } // ----------------------------------------------------------------------------- int TNEFDefaultHandler STD_ARGLIST { if (TNEF->Debug >= 1) printf("%s: [%i] %s\n", TNEFList[id].name, size, data); return 0; } // ----------------------------------------------------------------------------- int TNEFCodePage STD_ARGLIST { TNEF->CodePage.size = size; TNEF->CodePage.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->CodePage.data); memcpy(TNEF->CodePage.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFParentID STD_ARGLIST { memcpy(TNEF->parentID, data, MIN(size, sizeof(TNEF->parentID))); return 0; } // ----------------------------------------------------------------------------- int TNEFMessageID STD_ARGLIST { memcpy(TNEF->messageID, data, MIN(size, sizeof(TNEF->messageID))); return 0; } // ----------------------------------------------------------------------------- int TNEFBody STD_ARGLIST { TNEF->body.size = size; TNEF->body.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->body.data); memcpy(TNEF->body.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFOriginalMsgClass STD_ARGLIST { TNEF->OriginalMessageClass.size = size; TNEF->OriginalMessageClass.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->OriginalMessageClass.data); memcpy(TNEF->OriginalMessageClass.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFMessageClass STD_ARGLIST { memcpy(TNEF->messageClass, data, MIN(size, sizeof(TNEF->messageClass))); return 0; } // ----------------------------------------------------------------------------- int TNEFFromHandler STD_ARGLIST { TNEF->from.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->from.data); TNEF->from.size = size; memcpy(TNEF->from.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFSubjectHandler STD_ARGLIST { if (TNEF->subject.data) free(TNEF->subject.data); TNEF->subject.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->subject.data); TNEF->subject.size = size; memcpy(TNEF->subject.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFRendData STD_ARGLIST { Attachment *p; // Find the last attachment. p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; // Add a new one p->next = calloc(1, sizeof(Attachment)); ALLOCCHECK(p->next); p = p->next; TNEFInitAttachment(p); int correct = (size >= sizeof(renddata)) ? sizeof(renddata) : size; memcpy(&(p->RenderData), data, correct); return 0; } // ----------------------------------------------------------------------------- int TNEFVersion STD_ARGLIST { WORD major; WORD minor; minor = SwapWord((BYTE*)data, size); major = SwapWord((BYTE*)data + 2, size - 2); snprintf(TNEF->version, sizeof(TNEF->version), "TNEF%i.%i", major, minor); return 0; } // ----------------------------------------------------------------------------- int TNEFIcon STD_ARGLIST { Attachment *p; // Find the last attachment. p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->IconData.size = size; p->IconData.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(p->IconData.data); memcpy(p->IconData.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFRecipTable STD_ARGLIST { DWORD count; BYTE *d; int current_row; int propcount; int current_prop; d = (BYTE*)data; count = SwapDWord((BYTE*)d, 4); d += 4; // printf("Recipient Table containing %u rows\n", count); return 0; for (current_row = 0; current_row < count; current_row++) { propcount = SwapDWord((BYTE*)d, 4); if (TNEF->Debug >= 1) printf("> Row %i contains %i properties\n", current_row, propcount); d += 4; for (current_prop = 0; current_prop < propcount; current_prop++) { } } return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentMAPI STD_ARGLIST { Attachment *p; // Find the last attachment. // p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; return TNEFFillMapi(TNEF, (BYTE*)data, size, &(p->MAPI)); } // ----------------------------------------------------------------------------- int TNEFMapiProperties STD_ARGLIST { if (TNEFFillMapi(TNEF, (BYTE*)data, size, &(TNEF->MapiProperties)) < 0) { printf("ERROR Parsing MAPI block\n"); return -1; }; if (TNEF->Debug >= 3) { MAPIPrint(&(TNEF->MapiProperties)); } return 0; } int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p) { int i, j; DWORD num; BYTE *d; MAPIProperty *mp; DWORD type; DWORD length; variableLength *vl; WORD temp_word; DWORD temp_dword; DDWORD temp_ddword; int count = -1; int offset; d = data; p->count = SwapDWord((BYTE*)data, 4); d += 4; p->properties = calloc(p->count, sizeof(MAPIProperty)); ALLOCCHECK(p->properties); mp = p->properties; for (i = 0; i < p->count; i++) { if (count == -1) { mp->id = SwapDWord((BYTE*)d, 4); d += 4; mp->custom = 0; mp->count = 1; mp->namedproperty = 0; length = -1; if (PROP_ID(mp->id) >= 0x8000) { // Read the GUID SIZECHECK(16); memcpy(&(mp->guid[0]), d, 16); d += 16; SIZECHECK(4); length = SwapDWord((BYTE*)d, 4); d += sizeof(DWORD); if (length > 0) { mp->namedproperty = length; mp->propnames = calloc(length, sizeof(variableLength)); ALLOCCHECK(mp->propnames); while (length > 0) { SIZECHECK(4); type = SwapDWord((BYTE*)d, 4); mp->propnames[length - 1].data = calloc(type, sizeof(BYTE)); ALLOCCHECK(mp->propnames[length - 1].data); mp->propnames[length - 1].size = type; d += 4; for (j = 0; j < (type >> 1); j++) { SIZECHECK(j*2); mp->propnames[length - 1].data[j] = d[j * 2]; } d += type + ((type % 4) ? (4 - type % 4) : 0); length--; } } else { // READ the type SIZECHECK(sizeof(DWORD)); type = SwapDWord((BYTE*)d, sizeof(DWORD)); d += sizeof(DWORD); mp->id = PROP_TAG(PROP_TYPE(mp->id), type); } mp->custom = 1; } DEBUG2(TNEF->Debug, 3, "Type id = %04x, Prop id = %04x", PROP_TYPE(mp->id), PROP_ID(mp->id)); if (PROP_TYPE(mp->id) & MV_FLAG) { mp->id = PROP_TAG(PROP_TYPE(mp->id) - MV_FLAG, PROP_ID(mp->id)); SIZECHECK(4); mp->count = SwapDWord((BYTE*)d, 4); d += 4; count = 0; } mp->data = calloc(mp->count, sizeof(variableLength)); ALLOCCHECK(mp->data); vl = mp->data; } else { i--; count++; vl = &(mp->data[count]); } switch (PROP_TYPE(mp->id)) { case PT_BINARY: case PT_OBJECT: case PT_STRING8: case PT_UNICODE: // First number of objects (assume 1 for now) if (count == -1) { SIZECHECK(4); vl->size = SwapDWord((BYTE*)d, 4); d += 4; } // now size of object SIZECHECK(4); vl->size = SwapDWord((BYTE*)d, 4); d += 4; // now actual object if (vl->size != 0) { SIZECHECK(vl->size); if (PROP_TYPE(mp->id) == PT_UNICODE) { vl->data =(BYTE*) to_utf8(vl->size, (char*)d); } else { vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); memcpy(vl->data, d, vl->size); } } else { vl->data = NULL; } // Make sure to read in a multiple of 4 num = vl->size; offset = ((num % 4) ? (4 - num % 4) : 0); d += num + ((num % 4) ? (4 - num % 4) : 0); break; case PT_I2: // Read in 2 bytes, but proceed by 4 bytes vl->size = 2; vl->data = calloc(vl->size, sizeof(WORD)); ALLOCCHECK(vl->data); SIZECHECK(sizeof(WORD)) temp_word = SwapWord((BYTE*)d, sizeof(WORD)); memcpy(vl->data, &temp_word, vl->size); d += 4; break; case PT_BOOLEAN: case PT_LONG: case PT_R4: case PT_CURRENCY: case PT_APPTIME: case PT_ERROR: vl->size = 4; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(4); temp_dword = SwapDWord((BYTE*)d, 4); memcpy(vl->data, &temp_dword, vl->size); d += 4; break; case PT_DOUBLE: case PT_I8: case PT_SYSTIME: vl->size = 8; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(8); temp_ddword = SwapDDWord(d, 8); memcpy(vl->data, &temp_ddword, vl->size); d += 8; break; case PT_CLSID: vl->size = 16; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(vl->size); memcpy(vl->data, d, vl->size); d+=16; break; default: printf("Bad file\n"); exit(-1); } switch (PROP_ID(mp->id)) { case PR_SUBJECT: case PR_SUBJECT_IPM: case PR_ORIGINAL_SUBJECT: case PR_NORMALIZED_SUBJECT: case PR_CONVERSATION_TOPIC: DEBUG(TNEF->Debug, 3, "Got a Subject"); if (TNEF->subject.size == 0) { int i; DEBUG(TNEF->Debug, 3, "Assigning a Subject"); TNEF->subject.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->subject.data); TNEF->subject.size = vl->size; memcpy(TNEF->subject.data, vl->data, vl->size); // Unfortunately, we have to normalize out some invalid // characters, or else the file won't write for (i = 0; i != TNEF->subject.size; i++) { switch (TNEF->subject.data[i]) { case '\\': case '/': case '\0': TNEF->subject.data[i] = '_'; break; } } } break; } if (count == (mp->count - 1)) { count = -1; } if (count == -1) { mp++; } } if ((d - data) < size) { if (TNEF->Debug >= 1) { printf("ERROR DURING MAPI READ\n"); printf("Read %td bytes, Expected %u bytes\n", (d - data), size); printf("%td bytes missing\n", size - (d - data)); } } else if ((d - data) > size) { if (TNEF->Debug >= 1) { printf("ERROR DURING MAPI READ\n"); printf("Read %td bytes, Expected %u bytes\n", (d - data), size); printf("%li bytes extra\n", (d - data) - size); } } return 0; } // ----------------------------------------------------------------------------- int TNEFSentFor STD_ARGLIST { WORD name_length, addr_length; BYTE *d; d = (BYTE*)data; while ((d - (BYTE*)data) < size) { SIZECHECK(sizeof(WORD)); name_length = SwapWord((BYTE*)d, sizeof(WORD)); d += sizeof(WORD); if (TNEF->Debug >= 1) printf("Sent For : %s", d); d += name_length; SIZECHECK(sizeof(WORD)); addr_length = SwapWord((BYTE*)d, sizeof(WORD)); d += sizeof(WORD); if (TNEF->Debug >= 1) printf("<%s>\n", d); d += addr_length; } return 0; } // ----------------------------------------------------------------------------- int TNEFDateHandler STD_ARGLIST { dtr *Date; Attachment *p; WORD * tmp_src, *tmp_dst; int i; p = &(TNEF->starting_attach); switch (TNEFList[id].id) { case attDateSent: Date = &(TNEF->dateSent); break; case attDateRecd: Date = &(TNEF->dateReceived); break; case attDateModified: Date = &(TNEF->dateModified); break; case attDateStart: Date = &(TNEF->DateStart); break; case attDateEnd: Date = &(TNEF->DateEnd); break; case attAttachCreateDate: while (p->next != NULL) p = p->next; Date = &(p->CreateDate); break; case attAttachModifyDate: while (p->next != NULL) p = p->next; Date = &(p->ModifyDate); break; default: if (TNEF->Debug >= 1) printf("MISSING CASE\n"); return YTNEF_UNKNOWN_PROPERTY; } tmp_src = (WORD *)data; tmp_dst = (WORD *)Date; for (i = 0; i < sizeof(dtr) / sizeof(WORD); i++) { *tmp_dst++ = SwapWord((BYTE *)tmp_src++, sizeof(WORD)); } return 0; } void TNEFPrintDate(dtr Date) { char days[7][15] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; char months[12][15] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; if (Date.wDayOfWeek < 7) printf("%s ", days[Date.wDayOfWeek]); if ((Date.wMonth < 13) && (Date.wMonth > 0)) printf("%s ", months[Date.wMonth - 1]); printf("%hu, %hu ", Date.wDay, Date.wYear); if (Date.wHour > 12) printf("%i:%02hu:%02hu pm", (Date.wHour - 12), Date.wMinute, Date.wSecond); else if (Date.wHour == 12) printf("%hu:%02hu:%02hu pm", (Date.wHour), Date.wMinute, Date.wSecond); else printf("%hu:%02hu:%02hu am", Date.wHour, Date.wMinute, Date.wSecond); } // ----------------------------------------------------------------------------- int TNEFHexBreakdown STD_ARGLIST { int i; if (TNEF->Debug == 0) return 0; printf("%s: [%i bytes] \n", TNEFList[id].name, size); for (i = 0; i < size; i++) { printf("%02x ", data[i]); if ((i + 1) % 16 == 0) printf("\n"); } printf("\n"); return 0; } // ----------------------------------------------------------------------------- int TNEFDetailedPrint STD_ARGLIST { int i; if (TNEF->Debug == 0) return 0; printf("%s: [%i bytes] \n", TNEFList[id].name, size); for (i = 0; i < size; i++) { printf("%c", data[i]); } printf("\n"); return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentFilename STD_ARGLIST { Attachment *p; p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->Title.size = size; p->Title.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(p->Title.data); memcpy(p->Title.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentSave STD_ARGLIST { Attachment *p; p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->FileData.data = calloc(sizeof(char), size); ALLOCCHECK(p->FileData.data); p->FileData.size = size; memcpy(p->FileData.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFPriority STD_ARGLIST { DWORD value; value = SwapDWord((BYTE*)data, size); switch (value) { case 3: sprintf((TNEF->priority), "high"); break; case 2: sprintf((TNEF->priority), "normal"); break; case 1: sprintf((TNEF->priority), "low"); break; default: sprintf((TNEF->priority), "N/A"); break; } return 0; } // ----------------------------------------------------------------------------- int TNEFCheckForSignature(DWORD sig) { DWORD signature = 0x223E9F78; sig = SwapDWord((BYTE *)&sig, sizeof(DWORD)); if (signature == sig) { return 0; } else { return YTNEF_NOT_TNEF_STREAM; } } // ----------------------------------------------------------------------------- int TNEFGetKey(TNEFStruct *TNEF, WORD *key) { if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(WORD), 1, key) < 1) { if (TNEF->Debug >= 1) printf("Error reading Key\n"); return YTNEF_ERROR_READING_DATA; } *key = SwapWord((BYTE *)key, sizeof(WORD)); DEBUG1(TNEF->Debug, 2, "Key = 0x%X", *key); DEBUG1(TNEF->Debug, 2, "Key = %i", *key); return 0; } // ----------------------------------------------------------------------------- int TNEFGetHeader(TNEFStruct *TNEF, DWORD *type, DWORD *size) { BYTE component; DEBUG(TNEF->Debug, 2, "About to read Component"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(BYTE), 1, &component) < 1) { return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, "About to read type"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, type) < 1) { if (TNEF->Debug >= 1) printf("ERROR: Error reading type\n"); return YTNEF_ERROR_READING_DATA; } DEBUG1(TNEF->Debug, 2, "Type = 0x%X", *type); DEBUG1(TNEF->Debug, 2, "Type = %u", *type); DEBUG(TNEF->Debug, 2, "About to read size"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, size) < 1) { if (TNEF->Debug >= 1) printf("ERROR: Error reading size\n"); return YTNEF_ERROR_READING_DATA; } DEBUG1(TNEF->Debug, 2, "Size = %u", *size); *type = SwapDWord((BYTE *)type, sizeof(DWORD)); *size = SwapDWord((BYTE *)size, sizeof(DWORD)); return 0; } // ----------------------------------------------------------------------------- int TNEFRawRead(TNEFStruct *TNEF, BYTE *data, DWORD size, WORD *checksum) { WORD temp; int i; if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(BYTE), size, data) < size) { if (TNEF->Debug >= 1) printf("ERROR: Error reading data\n"); return YTNEF_ERROR_READING_DATA; } if (checksum != NULL) { *checksum = 0; for (i = 0; i < size; i++) { temp = data[i]; *checksum = (*checksum + temp); } } return 0; } #define INITVARLENGTH(x) (x).data = NULL; (x).size = 0; #define INITDTR(x) (x).wYear=0; (x).wMonth=0; (x).wDay=0; \ (x).wHour=0; (x).wMinute=0; (x).wSecond=0; \ (x).wDayOfWeek=0; #define INITSTR(x) memset((x), 0, sizeof(x)); void TNEFInitMapi(MAPIProps *p) { p->count = 0; p->properties = NULL; } void TNEFInitAttachment(Attachment *p) { INITDTR(p->Date); INITVARLENGTH(p->Title); INITVARLENGTH(p->MetaFile); INITDTR(p->CreateDate); INITDTR(p->ModifyDate); INITVARLENGTH(p->TransportFilename); INITVARLENGTH(p->FileData); INITVARLENGTH(p->IconData); memset(&(p->RenderData), 0, sizeof(renddata)); TNEFInitMapi(&(p->MAPI)); p->next = NULL; } void TNEFInitialize(TNEFStruct *TNEF) { INITSTR(TNEF->version); INITVARLENGTH(TNEF->from); INITVARLENGTH(TNEF->subject); INITDTR(TNEF->dateSent); INITDTR(TNEF->dateReceived); INITSTR(TNEF->messageStatus); INITSTR(TNEF->messageClass); INITSTR(TNEF->messageID); INITSTR(TNEF->parentID); INITSTR(TNEF->conversationID); INITVARLENGTH(TNEF->body); INITSTR(TNEF->priority); TNEFInitAttachment(&(TNEF->starting_attach)); INITDTR(TNEF->dateModified); TNEFInitMapi(&(TNEF->MapiProperties)); INITVARLENGTH(TNEF->CodePage); INITVARLENGTH(TNEF->OriginalMessageClass); INITVARLENGTH(TNEF->Owner); INITVARLENGTH(TNEF->SentFor); INITVARLENGTH(TNEF->Delegate); INITDTR(TNEF->DateStart); INITDTR(TNEF->DateEnd); INITVARLENGTH(TNEF->AidOwner); TNEF->RequestRes = 0; TNEF->IO.data = NULL; TNEF->IO.InitProc = NULL; TNEF->IO.ReadProc = NULL; TNEF->IO.CloseProc = NULL; } #undef INITVARLENGTH #undef INITDTR #undef INITSTR #define FREEVARLENGTH(x) if ((x).size > 0) { \ free((x).data); (x).size =0; } void TNEFFree(TNEFStruct *TNEF) { Attachment *p, *store; FREEVARLENGTH(TNEF->from); FREEVARLENGTH(TNEF->subject); FREEVARLENGTH(TNEF->body); FREEVARLENGTH(TNEF->CodePage); FREEVARLENGTH(TNEF->OriginalMessageClass); FREEVARLENGTH(TNEF->Owner); FREEVARLENGTH(TNEF->SentFor); FREEVARLENGTH(TNEF->Delegate); FREEVARLENGTH(TNEF->AidOwner); TNEFFreeMapiProps(&(TNEF->MapiProperties)); p = TNEF->starting_attach.next; while (p != NULL) { TNEFFreeAttachment(p); store = p->next; free(p); p = store; } } void TNEFFreeAttachment(Attachment *p) { FREEVARLENGTH(p->Title); FREEVARLENGTH(p->MetaFile); FREEVARLENGTH(p->TransportFilename); FREEVARLENGTH(p->FileData); FREEVARLENGTH(p->IconData); TNEFFreeMapiProps(&(p->MAPI)); } void TNEFFreeMapiProps(MAPIProps *p) { int i, j; for (i = 0; i < p->count; i++) { for (j = 0; j < p->properties[i].count; j++) { FREEVARLENGTH(p->properties[i].data[j]); } free(p->properties[i].data); for (j = 0; j < p->properties[i].namedproperty; j++) { FREEVARLENGTH(p->properties[i].propnames[j]); } free(p->properties[i].propnames); } free(p->properties); p->count = 0; } #undef FREEVARLENGTH // Procedures to handle File IO int TNEFFile_Open(TNEFIOStruct *IO) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG1(finfo->Debug, 3, "Opening %s", finfo->filename); if ((finfo->fptr = fopen(finfo->filename, "rb")) == NULL) { return -1; } else { return 0; } } int TNEFFile_Read(TNEFIOStruct *IO, int size, int count, void *dest) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG2(finfo->Debug, 3, "Reading %i blocks of %i size", count, size); if (finfo->fptr != NULL) { return fread((BYTE *)dest, size, count, finfo->fptr); } else { return -1; } } int TNEFFile_Close(TNEFIOStruct *IO) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG1(finfo->Debug, 3, "Closing file %s", finfo->filename); if (finfo->fptr != NULL) { fclose(finfo->fptr); finfo->fptr = NULL; } return 0; } int TNEFParseFile(char *filename, TNEFStruct *TNEF) { TNEFFileInfo finfo; if (TNEF->Debug >= 1) printf("Attempting to parse %s...\n", filename); finfo.filename = filename; finfo.fptr = NULL; finfo.Debug = TNEF->Debug; TNEF->IO.data = (void *)&finfo; TNEF->IO.InitProc = TNEFFile_Open; TNEF->IO.ReadProc = TNEFFile_Read; TNEF->IO.CloseProc = TNEFFile_Close; return TNEFParse(TNEF); } //------------------------------------------------------------- // Procedures to handle Memory IO int TNEFMemory_Open(TNEFIOStruct *IO) { TNEFMemInfo *minfo; minfo = (TNEFMemInfo *)IO->data; minfo->ptr = minfo->dataStart; return 0; } int TNEFMemory_Read(TNEFIOStruct *IO, int size, int count, void *dest) { TNEFMemInfo *minfo; int length; long max; minfo = (TNEFMemInfo *)IO->data; length = count * size; max = (minfo->dataStart + minfo->size) - (minfo->ptr); if (length > max) { return -1; } DEBUG1(minfo->Debug, 3, "Copying %i bytes", length); memcpy(dest, minfo->ptr, length); minfo->ptr += length; return count; } int TNEFMemory_Close(TNEFIOStruct *IO) { // Do nothing, really... return 0; } int TNEFParseMemory(BYTE *memory, long size, TNEFStruct *TNEF) { TNEFMemInfo minfo; DEBUG(TNEF->Debug, 1, "Attempting to parse memory block...\n"); minfo.dataStart = memory; minfo.ptr = memory; minfo.size = size; minfo.Debug = TNEF->Debug; TNEF->IO.data = (void *)&minfo; TNEF->IO.InitProc = TNEFMemory_Open; TNEF->IO.ReadProc = TNEFMemory_Read; TNEF->IO.CloseProc = TNEFMemory_Close; return TNEFParse(TNEF); } int TNEFParse(TNEFStruct *TNEF) { WORD key; DWORD type; DWORD size; DWORD signature; BYTE *data; WORD checksum, header_checksum; int i; if (TNEF->IO.ReadProc == NULL) { printf("ERROR: Setup incorrectly: No ReadProc\n"); return YTNEF_INCORRECT_SETUP; } if (TNEF->IO.InitProc != NULL) { DEBUG(TNEF->Debug, 2, "About to initialize"); if (TNEF->IO.InitProc(&TNEF->IO) != 0) { return YTNEF_CANNOT_INIT_DATA; } DEBUG(TNEF->Debug, 2, "Initialization finished"); } DEBUG(TNEF->Debug, 2, "Reading Signature"); if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) { printf("ERROR: Error reading signature\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, "Checking Signature"); if (TNEFCheckForSignature(signature) < 0) { printf("ERROR: Signature does not match. Not TNEF.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NOT_TNEF_STREAM; } DEBUG(TNEF->Debug, 2, "Reading Key."); if (TNEFGetKey(TNEF, &key) < 0) { printf("ERROR: Unable to retrieve key.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NO_KEY; } DEBUG(TNEF->Debug, 2, "Starting Full Processing."); while (TNEFGetHeader(TNEF, &type, &size) == 0) { DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size); DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size); data = calloc(size, sizeof(BYTE)); ALLOCCHECK(data); if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) { printf("ERROR: Unable to read data.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) { printf("ERROR: Unable to read checksum.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } checksum = SwapWord((BYTE *)&checksum, sizeof(WORD)); if (checksum != header_checksum) { printf("ERROR: Checksum mismatch. Data corruption?:\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_BAD_CHECKSUM; } for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) { if (TNEFList[i].id == type) { if (TNEFList[i].handler != NULL) { if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) { free(data); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_IN_HANDLER; } else { // Found our handler and processed it. now time to get out break; } } else { DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes", TNEFList[i].name, size); } } } free(data); } if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return 0; } // ---------------------------------------------------------------------------- variableLength *MAPIFindUserProp(MAPIProps *p, unsigned int ID) { int i; if (p != NULL) { for (i = 0; i < p->count; i++) { if ((p->properties[i].id == ID) && (p->properties[i].custom == 1)) { return (p->properties[i].data); } } } return MAPI_UNDEFINED; } variableLength *MAPIFindProperty(MAPIProps *p, unsigned int ID) { int i; if (p != NULL) { for (i = 0; i < p->count; i++) { if ((p->properties[i].id == ID) && (p->properties[i].custom == 0)) { return (p->properties[i].data); } } } return MAPI_UNDEFINED; } int MAPISysTimetoDTR(BYTE *data, dtr *thedate) { DDWORD ddword_tmp; int startingdate = 0; int tmp_date; int days_in_year = 365; unsigned int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; ddword_tmp = *((DDWORD *)data); ddword_tmp = ddword_tmp / 10; // micro-s ddword_tmp /= 1000; // ms ddword_tmp /= 1000; // s thedate->wSecond = (ddword_tmp % 60); ddword_tmp /= 60; // seconds to minutes thedate->wMinute = (ddword_tmp % 60); ddword_tmp /= 60; //minutes to hours thedate->wHour = (ddword_tmp % 24); ddword_tmp /= 24; // Hours to days // Now calculate the year based on # of days thedate->wYear = 1601; startingdate = 1; while (ddword_tmp >= days_in_year) { ddword_tmp -= days_in_year; thedate->wYear++; days_in_year = 365; startingdate++; if ((thedate->wYear % 4) == 0) { if ((thedate->wYear % 100) == 0) { // if the year is 1700,1800,1900, etc, then it is only // a leap year if exactly divisible by 400, not 4. if ((thedate->wYear % 400) == 0) { startingdate++; days_in_year = 366; } } else { startingdate++; days_in_year = 366; } } startingdate %= 7; } // the remaining number is the day # in this year // So now calculate the Month, & Day of month if ((thedate->wYear % 4) == 0) { // 29 days in february in a leap year months[1] = 29; } tmp_date = (int)ddword_tmp; thedate->wDayOfWeek = (tmp_date + startingdate) % 7; thedate->wMonth = 0; while (tmp_date > months[thedate->wMonth]) { tmp_date -= months[thedate->wMonth]; thedate->wMonth++; } thedate->wMonth++; thedate->wDay = tmp_date + 1; return 0; } void MAPIPrint(MAPIProps *p) { int j, i, index, h, x; DDWORD *ddword_ptr; DDWORD ddword_tmp; dtr thedate; MAPIProperty *mapi; variableLength *mapidata; variableLength vlTemp; int found; for (j = 0; j < p->count; j++) { mapi = &(p->properties[j]); printf(" #%i: Type: [", j); switch (PROP_TYPE(mapi->id)) { case PT_UNSPECIFIED: printf(" NONE "); break; case PT_NULL: printf(" NULL "); break; case PT_I2: printf(" I2 "); break; case PT_LONG: printf(" LONG "); break; case PT_R4: printf(" R4 "); break; case PT_DOUBLE: printf(" DOUBLE "); break; case PT_CURRENCY: printf("CURRENCY "); break; case PT_APPTIME: printf("APP TIME "); break; case PT_ERROR: printf(" ERROR "); break; case PT_BOOLEAN: printf(" BOOLEAN "); break; case PT_OBJECT: printf(" OBJECT "); break; case PT_I8: printf(" I8 "); break; case PT_STRING8: printf(" STRING8 "); break; case PT_UNICODE: printf(" UNICODE "); break; case PT_SYSTIME: printf("SYS TIME "); break; case PT_CLSID: printf("OLE GUID "); break; case PT_BINARY: printf(" BINARY "); break; default: printf("<%x>", PROP_TYPE(mapi->id)); break; } printf("] Code: ["); if (mapi->custom == 1) { printf("UD:x%04x", PROP_ID(mapi->id)); } else { found = 0; for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) { if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) { printf("%s", MPList[index].name); found = 1; } } if (found == 0) { printf("0x%04x", PROP_ID(mapi->id)); } } printf("]\n"); if (mapi->namedproperty > 0) { for (i = 0; i < mapi->namedproperty; i++) { printf(" Name: %s\n", mapi->propnames[i].data); } } for (i = 0; i < mapi->count; i++) { mapidata = &(mapi->data[i]); if (mapi->count > 1) { printf(" [%i/%u] ", i, mapi->count); } else { printf(" "); } printf("Size: %i", mapidata->size); switch (PROP_TYPE(mapi->id)) { case PT_SYSTIME: MAPISysTimetoDTR(mapidata->data, &thedate); printf(" Value: "); ddword_tmp = *((DDWORD *)mapidata->data); TNEFPrintDate(thedate); printf(" [HEX: "); for (x = 0; x < sizeof(ddword_tmp); x++) { printf(" %02x", (BYTE)mapidata->data[x]); } printf("] (%llu)\n", ddword_tmp); break; case PT_LONG: printf(" Value: %i\n", *((int*)mapidata->data)); break; case PT_I2: printf(" Value: %hi\n", *((short int*)mapidata->data)); break; case PT_BOOLEAN: if (mapi->data->data[0] != 0) { printf(" Value: True\n"); } else { printf(" Value: False\n"); } break; case PT_OBJECT: printf("\n"); break; case PT_BINARY: if (IsCompressedRTF(mapidata) == 1) { printf(" Detected Compressed RTF. "); printf("Decompressed text follows\n"); printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) { printf("%s\n", vlTemp.data); free(vlTemp.data); } printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); } else { printf(" Value: ["); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf("%c", mapidata->data[h]); } else { printf("."); } } printf("]\n"); } break; case PT_STRING8: printf(" Value: [%s]\n", mapidata->data); if (strlen((char*)mapidata->data) != mapidata->size - 1) { printf("Detected Hidden data: ["); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf("%c", mapidata->data[h]); } else { printf("."); } } printf("]\n"); } break; case PT_CLSID: printf(" Value: "); printf("[HEX: "); for(x=0; x< 16; x++) { printf(" %02x", (BYTE)mapidata->data[x]); } printf("]\n"); break; default: printf(" Value: [%s]\n", mapidata->data); } } } } int IsCompressedRTF(variableLength *p) { unsigned int in; BYTE *src; ULONG magic; if (p->size < 4) return 0; src = p->data; in = 0; in += 4; in += 4; magic = SwapDWord((BYTE*)src + in, 4); if (magic == 0x414c454d) { return 1; } else if (magic == 0x75465a4c) { return 1; } else { return 0; } } BYTE *DecompressRTF(variableLength *p, int *size) { BYTE *dst; // destination for uncompressed bytes BYTE *src; unsigned int in; unsigned int out; variableLength comp_Prebuf; ULONG compressedSize, uncompressedSize, magic; comp_Prebuf.size = strlen(RTF_PREBUF); comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1); ALLOCCHECK_CHAR(comp_Prebuf.data); memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size); src = p->data; in = 0; if (p->size < 20) { printf("File too small\n"); return(NULL); } compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; magic = SwapDWord((BYTE*)src + in, 4); in += 4; in += 4; // check size excluding the size field itself if (compressedSize != p->size - 4) { printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4); free(comp_Prebuf.data); return NULL; } // process the data if (magic == 0x414c454d) { // magic number that identifies the stream as a uncompressed stream dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + 4, uncompressedSize); } else if (magic == 0x75465a4c) { // magic number that identifies the stream as a compressed stream int flagCount = 0; int flags = 0; // Prevent overflow on 32 Bit Systems if (comp_Prebuf.size >= INT_MAX - uncompressedSize) { printf("Corrupted file\n"); exit(-1); } dst = calloc(comp_Prebuf.size + uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, comp_Prebuf.data, comp_Prebuf.size); out = comp_Prebuf.size; while (out < (comp_Prebuf.size + uncompressedSize)) { // each flag byte flags 8 literals/references, 1 per bit flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1; if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal unsigned int offset = src[in++]; unsigned int length = src[in++]; unsigned int end; offset = (offset << 4) | (length >> 4); // the offset relative to block start length = (length & 0xF) + 2; // the number of bytes to copy // the decompression buffer is supposed to wrap around back // to the beginning when the end is reached. we save the // need for such a buffer by pointing straight into the data // buffer, and simulating this behaviour by modifying the // pointers appropriately. offset = (out / 4096) * 4096 + offset; if (offset >= out) // take from previous block offset -= 4096; // note: can't use System.arraycopy, because the referenced // bytes can cross through the current out position. end = offset + length; while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize)) && (offset < (comp_Prebuf.size + uncompressedSize))) dst[out++] = dst[offset++]; } else { // literal if ((out >= (comp_Prebuf.size + uncompressedSize)) || (in >= p->size)) { printf("Corrupted stream\n"); exit(-1); } dst[out++] = src[in++]; } } // copy it back without the prebuffered data src = dst; dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + comp_Prebuf.size, uncompressedSize); free(src); *size = uncompressedSize; free(comp_Prebuf.data); return dst; } else { // unknown magic number printf("Unknown compression type (magic number %x)\n", magic); } free(comp_Prebuf.data); return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3208_0
crossvul-cpp_data_good_3255_0
/* * Routines having to do with the 'struct sk_buff' memory handlers. * * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk> * Florian La Roche <rzsfl@rz.uni-sb.de> * * Fixes: * Alan Cox : Fixed the worst of the load * balancer bugs. * Dave Platt : Interrupt stacking fix. * Richard Kooijman : Timestamp fixes. * Alan Cox : Changed buffer format. * Alan Cox : destructor hook for AF_UNIX etc. * Linus Torvalds : Better skb_clone. * Alan Cox : Added skb_copy. * Alan Cox : Added all the changed routines Linus * only put in the headers * Ray VanTassle : Fixed --skb->lock in free * Alan Cox : skb_copy copy arp field * Andi Kleen : slabified it. * Robert Olsson : Removed skb_head_pool * * NOTE: * The __skb_ routines should be called with interrupts * disabled, or you better be *real* sure that the operation is atomic * with respect to whatever list is being frobbed (e.g. via lock_sock() * or via disabling bottom half handlers, etc). * * 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. */ /* * The functions in this file will not compile correctly with gcc 2.4.x */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/kmemcheck.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/slab.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/sctp.h> #include <linux/netdevice.h> #ifdef CONFIG_NET_CLS_ACT #include <net/pkt_sched.h> #endif #include <linux/string.h> #include <linux/skbuff.h> #include <linux/splice.h> #include <linux/cache.h> #include <linux/rtnetlink.h> #include <linux/init.h> #include <linux/scatterlist.h> #include <linux/errqueue.h> #include <linux/prefetch.h> #include <linux/if_vlan.h> #include <net/protocol.h> #include <net/dst.h> #include <net/sock.h> #include <net/checksum.h> #include <net/ip6_checksum.h> #include <net/xfrm.h> #include <linux/uaccess.h> #include <trace/events/skb.h> #include <linux/highmem.h> #include <linux/capability.h> #include <linux/user_namespace.h> struct kmem_cache *skbuff_head_cache __read_mostly; static struct kmem_cache *skbuff_fclone_cache __read_mostly; int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS; EXPORT_SYMBOL(sysctl_max_skb_frags); /** * skb_panic - private function for out-of-line support * @skb: buffer * @sz: size * @addr: address * @msg: skb_over_panic or skb_under_panic * * Out-of-line support for skb_put() and skb_push(). * Called via the wrapper skb_over_panic() or skb_under_panic(). * Keep out of line to prevent kernel bloat. * __builtin_return_address is not used because it is not always reliable. */ static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr, const char msg[]) { pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n", msg, addr, skb->len, sz, skb->head, skb->data, (unsigned long)skb->tail, (unsigned long)skb->end, skb->dev ? skb->dev->name : "<NULL>"); BUG(); } static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr) { skb_panic(skb, sz, addr, __func__); } static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr) { skb_panic(skb, sz, addr, __func__); } /* * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells * the caller if emergency pfmemalloc reserves are being used. If it is and * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves * may be used. Otherwise, the packet data may be discarded until enough * memory is free */ #define kmalloc_reserve(size, gfp, node, pfmemalloc) \ __kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc) static void *__kmalloc_reserve(size_t size, gfp_t flags, int node, unsigned long ip, bool *pfmemalloc) { void *obj; bool ret_pfmemalloc = false; /* * Try a regular allocation, when that fails and we're not entitled * to the reserves, fail. */ obj = kmalloc_node_track_caller(size, flags | __GFP_NOMEMALLOC | __GFP_NOWARN, node); if (obj || !(gfp_pfmemalloc_allowed(flags))) goto out; /* Try again but now we are using pfmemalloc reserves */ ret_pfmemalloc = true; obj = kmalloc_node_track_caller(size, flags, node); out: if (pfmemalloc) *pfmemalloc = ret_pfmemalloc; return obj; } /* Allocate a new skbuff. We do this ourselves so we can fill in a few * 'private' fields and also do memory statistics to find all the * [BEEP] leaks. * */ struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node) { struct sk_buff *skb; /* Get the HEAD */ skb = kmem_cache_alloc_node(skbuff_head_cache, gfp_mask & ~__GFP_DMA, node); if (!skb) goto out; /* * Only clear those fields we need to clear, not those that we will * actually initialise below. Hence, don't put any more fields after * the tail pointer in struct sk_buff! */ memset(skb, 0, offsetof(struct sk_buff, tail)); skb->head = NULL; skb->truesize = sizeof(struct sk_buff); atomic_set(&skb->users, 1); skb->mac_header = (typeof(skb->mac_header))~0U; out: return skb; } /** * __alloc_skb - allocate a network buffer * @size: size to allocate * @gfp_mask: allocation mask * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache * instead of head cache and allocate a cloned (child) skb. * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for * allocations in case the data is required for writeback * @node: numa node to allocate memory on * * Allocate a new &sk_buff. The returned buffer has no headroom and a * tail room of at least size bytes. The object has a reference count * of one. The return is the buffer. On a failure the return is %NULL. * * Buffers may only be allocated from interrupts using a @gfp_mask of * %GFP_ATOMIC. */ struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask, int flags, int node) { struct kmem_cache *cache; struct skb_shared_info *shinfo; struct sk_buff *skb; u8 *data; bool pfmemalloc; cache = (flags & SKB_ALLOC_FCLONE) ? skbuff_fclone_cache : skbuff_head_cache; if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX)) gfp_mask |= __GFP_MEMALLOC; /* Get the HEAD */ skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node); if (!skb) goto out; prefetchw(skb); /* We do our best to align skb_shared_info on a separate cache * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives * aligned memory blocks, unless SLUB/SLAB debug is enabled. * Both skb->head and skb_shared_info are cache line aligned. */ size = SKB_DATA_ALIGN(size); size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc); if (!data) goto nodata; /* kmalloc(size) might give us more room than requested. * Put skb_shared_info exactly at the end of allocated zone, * to allow max possible filling before reallocation. */ size = SKB_WITH_OVERHEAD(ksize(data)); prefetchw(data + size); /* * Only clear those fields we need to clear, not those that we will * actually initialise below. Hence, don't put any more fields after * the tail pointer in struct sk_buff! */ memset(skb, 0, offsetof(struct sk_buff, tail)); /* Account for allocated memory : skb + skb->head */ skb->truesize = SKB_TRUESIZE(size); skb->pfmemalloc = pfmemalloc; atomic_set(&skb->users, 1); skb->head = data; skb->data = data; skb_reset_tail_pointer(skb); skb->end = skb->tail + size; skb->mac_header = (typeof(skb->mac_header))~0U; skb->transport_header = (typeof(skb->transport_header))~0U; /* make sure we initialize shinfo sequentially */ shinfo = skb_shinfo(skb); memset(shinfo, 0, offsetof(struct skb_shared_info, dataref)); atomic_set(&shinfo->dataref, 1); kmemcheck_annotate_variable(shinfo->destructor_arg); if (flags & SKB_ALLOC_FCLONE) { struct sk_buff_fclones *fclones; fclones = container_of(skb, struct sk_buff_fclones, skb1); kmemcheck_annotate_bitfield(&fclones->skb2, flags1); skb->fclone = SKB_FCLONE_ORIG; atomic_set(&fclones->fclone_ref, 1); fclones->skb2.fclone = SKB_FCLONE_CLONE; } out: return skb; nodata: kmem_cache_free(cache, skb); skb = NULL; goto out; } EXPORT_SYMBOL(__alloc_skb); /** * __build_skb - build a network buffer * @data: data buffer provided by caller * @frag_size: size of data, or 0 if head was kmalloced * * Allocate a new &sk_buff. Caller provides space holding head and * skb_shared_info. @data must have been allocated by kmalloc() only if * @frag_size is 0, otherwise data should come from the page allocator * or vmalloc() * The return is the new skb buffer. * On a failure the return is %NULL, and @data is not freed. * Notes : * Before IO, driver allocates only data buffer where NIC put incoming frame * Driver should add room at head (NET_SKB_PAD) and * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info)) * After IO, driver calls build_skb(), to allocate sk_buff and populate it * before giving packet to stack. * RX rings only contains data buffers, not full skbs. */ struct sk_buff *__build_skb(void *data, unsigned int frag_size) { struct skb_shared_info *shinfo; struct sk_buff *skb; unsigned int size = frag_size ? : ksize(data); skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC); if (!skb) return NULL; size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); memset(skb, 0, offsetof(struct sk_buff, tail)); skb->truesize = SKB_TRUESIZE(size); atomic_set(&skb->users, 1); skb->head = data; skb->data = data; skb_reset_tail_pointer(skb); skb->end = skb->tail + size; skb->mac_header = (typeof(skb->mac_header))~0U; skb->transport_header = (typeof(skb->transport_header))~0U; /* make sure we initialize shinfo sequentially */ shinfo = skb_shinfo(skb); memset(shinfo, 0, offsetof(struct skb_shared_info, dataref)); atomic_set(&shinfo->dataref, 1); kmemcheck_annotate_variable(shinfo->destructor_arg); return skb; } /* build_skb() is wrapper over __build_skb(), that specifically * takes care of skb->head and skb->pfmemalloc * This means that if @frag_size is not zero, then @data must be backed * by a page fragment, not kmalloc() or vmalloc() */ struct sk_buff *build_skb(void *data, unsigned int frag_size) { struct sk_buff *skb = __build_skb(data, frag_size); if (skb && frag_size) { skb->head_frag = 1; if (page_is_pfmemalloc(virt_to_head_page(data))) skb->pfmemalloc = 1; } return skb; } EXPORT_SYMBOL(build_skb); #define NAPI_SKB_CACHE_SIZE 64 struct napi_alloc_cache { struct page_frag_cache page; unsigned int skb_count; void *skb_cache[NAPI_SKB_CACHE_SIZE]; }; static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache); static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache); static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask) { struct page_frag_cache *nc; unsigned long flags; void *data; local_irq_save(flags); nc = this_cpu_ptr(&netdev_alloc_cache); data = page_frag_alloc(nc, fragsz, gfp_mask); local_irq_restore(flags); return data; } /** * netdev_alloc_frag - allocate a page fragment * @fragsz: fragment size * * Allocates a frag from a page for receive buffer. * Uses GFP_ATOMIC allocations. */ void *netdev_alloc_frag(unsigned int fragsz) { return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD); } EXPORT_SYMBOL(netdev_alloc_frag); static void *__napi_alloc_frag(unsigned int fragsz, gfp_t gfp_mask) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); return page_frag_alloc(&nc->page, fragsz, gfp_mask); } void *napi_alloc_frag(unsigned int fragsz) { return __napi_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD); } EXPORT_SYMBOL(napi_alloc_frag); /** * __netdev_alloc_skb - allocate an skbuff for rx on a specific device * @dev: network device to receive on * @len: length to allocate * @gfp_mask: get_free_pages mask, passed to alloc_skb * * Allocate a new &sk_buff and assign it a usage count of one. The * buffer has NET_SKB_PAD headroom built in. Users should allocate * the headroom they think they need without accounting for the * built in space. The built in space is used for optimisations. * * %NULL is returned if there is no free memory. */ struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len, gfp_t gfp_mask) { struct page_frag_cache *nc; unsigned long flags; struct sk_buff *skb; bool pfmemalloc; void *data; len += NET_SKB_PAD; if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) || (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) { skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE); if (!skb) goto skb_fail; goto skb_success; } len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); len = SKB_DATA_ALIGN(len); if (sk_memalloc_socks()) gfp_mask |= __GFP_MEMALLOC; local_irq_save(flags); nc = this_cpu_ptr(&netdev_alloc_cache); data = page_frag_alloc(nc, len, gfp_mask); pfmemalloc = nc->pfmemalloc; local_irq_restore(flags); if (unlikely(!data)) return NULL; skb = __build_skb(data, len); if (unlikely(!skb)) { skb_free_frag(data); return NULL; } /* use OR instead of assignment to avoid clearing of bits in mask */ if (pfmemalloc) skb->pfmemalloc = 1; skb->head_frag = 1; skb_success: skb_reserve(skb, NET_SKB_PAD); skb->dev = dev; skb_fail: return skb; } EXPORT_SYMBOL(__netdev_alloc_skb); /** * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance * @napi: napi instance this buffer was allocated for * @len: length to allocate * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages * * Allocate a new sk_buff for use in NAPI receive. This buffer will * attempt to allocate the head from a special reserved region used * only for NAPI Rx allocation. By doing this we can save several * CPU cycles by avoiding having to disable and re-enable IRQs. * * %NULL is returned if there is no free memory. */ struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len, gfp_t gfp_mask) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); struct sk_buff *skb; void *data; len += NET_SKB_PAD + NET_IP_ALIGN; if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) || (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) { skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE); if (!skb) goto skb_fail; goto skb_success; } len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); len = SKB_DATA_ALIGN(len); if (sk_memalloc_socks()) gfp_mask |= __GFP_MEMALLOC; data = page_frag_alloc(&nc->page, len, gfp_mask); if (unlikely(!data)) return NULL; skb = __build_skb(data, len); if (unlikely(!skb)) { skb_free_frag(data); return NULL; } /* use OR instead of assignment to avoid clearing of bits in mask */ if (nc->page.pfmemalloc) skb->pfmemalloc = 1; skb->head_frag = 1; skb_success: skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN); skb->dev = napi->dev; skb_fail: return skb; } EXPORT_SYMBOL(__napi_alloc_skb); void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off, int size, unsigned int truesize) { skb_fill_page_desc(skb, i, page, off, size); skb->len += size; skb->data_len += size; skb->truesize += truesize; } EXPORT_SYMBOL(skb_add_rx_frag); void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size, unsigned int truesize) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; skb_frag_size_add(frag, size); skb->len += size; skb->data_len += size; skb->truesize += truesize; } EXPORT_SYMBOL(skb_coalesce_rx_frag); static void skb_drop_list(struct sk_buff **listp) { kfree_skb_list(*listp); *listp = NULL; } static inline void skb_drop_fraglist(struct sk_buff *skb) { skb_drop_list(&skb_shinfo(skb)->frag_list); } static void skb_clone_fraglist(struct sk_buff *skb) { struct sk_buff *list; skb_walk_frags(skb, list) skb_get(list); } static void skb_free_head(struct sk_buff *skb) { unsigned char *head = skb->head; if (skb->head_frag) skb_free_frag(head); else kfree(head); } static void skb_release_data(struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int i; if (skb->cloned && atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1, &shinfo->dataref)) return; for (i = 0; i < shinfo->nr_frags; i++) __skb_frag_unref(&shinfo->frags[i]); /* * If skb buf is from userspace, we need to notify the caller * the lower device DMA has done; */ if (shinfo->tx_flags & SKBTX_DEV_ZEROCOPY) { struct ubuf_info *uarg; uarg = shinfo->destructor_arg; if (uarg->callback) uarg->callback(uarg, true); } if (shinfo->frag_list) kfree_skb_list(shinfo->frag_list); skb_free_head(skb); } /* * Free an skbuff by memory without cleaning the state. */ static void kfree_skbmem(struct sk_buff *skb) { struct sk_buff_fclones *fclones; switch (skb->fclone) { case SKB_FCLONE_UNAVAILABLE: kmem_cache_free(skbuff_head_cache, skb); return; case SKB_FCLONE_ORIG: fclones = container_of(skb, struct sk_buff_fclones, skb1); /* We usually free the clone (TX completion) before original skb * This test would have no chance to be true for the clone, * while here, branch prediction will be good. */ if (atomic_read(&fclones->fclone_ref) == 1) goto fastpath; break; default: /* SKB_FCLONE_CLONE */ fclones = container_of(skb, struct sk_buff_fclones, skb2); break; } if (!atomic_dec_and_test(&fclones->fclone_ref)) return; fastpath: kmem_cache_free(skbuff_fclone_cache, fclones); } static void skb_release_head_state(struct sk_buff *skb) { skb_dst_drop(skb); #ifdef CONFIG_XFRM secpath_put(skb->sp); #endif if (skb->destructor) { WARN_ON(in_irq()); skb->destructor(skb); } #if IS_ENABLED(CONFIG_NF_CONNTRACK) nf_conntrack_put(skb_nfct(skb)); #endif #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER) nf_bridge_put(skb->nf_bridge); #endif } /* Free everything but the sk_buff shell. */ static void skb_release_all(struct sk_buff *skb) { skb_release_head_state(skb); if (likely(skb->head)) skb_release_data(skb); } /** * __kfree_skb - private function * @skb: buffer * * Free an sk_buff. Release anything attached to the buffer. * Clean the state. This is an internal helper function. Users should * always call kfree_skb */ void __kfree_skb(struct sk_buff *skb) { skb_release_all(skb); kfree_skbmem(skb); } EXPORT_SYMBOL(__kfree_skb); /** * kfree_skb - free an sk_buff * @skb: buffer to free * * Drop a reference to the buffer and free it if the usage count has * hit zero. */ void kfree_skb(struct sk_buff *skb) { if (unlikely(!skb)) return; if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; trace_kfree_skb(skb, __builtin_return_address(0)); __kfree_skb(skb); } EXPORT_SYMBOL(kfree_skb); void kfree_skb_list(struct sk_buff *segs) { while (segs) { struct sk_buff *next = segs->next; kfree_skb(segs); segs = next; } } EXPORT_SYMBOL(kfree_skb_list); /** * skb_tx_error - report an sk_buff xmit error * @skb: buffer that triggered an error * * Report xmit error if a device callback is tracking this skb. * skb must be freed afterwards. */ void skb_tx_error(struct sk_buff *skb) { if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) { struct ubuf_info *uarg; uarg = skb_shinfo(skb)->destructor_arg; if (uarg->callback) uarg->callback(uarg, false); skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY; } } EXPORT_SYMBOL(skb_tx_error); /** * consume_skb - free an skbuff * @skb: buffer to free * * Drop a ref to the buffer and free it if the usage count has hit zero * Functions identically to kfree_skb, but kfree_skb assumes that the frame * is being dropped after a failure and notes that */ void consume_skb(struct sk_buff *skb) { if (unlikely(!skb)) return; if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; trace_consume_skb(skb); __kfree_skb(skb); } EXPORT_SYMBOL(consume_skb); void __kfree_skb_flush(void) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); /* flush skb_cache if containing objects */ if (nc->skb_count) { kmem_cache_free_bulk(skbuff_head_cache, nc->skb_count, nc->skb_cache); nc->skb_count = 0; } } static inline void _kfree_skb_defer(struct sk_buff *skb) { struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache); /* drop skb->head and call any destructors for packet */ skb_release_all(skb); /* record skb to CPU local list */ nc->skb_cache[nc->skb_count++] = skb; #ifdef CONFIG_SLUB /* SLUB writes into objects when freeing */ prefetchw(skb); #endif /* flush skb_cache if it is filled */ if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) { kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_SIZE, nc->skb_cache); nc->skb_count = 0; } } void __kfree_skb_defer(struct sk_buff *skb) { _kfree_skb_defer(skb); } void napi_consume_skb(struct sk_buff *skb, int budget) { if (unlikely(!skb)) return; /* Zero budget indicate non-NAPI context called us, like netpoll */ if (unlikely(!budget)) { dev_consume_skb_any(skb); return; } if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; /* if reaching here SKB is ready to free */ trace_consume_skb(skb); /* if SKB is a clone, don't handle this case */ if (skb->fclone != SKB_FCLONE_UNAVAILABLE) { __kfree_skb(skb); return; } _kfree_skb_defer(skb); } EXPORT_SYMBOL(napi_consume_skb); /* Make sure a field is enclosed inside headers_start/headers_end section */ #define CHECK_SKB_FIELD(field) \ BUILD_BUG_ON(offsetof(struct sk_buff, field) < \ offsetof(struct sk_buff, headers_start)); \ BUILD_BUG_ON(offsetof(struct sk_buff, field) > \ offsetof(struct sk_buff, headers_end)); \ static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old) { new->tstamp = old->tstamp; /* We do not copy old->sk */ new->dev = old->dev; memcpy(new->cb, old->cb, sizeof(old->cb)); skb_dst_copy(new, old); #ifdef CONFIG_XFRM new->sp = secpath_get(old->sp); #endif __nf_copy(new, old, false); /* Note : this field could be in headers_start/headers_end section * It is not yet because we do not want to have a 16 bit hole */ new->queue_mapping = old->queue_mapping; memcpy(&new->headers_start, &old->headers_start, offsetof(struct sk_buff, headers_end) - offsetof(struct sk_buff, headers_start)); CHECK_SKB_FIELD(protocol); CHECK_SKB_FIELD(csum); CHECK_SKB_FIELD(hash); CHECK_SKB_FIELD(priority); CHECK_SKB_FIELD(skb_iif); CHECK_SKB_FIELD(vlan_proto); CHECK_SKB_FIELD(vlan_tci); CHECK_SKB_FIELD(transport_header); CHECK_SKB_FIELD(network_header); CHECK_SKB_FIELD(mac_header); CHECK_SKB_FIELD(inner_protocol); CHECK_SKB_FIELD(inner_transport_header); CHECK_SKB_FIELD(inner_network_header); CHECK_SKB_FIELD(inner_mac_header); CHECK_SKB_FIELD(mark); #ifdef CONFIG_NETWORK_SECMARK CHECK_SKB_FIELD(secmark); #endif #ifdef CONFIG_NET_RX_BUSY_POLL CHECK_SKB_FIELD(napi_id); #endif #ifdef CONFIG_XPS CHECK_SKB_FIELD(sender_cpu); #endif #ifdef CONFIG_NET_SCHED CHECK_SKB_FIELD(tc_index); #endif } /* * You should not add any new code to this function. Add it to * __copy_skb_header above instead. */ static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb) { #define C(x) n->x = skb->x n->next = n->prev = NULL; n->sk = NULL; __copy_skb_header(n, skb); C(len); C(data_len); C(mac_len); n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len; n->cloned = 1; n->nohdr = 0; n->destructor = NULL; C(tail); C(end); C(head); C(head_frag); C(data); C(truesize); atomic_set(&n->users, 1); atomic_inc(&(skb_shinfo(skb)->dataref)); skb->cloned = 1; return n; #undef C } /** * skb_morph - morph one skb into another * @dst: the skb to receive the contents * @src: the skb to supply the contents * * This is identical to skb_clone except that the target skb is * supplied by the user. * * The target skb is returned upon exit. */ struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src) { skb_release_all(dst); return __skb_clone(dst, src); } EXPORT_SYMBOL_GPL(skb_morph); /** * skb_copy_ubufs - copy userspace skb frags buffers to kernel * @skb: the skb to modify * @gfp_mask: allocation priority * * This must be called on SKBTX_DEV_ZEROCOPY skb. * It will copy all frags into kernel and drop the reference * to userspace pages. * * If this function is called from an interrupt gfp_mask() must be * %GFP_ATOMIC. * * Returns 0 on success or a negative error code on failure * to allocate kernel memory to copy to. */ int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask) { int i; int num_frags = skb_shinfo(skb)->nr_frags; struct page *page, *head = NULL; struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg; for (i = 0; i < num_frags; i++) { u8 *vaddr; skb_frag_t *f = &skb_shinfo(skb)->frags[i]; page = alloc_page(gfp_mask); if (!page) { while (head) { struct page *next = (struct page *)page_private(head); put_page(head); head = next; } return -ENOMEM; } vaddr = kmap_atomic(skb_frag_page(f)); memcpy(page_address(page), vaddr + f->page_offset, skb_frag_size(f)); kunmap_atomic(vaddr); set_page_private(page, (unsigned long)head); head = page; } /* skb frags release userspace buffers */ for (i = 0; i < num_frags; i++) skb_frag_unref(skb, i); uarg->callback(uarg, false); /* skb frags point to kernel buffers */ for (i = num_frags - 1; i >= 0; i--) { __skb_fill_page_desc(skb, i, head, 0, skb_shinfo(skb)->frags[i].size); head = (struct page *)page_private(head); } skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY; return 0; } EXPORT_SYMBOL_GPL(skb_copy_ubufs); /** * skb_clone - duplicate an sk_buff * @skb: buffer to clone * @gfp_mask: allocation priority * * Duplicate an &sk_buff. The new one is not owned by a socket. Both * copies share the same packet data but not structure. The new * buffer has a reference count of 1. If the allocation fails the * function returns %NULL otherwise the new buffer is returned. * * If this function is called from an interrupt gfp_mask() must be * %GFP_ATOMIC. */ struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask) { struct sk_buff_fclones *fclones = container_of(skb, struct sk_buff_fclones, skb1); struct sk_buff *n; if (skb_orphan_frags(skb, gfp_mask)) return NULL; if (skb->fclone == SKB_FCLONE_ORIG && atomic_read(&fclones->fclone_ref) == 1) { n = &fclones->skb2; atomic_set(&fclones->fclone_ref, 2); } else { if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; n = kmem_cache_alloc(skbuff_head_cache, gfp_mask); if (!n) return NULL; kmemcheck_annotate_bitfield(n, flags1); n->fclone = SKB_FCLONE_UNAVAILABLE; } return __skb_clone(n, skb); } EXPORT_SYMBOL(skb_clone); static void skb_headers_offset_update(struct sk_buff *skb, int off) { /* Only adjust this if it actually is csum_start rather than csum */ if (skb->ip_summed == CHECKSUM_PARTIAL) skb->csum_start += off; /* {transport,network,mac}_header and tail are relative to skb->head */ skb->transport_header += off; skb->network_header += off; if (skb_mac_header_was_set(skb)) skb->mac_header += off; skb->inner_transport_header += off; skb->inner_network_header += off; skb->inner_mac_header += off; } static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old) { __copy_skb_header(new, old); skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size; skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs; skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type; } static inline int skb_alloc_rx_flag(const struct sk_buff *skb) { if (skb_pfmemalloc(skb)) return SKB_ALLOC_RX; return 0; } /** * skb_copy - create private copy of an sk_buff * @skb: buffer to copy * @gfp_mask: allocation priority * * Make a copy of both an &sk_buff and its data. This is used when the * caller wishes to modify the data and needs a private copy of the * data to alter. Returns %NULL on failure or the pointer to the buffer * on success. The returned buffer has a reference count of 1. * * As by-product this function converts non-linear &sk_buff to linear * one, so that &sk_buff becomes completely private and caller is allowed * to modify all the data of returned buffer. This means that this * function is not recommended for use in circumstances when only * header is going to be modified. Use pskb_copy() instead. */ struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask) { int headerlen = skb_headroom(skb); unsigned int size = skb_end_offset(skb) + skb->data_len; struct sk_buff *n = __alloc_skb(size, gfp_mask, skb_alloc_rx_flag(skb), NUMA_NO_NODE); if (!n) return NULL; /* Set the data pointer */ skb_reserve(n, headerlen); /* Set the tail pointer and length */ skb_put(n, skb->len); if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len)) BUG(); copy_skb_header(n, skb); return n; } EXPORT_SYMBOL(skb_copy); /** * __pskb_copy_fclone - create copy of an sk_buff with private head. * @skb: buffer to copy * @headroom: headroom of new skb * @gfp_mask: allocation priority * @fclone: if true allocate the copy of the skb from the fclone * cache instead of the head cache; it is recommended to set this * to true for the cases where the copy will likely be cloned * * Make a copy of both an &sk_buff and part of its data, located * in header. Fragmented data remain shared. This is used when * the caller wishes to modify only header of &sk_buff and needs * private copy of the header to alter. Returns %NULL on failure * or the pointer to the buffer on success. * The returned buffer has a reference count of 1. */ struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom, gfp_t gfp_mask, bool fclone) { unsigned int size = skb_headlen(skb) + headroom; int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0); struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE); if (!n) goto out; /* Set the data pointer */ skb_reserve(n, headroom); /* Set the tail pointer and length */ skb_put(n, skb_headlen(skb)); /* Copy the bytes */ skb_copy_from_linear_data(skb, n->data, n->len); n->truesize += skb->data_len; n->data_len = skb->data_len; n->len = skb->len; if (skb_shinfo(skb)->nr_frags) { int i; if (skb_orphan_frags(skb, gfp_mask)) { kfree_skb(n); n = NULL; goto out; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i]; skb_frag_ref(skb, i); } skb_shinfo(n)->nr_frags = i; } if (skb_has_frag_list(skb)) { skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list; skb_clone_fraglist(n); } copy_skb_header(n, skb); out: return n; } EXPORT_SYMBOL(__pskb_copy_fclone); /** * pskb_expand_head - reallocate header of &sk_buff * @skb: buffer to reallocate * @nhead: room to add at head * @ntail: room to add at tail * @gfp_mask: allocation priority * * Expands (or creates identical copy, if @nhead and @ntail are zero) * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have * reference count of 1. Returns zero in the case of success or error, * if expansion failed. In the last case, &sk_buff is not changed. * * All the pointers pointing into skb header may change and must be * reloaded after call to this function. */ int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail, gfp_t gfp_mask) { int i, osize = skb_end_offset(skb); int size = osize + nhead + ntail; long off; u8 *data; BUG_ON(nhead < 0); if (skb_shared(skb)) BUG(); size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) goto nodata; size = SKB_WITH_OVERHEAD(ksize(data)); /* Copy only real data... and, alas, header. This should be * optimized for the cases when header is void. */ memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head); memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); /* * if shinfo is shared we must drop the old head gracefully, but if it * is not we can just drop the old head and let the existing refcount * be since all we did is relocate the values */ if (skb_cloned(skb)) { /* copy this zero copy skb frags */ if (skb_orphan_frags(skb, gfp_mask)) goto nofrags; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_frag_ref(skb, i); if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); skb_release_data(skb); } else { skb_free_head(skb); } off = (data + nhead) - skb->head; skb->head = data; skb->head_frag = 0; skb->data += off; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; off = nhead; #else skb->end = skb->head + size; #endif skb->tail += off; skb_headers_offset_update(skb, nhead); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; atomic_set(&skb_shinfo(skb)->dataref, 1); /* It is not generally safe to change skb->truesize. * For the moment, we really care of rx path, or * when skb is orphaned (not attached to a socket). */ if (!skb->sk || skb->destructor == sock_edemux) skb->truesize += size - osize; return 0; nofrags: kfree(data); nodata: return -ENOMEM; } EXPORT_SYMBOL(pskb_expand_head); /* Make private copy of skb with writable head and some headroom */ struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom) { struct sk_buff *skb2; int delta = headroom - skb_headroom(skb); if (delta <= 0) skb2 = pskb_copy(skb, GFP_ATOMIC); else { skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0, GFP_ATOMIC)) { kfree_skb(skb2); skb2 = NULL; } } return skb2; } EXPORT_SYMBOL(skb_realloc_headroom); /** * skb_copy_expand - copy and expand sk_buff * @skb: buffer to copy * @newheadroom: new free bytes at head * @newtailroom: new free bytes at tail * @gfp_mask: allocation priority * * Make a copy of both an &sk_buff and its data and while doing so * allocate additional space. * * This is used when the caller wishes to modify the data and needs a * private copy of the data to alter as well as more space for new fields. * Returns %NULL on failure or the pointer to the buffer * on success. The returned buffer has a reference count of 1. * * You must pass %GFP_ATOMIC as the allocation priority if this function * is called from an interrupt. */ struct sk_buff *skb_copy_expand(const struct sk_buff *skb, int newheadroom, int newtailroom, gfp_t gfp_mask) { /* * Allocate the copy buffer */ struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom, gfp_mask, skb_alloc_rx_flag(skb), NUMA_NO_NODE); int oldheadroom = skb_headroom(skb); int head_copy_len, head_copy_off; if (!n) return NULL; skb_reserve(n, newheadroom); /* Set the tail pointer and length */ skb_put(n, skb->len); head_copy_len = oldheadroom; head_copy_off = 0; if (newheadroom <= head_copy_len) head_copy_len = newheadroom; else head_copy_off = newheadroom - head_copy_len; /* Copy the linear header and data. */ if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off, skb->len + head_copy_len)) BUG(); copy_skb_header(n, skb); skb_headers_offset_update(n, newheadroom - oldheadroom); return n; } EXPORT_SYMBOL(skb_copy_expand); /** * skb_pad - zero pad the tail of an skb * @skb: buffer to pad * @pad: space to pad * * Ensure that a buffer is followed by a padding area that is zero * filled. Used by network drivers which may DMA or transfer data * beyond the buffer end onto the wire. * * May return error in out of memory cases. The skb is freed on error. */ int skb_pad(struct sk_buff *skb, int pad) { int err; int ntail; /* If the skbuff is non linear tailroom is always zero.. */ if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) { memset(skb->data+skb->len, 0, pad); return 0; } ntail = skb->data_len + pad - (skb->end - skb->tail); if (likely(skb_cloned(skb) || ntail > 0)) { err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC); if (unlikely(err)) goto free_skb; } /* FIXME: The use of this function with non-linear skb's really needs * to be audited. */ err = skb_linearize(skb); if (unlikely(err)) goto free_skb; memset(skb->data + skb->len, 0, pad); return 0; free_skb: kfree_skb(skb); return err; } EXPORT_SYMBOL(skb_pad); /** * pskb_put - add data to the tail of a potentially fragmented buffer * @skb: start of the buffer to use * @tail: tail fragment of the buffer to use * @len: amount of data to add * * This function extends the used data area of the potentially * fragmented buffer. @tail must be the last fragment of @skb -- or * @skb itself. If this would exceed the total buffer size the kernel * will panic. A pointer to the first byte of the extra data is * returned. */ unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len) { if (tail != skb) { skb->data_len += len; skb->len += len; } return skb_put(tail, len); } EXPORT_SYMBOL_GPL(pskb_put); /** * skb_put - add data to a buffer * @skb: buffer to use * @len: amount of data to add * * This function extends the used data area of the buffer. If this would * exceed the total buffer size the kernel will panic. A pointer to the * first byte of the extra data is returned. */ unsigned char *skb_put(struct sk_buff *skb, unsigned int len) { unsigned char *tmp = skb_tail_pointer(skb); SKB_LINEAR_ASSERT(skb); skb->tail += len; skb->len += len; if (unlikely(skb->tail > skb->end)) skb_over_panic(skb, len, __builtin_return_address(0)); return tmp; } EXPORT_SYMBOL(skb_put); /** * skb_push - add data to the start of a buffer * @skb: buffer to use * @len: amount of data to add * * This function extends the used data area of the buffer at the buffer * start. If this would exceed the total buffer headroom the kernel will * panic. A pointer to the first byte of the extra data is returned. */ unsigned char *skb_push(struct sk_buff *skb, unsigned int len) { skb->data -= len; skb->len += len; if (unlikely(skb->data<skb->head)) skb_under_panic(skb, len, __builtin_return_address(0)); return skb->data; } EXPORT_SYMBOL(skb_push); /** * skb_pull - remove data from the start of a buffer * @skb: buffer to use * @len: amount of data to remove * * This function removes data from the start of a buffer, returning * the memory to the headroom. A pointer to the next data in the buffer * is returned. Once the data has been pulled future pushes will overwrite * the old data. */ unsigned char *skb_pull(struct sk_buff *skb, unsigned int len) { return skb_pull_inline(skb, len); } EXPORT_SYMBOL(skb_pull); /** * skb_trim - remove end from a buffer * @skb: buffer to alter * @len: new length * * Cut the length of a buffer down by removing data from the tail. If * the buffer is already under the length specified it is not modified. * The skb must be linear. */ void skb_trim(struct sk_buff *skb, unsigned int len) { if (skb->len > len) __skb_trim(skb, len); } EXPORT_SYMBOL(skb_trim); /* Trims skb to length len. It can change skb pointers. */ int ___pskb_trim(struct sk_buff *skb, unsigned int len) { struct sk_buff **fragp; struct sk_buff *frag; int offset = skb_headlen(skb); int nfrags = skb_shinfo(skb)->nr_frags; int i; int err; if (skb_cloned(skb) && unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))) return err; i = 0; if (offset >= len) goto drop_pages; for (; i < nfrags; i++) { int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]); if (end < len) { offset = end; continue; } skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset); drop_pages: skb_shinfo(skb)->nr_frags = i; for (; i < nfrags; i++) skb_frag_unref(skb, i); if (skb_has_frag_list(skb)) skb_drop_fraglist(skb); goto done; } for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp); fragp = &frag->next) { int end = offset + frag->len; if (skb_shared(frag)) { struct sk_buff *nfrag; nfrag = skb_clone(frag, GFP_ATOMIC); if (unlikely(!nfrag)) return -ENOMEM; nfrag->next = frag->next; consume_skb(frag); frag = nfrag; *fragp = frag; } if (end < len) { offset = end; continue; } if (end > len && unlikely((err = pskb_trim(frag, len - offset)))) return err; if (frag->next) skb_drop_list(&frag->next); break; } done: if (len > skb_headlen(skb)) { skb->data_len -= skb->len - len; skb->len = len; } else { skb->len = len; skb->data_len = 0; skb_set_tail_pointer(skb, len); } return 0; } EXPORT_SYMBOL(___pskb_trim); /** * __pskb_pull_tail - advance tail of skb header * @skb: buffer to reallocate * @delta: number of bytes to advance tail * * The function makes a sense only on a fragmented &sk_buff, * it expands header moving its tail forward and copying necessary * data from fragmented part. * * &sk_buff MUST have reference count of 1. * * Returns %NULL (and &sk_buff does not change) if pull failed * or value of new tail of skb in the case of success. * * All the pointers pointing into skb header may change and must be * reloaded after call to this function. */ /* Moves tail of skb head forward, copying data from fragmented part, * when it is necessary. * 1. It may fail due to malloc failure. * 2. It may change skb pointers. * * It is pretty complicated. Luckily, it is called only in exceptional cases. */ unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta) { /* If skb has not enough free space at tail, get new one * plus 128 bytes for future expansions. If we have enough * room at tail, reallocate without expansion only if skb is cloned. */ int i, k, eat = (skb->tail + delta) - skb->end; if (eat > 0 || skb_cloned(skb)) { if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0, GFP_ATOMIC)) return NULL; } if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta)) BUG(); /* Optimization: no fragments, no reasons to preestimate * size of pulled pages. Superb. */ if (!skb_has_frag_list(skb)) goto pull_pages; /* Estimate size of pulled pages. */ eat = delta; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (size >= eat) goto pull_pages; eat -= size; } /* If we need update frag list, we are in troubles. * Certainly, it possible to add an offset to skb data, * but taking into account that pulling is expected to * be very rare operation, it is worth to fight against * further bloating skb head and crucify ourselves here instead. * Pure masohism, indeed. 8)8) */ if (eat) { struct sk_buff *list = skb_shinfo(skb)->frag_list; struct sk_buff *clone = NULL; struct sk_buff *insp = NULL; do { BUG_ON(!list); if (list->len <= eat) { /* Eaten as whole. */ eat -= list->len; list = list->next; insp = list; } else { /* Eaten partially. */ if (skb_shared(list)) { /* Sucks! We need to fork list. :-( */ clone = skb_clone(list, GFP_ATOMIC); if (!clone) return NULL; insp = list->next; list = clone; } else { /* This may be pulled without * problems. */ insp = list; } if (!pskb_pull(list, eat)) { kfree_skb(clone); return NULL; } break; } } while (eat); /* Free pulled out fragments. */ while ((list = skb_shinfo(skb)->frag_list) != insp) { skb_shinfo(skb)->frag_list = list->next; kfree_skb(list); } /* And insert new clone at head. */ if (clone) { clone->next = list; skb_shinfo(skb)->frag_list = clone; } } /* Success! Now we may commit changes to skb data. */ pull_pages: eat = delta; k = 0; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (size <= eat) { skb_frag_unref(skb, i); eat -= size; } else { skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i]; if (eat) { skb_shinfo(skb)->frags[k].page_offset += eat; skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat); eat = 0; } k++; } } skb_shinfo(skb)->nr_frags = k; skb->tail += delta; skb->data_len -= delta; return skb_tail_pointer(skb); } EXPORT_SYMBOL(__pskb_pull_tail); /** * skb_copy_bits - copy bits from skb to kernel buffer * @skb: source skb * @offset: offset in source * @to: destination buffer * @len: number of bytes to copy * * Copy the specified number of bytes from the source skb to the * destination buffer. * * CAUTION ! : * If its prototype is ever changed, * check arch/{*}/net/{*}.S files, * since it is called from BPF assembly code. */ int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len) { int start = skb_headlen(skb); struct sk_buff *frag_iter; int i, copy; if (offset > (int)skb->len - len) goto fault; /* Copy header. */ if ((copy = start - offset) > 0) { if (copy > len) copy = len; skb_copy_from_linear_data_offset(skb, offset, to, copy); if ((len -= copy) == 0) return 0; offset += copy; to += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; skb_frag_t *f = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(f); if ((copy = end - offset) > 0) { u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(f)); memcpy(to, vaddr + f->page_offset + offset - start, copy); kunmap_atomic(vaddr); if ((len -= copy) == 0) return 0; offset += copy; to += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_copy_bits(frag_iter, offset - start, to, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; to += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_bits); /* * Callback from splice_to_pipe(), if we need to release some pages * at the end of the spd in case we error'ed out in filling the pipe. */ static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i) { put_page(spd->pages[i]); } static struct page *linear_to_page(struct page *page, unsigned int *len, unsigned int *offset, struct sock *sk) { struct page_frag *pfrag = sk_page_frag(sk); if (!sk_page_frag_refill(sk, pfrag)) return NULL; *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset); memcpy(page_address(pfrag->page) + pfrag->offset, page_address(page) + *offset, *len); *offset = pfrag->offset; pfrag->offset += *len; return pfrag->page; } static bool spd_can_coalesce(const struct splice_pipe_desc *spd, struct page *page, unsigned int offset) { return spd->nr_pages && spd->pages[spd->nr_pages - 1] == page && (spd->partial[spd->nr_pages - 1].offset + spd->partial[spd->nr_pages - 1].len == offset); } /* * Fill page/offset/length into spd, if it can hold more pages. */ static bool spd_fill_page(struct splice_pipe_desc *spd, struct pipe_inode_info *pipe, struct page *page, unsigned int *len, unsigned int offset, bool linear, struct sock *sk) { if (unlikely(spd->nr_pages == MAX_SKB_FRAGS)) return true; if (linear) { page = linear_to_page(page, len, &offset, sk); if (!page) return true; } if (spd_can_coalesce(spd, page, offset)) { spd->partial[spd->nr_pages - 1].len += *len; return false; } get_page(page); spd->pages[spd->nr_pages] = page; spd->partial[spd->nr_pages].len = *len; spd->partial[spd->nr_pages].offset = offset; spd->nr_pages++; return false; } static bool __splice_segment(struct page *page, unsigned int poff, unsigned int plen, unsigned int *off, unsigned int *len, struct splice_pipe_desc *spd, bool linear, struct sock *sk, struct pipe_inode_info *pipe) { if (!*len) return true; /* skip this segment if already processed */ if (*off >= plen) { *off -= plen; return false; } /* ignore any bits we already processed */ poff += *off; plen -= *off; *off = 0; do { unsigned int flen = min(*len, plen); if (spd_fill_page(spd, pipe, page, &flen, poff, linear, sk)) return true; poff += flen; plen -= flen; *len -= flen; } while (*len && plen); return false; } /* * Map linear and fragment data from the skb to spd. It reports true if the * pipe is full or if we already spliced the requested length. */ static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe, unsigned int *offset, unsigned int *len, struct splice_pipe_desc *spd, struct sock *sk) { int seg; struct sk_buff *iter; /* map the linear part : * If skb->head_frag is set, this 'linear' part is backed by a * fragment, and if the head is not shared with any clones then * we can avoid a copy since we own the head portion of this page. */ if (__splice_segment(virt_to_page(skb->data), (unsigned long) skb->data & (PAGE_SIZE - 1), skb_headlen(skb), offset, len, spd, skb_head_is_locked(skb), sk, pipe)) return true; /* * then map the fragments */ for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) { const skb_frag_t *f = &skb_shinfo(skb)->frags[seg]; if (__splice_segment(skb_frag_page(f), f->page_offset, skb_frag_size(f), offset, len, spd, false, sk, pipe)) return true; } skb_walk_frags(skb, iter) { if (*offset >= iter->len) { *offset -= iter->len; continue; } /* __skb_splice_bits() only fails if the output has no room * left, so no point in going over the frag_list for the error * case. */ if (__skb_splice_bits(iter, pipe, offset, len, spd, sk)) return true; } return false; } /* * Map data from the skb to a pipe. Should handle both the linear part, * the fragments, and the frag list. */ int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset, struct pipe_inode_info *pipe, unsigned int tlen, unsigned int flags) { struct partial_page partial[MAX_SKB_FRAGS]; struct page *pages[MAX_SKB_FRAGS]; struct splice_pipe_desc spd = { .pages = pages, .partial = partial, .nr_pages_max = MAX_SKB_FRAGS, .flags = flags, .ops = &nosteal_pipe_buf_ops, .spd_release = sock_spd_release, }; int ret = 0; __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk); if (spd.nr_pages) ret = splice_to_pipe(pipe, &spd); return ret; } EXPORT_SYMBOL_GPL(skb_splice_bits); /** * skb_store_bits - store bits from kernel buffer to skb * @skb: destination buffer * @offset: offset in destination * @from: source buffer * @len: number of bytes to copy * * Copy the specified number of bytes from the source buffer to the * destination skb. This function handles all the messy bits of * traversing fragment lists and such. */ int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len) { int start = skb_headlen(skb); struct sk_buff *frag_iter; int i, copy; if (offset > (int)skb->len - len) goto fault; if ((copy = start - offset) > 0) { if (copy > len) copy = len; skb_copy_to_linear_data_offset(skb, offset, from, copy); if ((len -= copy) == 0) return 0; offset += copy; from += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; int end; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); memcpy(vaddr + frag->page_offset + offset - start, from, copy); kunmap_atomic(vaddr); if ((len -= copy) == 0) return 0; offset += copy; from += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_store_bits(frag_iter, offset - start, from, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; from += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_store_bits); /* Checksum skb data. */ __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len, __wsum csum, const struct skb_checksum_ops *ops) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int pos = 0; /* Checksum header. */ if (copy > 0) { if (copy > len) copy = len; csum = ops->update(skb->data + offset, copy, csum); if ((len -= copy) == 0) return csum; offset += copy; pos = copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { __wsum csum2; u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); csum2 = ops->update(vaddr + frag->page_offset + offset - start, copy, 0); kunmap_atomic(vaddr); csum = ops->combine(csum, csum2, pos, copy); if (!(len -= copy)) return csum; offset += copy; pos += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { __wsum csum2; if (copy > len) copy = len; csum2 = __skb_checksum(frag_iter, offset - start, copy, 0, ops); csum = ops->combine(csum, csum2, pos, copy); if ((len -= copy) == 0) return csum; offset += copy; pos += copy; } start = end; } BUG_ON(len); return csum; } EXPORT_SYMBOL(__skb_checksum); __wsum skb_checksum(const struct sk_buff *skb, int offset, int len, __wsum csum) { const struct skb_checksum_ops ops = { .update = csum_partial_ext, .combine = csum_block_add_ext, }; return __skb_checksum(skb, offset, len, csum, &ops); } EXPORT_SYMBOL(skb_checksum); /* Both of above in one bottle. */ __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset, u8 *to, int len, __wsum csum) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int pos = 0; /* Copy header. */ if (copy > 0) { if (copy > len) copy = len; csum = csum_partial_copy_nocheck(skb->data + offset, to, copy, csum); if ((len -= copy) == 0) return csum; offset += copy; to += copy; pos = copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; WARN_ON(start > offset + len); end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]); if ((copy = end - offset) > 0) { __wsum csum2; u8 *vaddr; skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); csum2 = csum_partial_copy_nocheck(vaddr + frag->page_offset + offset - start, to, copy, 0); kunmap_atomic(vaddr); csum = csum_block_add(csum, csum2, pos); if (!(len -= copy)) return csum; offset += copy; to += copy; pos += copy; } start = end; } skb_walk_frags(skb, frag_iter) { __wsum csum2; int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; csum2 = skb_copy_and_csum_bits(frag_iter, offset - start, to, copy, 0); csum = csum_block_add(csum, csum2, pos); if ((len -= copy) == 0) return csum; offset += copy; to += copy; pos += copy; } start = end; } BUG_ON(len); return csum; } EXPORT_SYMBOL(skb_copy_and_csum_bits); /** * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy() * @from: source buffer * * Calculates the amount of linear headroom needed in the 'to' skb passed * into skb_zerocopy(). */ unsigned int skb_zerocopy_headlen(const struct sk_buff *from) { unsigned int hlen = 0; if (!from->head_frag || skb_headlen(from) < L1_CACHE_BYTES || skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) hlen = skb_headlen(from); if (skb_has_frag_list(from)) hlen = from->len; return hlen; } EXPORT_SYMBOL_GPL(skb_zerocopy_headlen); /** * skb_zerocopy - Zero copy skb to skb * @to: destination buffer * @from: source buffer * @len: number of bytes to copy from source buffer * @hlen: size of linear headroom in destination buffer * * Copies up to `len` bytes from `from` to `to` by creating references * to the frags in the source buffer. * * The `hlen` as calculated by skb_zerocopy_headlen() specifies the * headroom in the `to` buffer. * * Return value: * 0: everything is OK * -ENOMEM: couldn't orphan frags of @from due to lack of memory * -EFAULT: skb_copy_bits() found some problem with skb geometry */ int skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen) { int i, j = 0; int plen = 0; /* length of skb->head fragment */ int ret; struct page *page; unsigned int offset; BUG_ON(!from->head_frag && !hlen); /* dont bother with small payloads */ if (len <= skb_tailroom(to)) return skb_copy_bits(from, 0, skb_put(to, len), len); if (hlen) { ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen); if (unlikely(ret)) return ret; len -= hlen; } else { plen = min_t(int, skb_headlen(from), len); if (plen) { page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); __skb_fill_page_desc(to, 0, page, offset, plen); get_page(page); j = 1; len -= plen; } } to->truesize += len + plen; to->len += len + plen; to->data_len += len + plen; if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) { skb_tx_error(from); return -ENOMEM; } for (i = 0; i < skb_shinfo(from)->nr_frags; i++) { if (!len) break; skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i]; skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len); len -= skb_shinfo(to)->frags[j].size; skb_frag_ref(to, j); j++; } skb_shinfo(to)->nr_frags = j; return 0; } EXPORT_SYMBOL_GPL(skb_zerocopy); void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to) { __wsum csum; long csstart; if (skb->ip_summed == CHECKSUM_PARTIAL) csstart = skb_checksum_start_offset(skb); else csstart = skb_headlen(skb); BUG_ON(csstart > skb_headlen(skb)); skb_copy_from_linear_data(skb, to, csstart); csum = 0; if (csstart != skb->len) csum = skb_copy_and_csum_bits(skb, csstart, to + csstart, skb->len - csstart, 0); if (skb->ip_summed == CHECKSUM_PARTIAL) { long csstuff = csstart + skb->csum_offset; *((__sum16 *)(to + csstuff)) = csum_fold(csum); } } EXPORT_SYMBOL(skb_copy_and_csum_dev); /** * skb_dequeue - remove from the head of the queue * @list: list to dequeue from * * Remove the head of the list. The list lock is taken so the function * may be used safely with other locking list functions. The head item is * returned or %NULL if the list is empty. */ struct sk_buff *skb_dequeue(struct sk_buff_head *list) { unsigned long flags; struct sk_buff *result; spin_lock_irqsave(&list->lock, flags); result = __skb_dequeue(list); spin_unlock_irqrestore(&list->lock, flags); return result; } EXPORT_SYMBOL(skb_dequeue); /** * skb_dequeue_tail - remove from the tail of the queue * @list: list to dequeue from * * Remove the tail of the list. The list lock is taken so the function * may be used safely with other locking list functions. The tail item is * returned or %NULL if the list is empty. */ struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list) { unsigned long flags; struct sk_buff *result; spin_lock_irqsave(&list->lock, flags); result = __skb_dequeue_tail(list); spin_unlock_irqrestore(&list->lock, flags); return result; } EXPORT_SYMBOL(skb_dequeue_tail); /** * skb_queue_purge - empty a list * @list: list to empty * * Delete all buffers on an &sk_buff list. Each buffer is removed from * the list and one reference dropped. This function takes the list * lock and is atomic with respect to other list locking functions. */ void skb_queue_purge(struct sk_buff_head *list) { struct sk_buff *skb; while ((skb = skb_dequeue(list)) != NULL) kfree_skb(skb); } EXPORT_SYMBOL(skb_queue_purge); /** * skb_rbtree_purge - empty a skb rbtree * @root: root of the rbtree to empty * * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from * the list and one reference dropped. This function does not take * any lock. Synchronization should be handled by the caller (e.g., TCP * out-of-order queue is protected by the socket lock). */ void skb_rbtree_purge(struct rb_root *root) { struct sk_buff *skb, *next; rbtree_postorder_for_each_entry_safe(skb, next, root, rbnode) kfree_skb(skb); *root = RB_ROOT; } /** * skb_queue_head - queue a buffer at the list head * @list: list to use * @newsk: buffer to queue * * Queue a buffer at the start of the list. This function takes the * list lock and can be used safely with other locking &sk_buff functions * safely. * * A buffer cannot be placed on two lists at the same time. */ void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_head(list, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_queue_head); /** * skb_queue_tail - queue a buffer at the list tail * @list: list to use * @newsk: buffer to queue * * Queue a buffer at the tail of the list. This function takes the * list lock and can be used safely with other locking &sk_buff functions * safely. * * A buffer cannot be placed on two lists at the same time. */ void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_tail(list, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_queue_tail); /** * skb_unlink - remove a buffer from a list * @skb: buffer to remove * @list: list to use * * Remove a packet from a list. The list locks are taken and this * function is atomic with respect to other list locked calls * * You must know what list the SKB is on. */ void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_unlink(skb, list); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_unlink); /** * skb_append - append a buffer * @old: buffer to insert after * @newsk: buffer to insert * @list: list to use * * Place a packet after a given packet in a list. The list locks are taken * and this function is atomic with respect to other list locked calls. * A buffer cannot be placed on two lists at the same time. */ void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_queue_after(list, old, newsk); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_append); /** * skb_insert - insert a buffer * @old: buffer to insert before * @newsk: buffer to insert * @list: list to use * * Place a packet before a given packet in a list. The list locks are * taken and this function is atomic with respect to other list locked * calls. * * A buffer cannot be placed on two lists at the same time. */ void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list) { unsigned long flags; spin_lock_irqsave(&list->lock, flags); __skb_insert(newsk, old->prev, old, list); spin_unlock_irqrestore(&list->lock, flags); } EXPORT_SYMBOL(skb_insert); static inline void skb_split_inside_header(struct sk_buff *skb, struct sk_buff* skb1, const u32 len, const int pos) { int i; skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len), pos - len); /* And move data appendix as is. */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i]; skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags; skb_shinfo(skb)->nr_frags = 0; skb1->data_len = skb->data_len; skb1->len += skb1->data_len; skb->data_len = 0; skb->len = len; skb_set_tail_pointer(skb, len); } static inline void skb_split_no_header(struct sk_buff *skb, struct sk_buff* skb1, const u32 len, int pos) { int i, k = 0; const int nfrags = skb_shinfo(skb)->nr_frags; skb_shinfo(skb)->nr_frags = 0; skb1->len = skb1->data_len = skb->len - len; skb->len = len; skb->data_len = len - pos; for (i = 0; i < nfrags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (pos + size > len) { skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i]; if (pos < len) { /* Split frag. * We have two variants in this case: * 1. Move all the frag to the second * part, if it is possible. F.e. * this approach is mandatory for TUX, * where splitting is expensive. * 2. Split is accurately. We make this. */ skb_frag_ref(skb, i); skb_shinfo(skb1)->frags[0].page_offset += len - pos; skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos); skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos); skb_shinfo(skb)->nr_frags++; } k++; } else skb_shinfo(skb)->nr_frags++; pos += size; } skb_shinfo(skb1)->nr_frags = k; } /** * skb_split - Split fragmented skb to two parts at length len. * @skb: the buffer to split * @skb1: the buffer to receive the second part * @len: new length for skb */ void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len) { int pos = skb_headlen(skb); skb_shinfo(skb1)->tx_flags = skb_shinfo(skb)->tx_flags & SKBTX_SHARED_FRAG; if (len < pos) /* Split line is inside header. */ skb_split_inside_header(skb, skb1, len, pos); else /* Second chunk has no header, nothing to copy. */ skb_split_no_header(skb, skb1, len, pos); } EXPORT_SYMBOL(skb_split); /* Shifting from/to a cloned skb is a no-go. * * Caller cannot keep skb_shinfo related pointers past calling here! */ static int skb_prepare_for_shift(struct sk_buff *skb) { return skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC); } /** * skb_shift - Shifts paged data partially from skb to another * @tgt: buffer into which tail data gets added * @skb: buffer from which the paged data comes from * @shiftlen: shift up to this many bytes * * Attempts to shift up to shiftlen worth of bytes, which may be less than * the length of the skb, from skb to tgt. Returns number bytes shifted. * It's up to caller to free skb if everything was shifted. * * If @tgt runs out of frags, the whole operation is aborted. * * Skb cannot include anything else but paged data while tgt is allowed * to have non-paged data as well. * * TODO: full sized shift could be optimized but that would need * specialized skb free'er to handle frags without up-to-date nr_frags. */ int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen) { int from, to, merge, todo; struct skb_frag_struct *fragfrom, *fragto; BUG_ON(shiftlen > skb->len); if (skb_headlen(skb)) return 0; todo = shiftlen; from = 0; to = skb_shinfo(tgt)->nr_frags; fragfrom = &skb_shinfo(skb)->frags[from]; /* Actual merge is delayed until the point when we know we can * commit all, so that we don't have to undo partial changes */ if (!to || !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom), fragfrom->page_offset)) { merge = -1; } else { merge = to - 1; todo -= skb_frag_size(fragfrom); if (todo < 0) { if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; /* All previous frag pointers might be stale! */ fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, shiftlen); skb_frag_size_sub(fragfrom, shiftlen); fragfrom->page_offset += shiftlen; goto onlymerged; } from++; } /* Skip full, not-fitting skb to avoid expensive operations */ if ((shiftlen == skb->len) && (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to)) return 0; if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) { if (to == MAX_SKB_FRAGS) return 0; fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[to]; if (todo >= skb_frag_size(fragfrom)) { *fragto = *fragfrom; todo -= skb_frag_size(fragfrom); from++; to++; } else { __skb_frag_ref(fragfrom); fragto->page = fragfrom->page; fragto->page_offset = fragfrom->page_offset; skb_frag_size_set(fragto, todo); fragfrom->page_offset += todo; skb_frag_size_sub(fragfrom, todo); todo = 0; to++; break; } } /* Ready to "commit" this state change to tgt */ skb_shinfo(tgt)->nr_frags = to; if (merge >= 0) { fragfrom = &skb_shinfo(skb)->frags[0]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, skb_frag_size(fragfrom)); __skb_frag_unref(fragfrom); } /* Reposition in the original skb */ to = 0; while (from < skb_shinfo(skb)->nr_frags) skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++]; skb_shinfo(skb)->nr_frags = to; BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags); onlymerged: /* Most likely the tgt won't ever need its checksum anymore, skb on * the other hand might need it if it needs to be resent */ tgt->ip_summed = CHECKSUM_PARTIAL; skb->ip_summed = CHECKSUM_PARTIAL; /* Yak, is it really working this way? Some helper please? */ skb->len -= shiftlen; skb->data_len -= shiftlen; skb->truesize -= shiftlen; tgt->len += shiftlen; tgt->data_len += shiftlen; tgt->truesize += shiftlen; return shiftlen; } /** * skb_prepare_seq_read - Prepare a sequential read of skb data * @skb: the buffer to read * @from: lower offset of data to be read * @to: upper offset of data to be read * @st: state variable * * Initializes the specified state variable. Must be called before * invoking skb_seq_read() for the first time. */ void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from, unsigned int to, struct skb_seq_state *st) { st->lower_offset = from; st->upper_offset = to; st->root_skb = st->cur_skb = skb; st->frag_idx = st->stepped_offset = 0; st->frag_data = NULL; } EXPORT_SYMBOL(skb_prepare_seq_read); /** * skb_seq_read - Sequentially read skb data * @consumed: number of bytes consumed by the caller so far * @data: destination pointer for data to be returned * @st: state variable * * Reads a block of skb data at @consumed relative to the * lower offset specified to skb_prepare_seq_read(). Assigns * the head of the data block to @data and returns the length * of the block or 0 if the end of the skb data or the upper * offset has been reached. * * The caller is not required to consume all of the data * returned, i.e. @consumed is typically set to the number * of bytes already consumed and the next call to * skb_seq_read() will return the remaining part of the block. * * Note 1: The size of each block of data returned can be arbitrary, * this limitation is the cost for zerocopy sequential * reads of potentially non linear data. * * Note 2: Fragment lists within fragments are not implemented * at the moment, state->root_skb could be replaced with * a stack for this purpose. */ unsigned int skb_seq_read(unsigned int consumed, const u8 **data, struct skb_seq_state *st) { unsigned int block_limit, abs_offset = consumed + st->lower_offset; skb_frag_t *frag; if (unlikely(abs_offset >= st->upper_offset)) { if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } return 0; } next_skb: block_limit = skb_headlen(st->cur_skb) + st->stepped_offset; if (abs_offset < block_limit && !st->frag_data) { *data = st->cur_skb->data + (abs_offset - st->stepped_offset); return block_limit - abs_offset; } if (st->frag_idx == 0 && !st->frag_data) st->stepped_offset += skb_headlen(st->cur_skb); while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) { frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx]; block_limit = skb_frag_size(frag) + st->stepped_offset; if (abs_offset < block_limit) { if (!st->frag_data) st->frag_data = kmap_atomic(skb_frag_page(frag)); *data = (u8 *) st->frag_data + frag->page_offset + (abs_offset - st->stepped_offset); return block_limit - abs_offset; } if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } st->frag_idx++; st->stepped_offset += skb_frag_size(frag); } if (st->frag_data) { kunmap_atomic(st->frag_data); st->frag_data = NULL; } if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) { st->cur_skb = skb_shinfo(st->root_skb)->frag_list; st->frag_idx = 0; goto next_skb; } else if (st->cur_skb->next) { st->cur_skb = st->cur_skb->next; st->frag_idx = 0; goto next_skb; } return 0; } EXPORT_SYMBOL(skb_seq_read); /** * skb_abort_seq_read - Abort a sequential read of skb data * @st: state variable * * Must be called if skb_seq_read() was not called until it * returned 0. */ void skb_abort_seq_read(struct skb_seq_state *st) { if (st->frag_data) kunmap_atomic(st->frag_data); } EXPORT_SYMBOL(skb_abort_seq_read); #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb)) static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text, struct ts_config *conf, struct ts_state *state) { return skb_seq_read(offset, text, TS_SKB_CB(state)); } static void skb_ts_finish(struct ts_config *conf, struct ts_state *state) { skb_abort_seq_read(TS_SKB_CB(state)); } /** * skb_find_text - Find a text pattern in skb data * @skb: the buffer to look in * @from: search offset * @to: search limit * @config: textsearch configuration * * Finds a pattern in the skb data according to the specified * textsearch configuration. Use textsearch_next() to retrieve * subsequent occurrences of the pattern. Returns the offset * to the first occurrence or UINT_MAX if no match was found. */ unsigned int skb_find_text(struct sk_buff *skb, unsigned int from, unsigned int to, struct ts_config *config) { struct ts_state state; unsigned int ret; config->get_next_block = skb_ts_get_next_block; config->finish = skb_ts_finish; skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state)); ret = textsearch_find(config, &state); return (ret <= to - from ? ret : UINT_MAX); } EXPORT_SYMBOL(skb_find_text); /** * skb_append_datato_frags - append the user data to a skb * @sk: sock structure * @skb: skb structure to be appended with user data. * @getfrag: call back function to be used for getting the user data * @from: pointer to user message iov * @length: length of the iov message * * Description: This procedure append the user data in the fragment part * of the skb if any page alloc fails user this procedure returns -ENOMEM */ int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb, int (*getfrag)(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length) { int frg_cnt = skb_shinfo(skb)->nr_frags; int copy; int offset = 0; int ret; struct page_frag *pfrag = &current->task_frag; do { /* Return error if we don't have space for new frag */ if (frg_cnt >= MAX_SKB_FRAGS) return -EMSGSIZE; if (!sk_page_frag_refill(sk, pfrag)) return -ENOMEM; /* copy the user data to page */ copy = min_t(int, length, pfrag->size - pfrag->offset); ret = getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, 0, skb); if (ret < 0) return -EFAULT; /* copy was successful so update the size parameters */ skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset, copy); frg_cnt++; pfrag->offset += copy; get_page(pfrag->page); skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); skb->len += copy; skb->data_len += copy; offset += copy; length -= copy; } while (length > 0); return 0; } EXPORT_SYMBOL(skb_append_datato_frags); int skb_append_pagefrags(struct sk_buff *skb, struct page *page, int offset, size_t size) { int i = skb_shinfo(skb)->nr_frags; if (skb_can_coalesce(skb, i, page, offset)) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size); } else if (i < MAX_SKB_FRAGS) { get_page(page); skb_fill_page_desc(skb, i, page, offset, size); } else { return -EMSGSIZE; } return 0; } EXPORT_SYMBOL_GPL(skb_append_pagefrags); /** * skb_pull_rcsum - pull skb and update receive checksum * @skb: buffer to update * @len: length of data pulled * * This function performs an skb_pull on the packet and updates * the CHECKSUM_COMPLETE checksum. It should be used on * receive path processing instead of skb_pull unless you know * that the checksum difference is zero (e.g., a valid IP header) * or you are setting ip_summed to CHECKSUM_NONE. */ unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len) { unsigned char *data = skb->data; BUG_ON(len > skb->len); __skb_pull(skb, len); skb_postpull_rcsum(skb, data, len); return skb->data; } EXPORT_SYMBOL_GPL(skb_pull_rcsum); /** * skb_segment - Perform protocol segmentation on skb. * @head_skb: buffer to segment * @features: features for the output path (see dev->features) * * This function performs segmentation on the given skb. It returns * a pointer to the first in a list of new skbs for the segments. * In case of error it returns ERR_PTR(err). */ struct sk_buff *skb_segment(struct sk_buff *head_skb, netdev_features_t features) { struct sk_buff *segs = NULL; struct sk_buff *tail = NULL; struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; skb_frag_t *frag = skb_shinfo(head_skb)->frags; unsigned int mss = skb_shinfo(head_skb)->gso_size; unsigned int doffset = head_skb->data - skb_mac_header(head_skb); struct sk_buff *frag_skb = head_skb; unsigned int offset = doffset; unsigned int tnl_hlen = skb_tnl_header_len(head_skb); unsigned int partial_segs = 0; unsigned int headroom; unsigned int len = head_skb->len; __be16 proto; bool csum, sg; int nfrags = skb_shinfo(head_skb)->nr_frags; int err = -ENOMEM; int i = 0; int pos; int dummy; __skb_push(head_skb, doffset); proto = skb_network_protocol(head_skb, &dummy); if (unlikely(!proto)) return ERR_PTR(-EINVAL); sg = !!(features & NETIF_F_SG); csum = !!can_checksum_protocol(features, proto); if (sg && csum && (mss != GSO_BY_FRAGS)) { if (!(features & NETIF_F_GSO_PARTIAL)) { struct sk_buff *iter; if (!list_skb || !net_gso_ok(features, skb_shinfo(head_skb)->gso_type)) goto normal; /* Split the buffer at the frag_list pointer. * This is based on the assumption that all * buffers in the chain excluding the last * containing the same amount of data. */ skb_walk_frags(head_skb, iter) { if (skb_headlen(iter)) goto normal; len -= iter->len; } } /* GSO partial only requires that we trim off any excess that * doesn't fit into an MSS sized block, so take care of that * now. */ partial_segs = len / mss; if (partial_segs > 1) mss *= partial_segs; else partial_segs = 0; } normal: headroom = skb_headroom(head_skb); pos = skb_headlen(head_skb); do { struct sk_buff *nskb; skb_frag_t *nskb_frag; int hsize; int size; if (unlikely(mss == GSO_BY_FRAGS)) { len = list_skb->len; } else { len = head_skb->len - offset; if (len > mss) len = mss; } hsize = skb_headlen(head_skb) - offset; if (hsize < 0) hsize = 0; if (hsize > len || !sg) hsize = len; if (!hsize && i >= nfrags && skb_headlen(list_skb) && (skb_headlen(list_skb) == len || sg)) { BUG_ON(skb_headlen(list_skb) > len); i = 0; nfrags = skb_shinfo(list_skb)->nr_frags; frag = skb_shinfo(list_skb)->frags; frag_skb = list_skb; pos += skb_headlen(list_skb); while (pos < offset + len) { BUG_ON(i >= nfrags); size = skb_frag_size(frag); if (pos + size > offset + len) break; i++; pos += size; frag++; } nskb = skb_clone(list_skb, GFP_ATOMIC); list_skb = list_skb->next; if (unlikely(!nskb)) goto err; if (unlikely(pskb_trim(nskb, len))) { kfree_skb(nskb); goto err; } hsize = skb_end_offset(nskb); if (skb_cow_head(nskb, doffset + headroom)) { kfree_skb(nskb); goto err; } nskb->truesize += skb_end_offset(nskb) - hsize; skb_release_head_state(nskb); __skb_push(nskb, doffset); } else { nskb = __alloc_skb(hsize + doffset + headroom, GFP_ATOMIC, skb_alloc_rx_flag(head_skb), NUMA_NO_NODE); if (unlikely(!nskb)) goto err; skb_reserve(nskb, headroom); __skb_put(nskb, doffset); } if (segs) tail->next = nskb; else segs = nskb; tail = nskb; __copy_skb_header(nskb, head_skb); skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); skb_reset_mac_len(nskb); skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, nskb->data - tnl_hlen, doffset + tnl_hlen); if (nskb->len == len + doffset) goto perform_csum_check; if (!sg) { if (!nskb->remcsum_offload) nskb->ip_summed = CHECKSUM_NONE; SKB_GSO_CB(nskb)->csum = skb_copy_and_csum_bits(head_skb, offset, skb_put(nskb, len), len, 0); SKB_GSO_CB(nskb)->csum_start = skb_headroom(nskb) + doffset; continue; } nskb_frag = skb_shinfo(nskb)->frags; skb_copy_from_linear_data_offset(head_skb, offset, skb_put(nskb, hsize), hsize); skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & SKBTX_SHARED_FRAG; while (pos < offset + len) { if (i >= nfrags) { BUG_ON(skb_headlen(list_skb)); i = 0; nfrags = skb_shinfo(list_skb)->nr_frags; frag = skb_shinfo(list_skb)->frags; frag_skb = list_skb; BUG_ON(!nfrags); list_skb = list_skb->next; } if (unlikely(skb_shinfo(nskb)->nr_frags >= MAX_SKB_FRAGS)) { net_warn_ratelimited( "skb_segment: too many frags: %u %u\n", pos, mss); goto err; } if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC))) goto err; *nskb_frag = *frag; __skb_frag_ref(nskb_frag); size = skb_frag_size(nskb_frag); if (pos < offset) { nskb_frag->page_offset += offset - pos; skb_frag_size_sub(nskb_frag, offset - pos); } skb_shinfo(nskb)->nr_frags++; if (pos + size <= offset + len) { i++; frag++; pos += size; } else { skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); goto skip_fraglist; } nskb_frag++; } skip_fraglist: nskb->data_len = len - hsize; nskb->len += nskb->data_len; nskb->truesize += nskb->data_len; perform_csum_check: if (!csum) { if (skb_has_shared_frag(nskb)) { err = __skb_linearize(nskb); if (err) goto err; } if (!nskb->remcsum_offload) nskb->ip_summed = CHECKSUM_NONE; SKB_GSO_CB(nskb)->csum = skb_checksum(nskb, doffset, nskb->len - doffset, 0); SKB_GSO_CB(nskb)->csum_start = skb_headroom(nskb) + doffset; } } while ((offset += len) < head_skb->len); /* Some callers want to get the end of the list. * Put it in segs->prev to avoid walking the list. * (see validate_xmit_skb_list() for example) */ segs->prev = tail; if (partial_segs) { struct sk_buff *iter; int type = skb_shinfo(head_skb)->gso_type; unsigned short gso_size = skb_shinfo(head_skb)->gso_size; /* Update type to add partial and then remove dodgy if set */ type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL; type &= ~SKB_GSO_DODGY; /* Update GSO info and prepare to start updating headers on * our way back down the stack of protocols. */ for (iter = segs; iter; iter = iter->next) { skb_shinfo(iter)->gso_size = gso_size; skb_shinfo(iter)->gso_segs = partial_segs; skb_shinfo(iter)->gso_type = type; SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset; } if (tail->len - doffset <= gso_size) skb_shinfo(tail)->gso_size = 0; else if (tail != segs) skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size); } /* Following permits correct backpressure, for protocols * using skb_set_owner_w(). * Idea is to tranfert ownership from head_skb to last segment. */ if (head_skb->destructor == sock_wfree) { swap(tail->truesize, head_skb->truesize); swap(tail->destructor, head_skb->destructor); swap(tail->sk, head_skb->sk); } return segs; err: kfree_skb_list(segs); return ERR_PTR(err); } EXPORT_SYMBOL_GPL(skb_segment); int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb) { struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb); unsigned int offset = skb_gro_offset(skb); unsigned int headlen = skb_headlen(skb); unsigned int len = skb_gro_len(skb); struct sk_buff *lp, *p = *head; unsigned int delta_truesize; if (unlikely(p->len + len >= 65536)) return -E2BIG; lp = NAPI_GRO_CB(p)->last; pinfo = skb_shinfo(lp); if (headlen <= offset) { skb_frag_t *frag; skb_frag_t *frag2; int i = skbinfo->nr_frags; int nr_frags = pinfo->nr_frags + i; if (nr_frags > MAX_SKB_FRAGS) goto merge; offset -= headlen; pinfo->nr_frags = nr_frags; skbinfo->nr_frags = 0; frag = pinfo->frags + nr_frags; frag2 = skbinfo->frags + i; do { *--frag = *--frag2; } while (--i); frag->page_offset += offset; skb_frag_size_sub(frag, offset); /* all fragments truesize : remove (head size + sk_buff) */ delta_truesize = skb->truesize - SKB_TRUESIZE(skb_end_offset(skb)); skb->truesize -= skb->data_len; skb->len -= skb->data_len; skb->data_len = 0; NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE; goto done; } else if (skb->head_frag) { int nr_frags = pinfo->nr_frags; skb_frag_t *frag = pinfo->frags + nr_frags; struct page *page = virt_to_head_page(skb->head); unsigned int first_size = headlen - offset; unsigned int first_offset; if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS) goto merge; first_offset = skb->data - (unsigned char *)page_address(page) + offset; pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags; frag->page.p = page; frag->page_offset = first_offset; skb_frag_size_set(frag, first_size); memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags); /* We dont need to clear skbinfo->nr_frags here */ delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff)); NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD; goto done; } merge: delta_truesize = skb->truesize; if (offset > headlen) { unsigned int eat = offset - headlen; skbinfo->frags[0].page_offset += eat; skb_frag_size_sub(&skbinfo->frags[0], eat); skb->data_len -= eat; skb->len -= eat; offset = headlen; } __skb_pull(skb, offset); if (NAPI_GRO_CB(p)->last == p) skb_shinfo(p)->frag_list = skb; else NAPI_GRO_CB(p)->last->next = skb; NAPI_GRO_CB(p)->last = skb; __skb_header_release(skb); lp = p; done: NAPI_GRO_CB(p)->count++; p->data_len += len; p->truesize += delta_truesize; p->len += len; if (lp != p) { lp->data_len += len; lp->truesize += delta_truesize; lp->len += len; } NAPI_GRO_CB(skb)->same_flow = 1; return 0; } EXPORT_SYMBOL_GPL(skb_gro_receive); void __init skb_init(void) { skbuff_head_cache = kmem_cache_create("skbuff_head_cache", sizeof(struct sk_buff), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache", sizeof(struct sk_buff_fclones), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } /** * skb_to_sgvec - Fill a scatter-gather list from a socket buffer * @skb: Socket buffer containing the buffers to be mapped * @sg: The scatter-gather list to map into * @offset: The offset into the buffer's contents to start mapping * @len: Length of buffer space to be mapped * * Fill the specified scatter-gather list with mappings/pointers into a * region of the buffer space attached to a socket buffer. */ static int __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int elt = 0; if (copy > 0) { if (copy > len) copy = len; sg_set_buf(sg, skb->data + offset, copy); elt++; if ((len -= copy) == 0) return elt; offset += copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; WARN_ON(start > offset + len); end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]); if ((copy = end - offset) > 0) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (copy > len) copy = len; sg_set_page(&sg[elt], skb_frag_page(frag), copy, frag->page_offset+offset-start); elt++; if (!(len -= copy)) return elt; offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; elt += __skb_to_sgvec(frag_iter, sg+elt, offset - start, copy); if ((len -= copy) == 0) return elt; offset += copy; } start = end; } BUG_ON(len); return elt; } /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given * sglist without mark the sg which contain last skb data as the end. * So the caller can mannipulate sg list as will when padding new data after * the first call without calling sg_unmark_end to expend sg list. * * Scenario to use skb_to_sgvec_nomark: * 1. sg_init_table * 2. skb_to_sgvec_nomark(payload1) * 3. skb_to_sgvec_nomark(payload2) * * This is equivalent to: * 1. sg_init_table * 2. skb_to_sgvec(payload1) * 3. sg_unmark_end * 4. skb_to_sgvec(payload2) * * When mapping mutilple payload conditionally, skb_to_sgvec_nomark * is more preferable. */ int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { return __skb_to_sgvec(skb, sg, offset, len); } EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark); int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len) { int nsg = __skb_to_sgvec(skb, sg, offset, len); sg_mark_end(&sg[nsg - 1]); return nsg; } EXPORT_SYMBOL_GPL(skb_to_sgvec); /** * skb_cow_data - Check that a socket buffer's data buffers are writable * @skb: The socket buffer to check. * @tailbits: Amount of trailing space to be added * @trailer: Returned pointer to the skb where the @tailbits space begins * * Make sure that the data buffers attached to a socket buffer are * writable. If they are not, private copies are made of the data buffers * and the socket buffer is set to use these instead. * * If @tailbits is given, make sure that there is space to write @tailbits * bytes of data beyond current end of socket buffer. @trailer will be * set to point to the skb in which this space begins. * * The number of scatterlist elements required to completely map the * COW'd and extended socket buffer will be returned. */ int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer) { int copyflag; int elt; struct sk_buff *skb1, **skb_p; /* If skb is cloned or its head is paged, reallocate * head pulling out all the pages (pages are considered not writable * at the moment even if they are anonymous). */ if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) && __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL) return -ENOMEM; /* Easy case. Most of packets will go this way. */ if (!skb_has_frag_list(skb)) { /* A little of trouble, not enough of space for trailer. * This should not happen, when stack is tuned to generate * good frames. OK, on miss we reallocate and reserve even more * space, 128 bytes is fair. */ if (skb_tailroom(skb) < tailbits && pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC)) return -ENOMEM; /* Voila! */ *trailer = skb; return 1; } /* Misery. We are in troubles, going to mincer fragments... */ elt = 1; skb_p = &skb_shinfo(skb)->frag_list; copyflag = 0; while ((skb1 = *skb_p) != NULL) { int ntail = 0; /* The fragment is partially pulled by someone, * this can happen on input. Copy it and everything * after it. */ if (skb_shared(skb1)) copyflag = 1; /* If the skb is the last, worry about trailer. */ if (skb1->next == NULL && tailbits) { if (skb_shinfo(skb1)->nr_frags || skb_has_frag_list(skb1) || skb_tailroom(skb1) < tailbits) ntail = tailbits + 128; } if (copyflag || skb_cloned(skb1) || ntail || skb_shinfo(skb1)->nr_frags || skb_has_frag_list(skb1)) { struct sk_buff *skb2; /* Fuck, we are miserable poor guys... */ if (ntail == 0) skb2 = skb_copy(skb1, GFP_ATOMIC); else skb2 = skb_copy_expand(skb1, skb_headroom(skb1), ntail, GFP_ATOMIC); if (unlikely(skb2 == NULL)) return -ENOMEM; if (skb1->sk) skb_set_owner_w(skb2, skb1->sk); /* Looking around. Are we still alive? * OK, link new skb, drop old one */ skb2->next = skb1->next; *skb_p = skb2; kfree_skb(skb1); skb1 = skb2; } elt++; *trailer = skb1; skb_p = &skb1->next; } return elt; } EXPORT_SYMBOL_GPL(skb_cow_data); static void sock_rmem_free(struct sk_buff *skb) { struct sock *sk = skb->sk; atomic_sub(skb->truesize, &sk->sk_rmem_alloc); } static void skb_set_err_queue(struct sk_buff *skb) { /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING. * So, it is safe to (mis)use it to mark skbs on the error queue. */ skb->pkt_type = PACKET_OUTGOING; BUILD_BUG_ON(PACKET_OUTGOING == 0); } /* * Note: We dont mem charge error packets (no sk_forward_alloc changes) */ int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf) return -ENOMEM; skb_orphan(skb); skb->sk = sk; skb->destructor = sock_rmem_free; atomic_add(skb->truesize, &sk->sk_rmem_alloc); skb_set_err_queue(skb); /* before exiting rcu section, make sure dst is refcounted */ skb_dst_force(skb); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(sock_queue_err_skb); static bool is_icmp_err_skb(const struct sk_buff *skb) { return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP || SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6); } struct sk_buff *sock_dequeue_err_skb(struct sock *sk) { struct sk_buff_head *q = &sk->sk_error_queue; struct sk_buff *skb, *skb_next = NULL; bool icmp_next = false; unsigned long flags; spin_lock_irqsave(&q->lock, flags); skb = __skb_dequeue(q); if (skb && (skb_next = skb_peek(q))) icmp_next = is_icmp_err_skb(skb_next); spin_unlock_irqrestore(&q->lock, flags); if (is_icmp_err_skb(skb) && !icmp_next) sk->sk_err = 0; if (skb_next) sk->sk_error_report(sk); return skb; } EXPORT_SYMBOL(sock_dequeue_err_skb); /** * skb_clone_sk - create clone of skb, and take reference to socket * @skb: the skb to clone * * This function creates a clone of a buffer that holds a reference on * sk_refcnt. Buffers created via this function are meant to be * returned using sock_queue_err_skb, or free via kfree_skb. * * When passing buffers allocated with this function to sock_queue_err_skb * it is necessary to wrap the call with sock_hold/sock_put in order to * prevent the socket from being released prior to being enqueued on * the sk_error_queue. */ struct sk_buff *skb_clone_sk(struct sk_buff *skb) { struct sock *sk = skb->sk; struct sk_buff *clone; if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt)) return NULL; clone = skb_clone(skb, GFP_ATOMIC); if (!clone) { sock_put(sk); return NULL; } clone->sk = sk; clone->destructor = sock_efree; return clone; } EXPORT_SYMBOL(skb_clone_sk); static void __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype) { struct sock_exterr_skb *serr; int err; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); } static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly) { bool ret; if (likely(sysctl_tstamp_allow_data || tsonly)) return true; read_lock_bh(&sk->sk_callback_lock); ret = sk->sk_socket && sk->sk_socket->file && file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW); read_unlock_bh(&sk->sk_callback_lock); return ret; } void skb_complete_tx_timestamp(struct sk_buff *skb, struct skb_shared_hwtstamps *hwtstamps) { struct sock *sk = skb->sk; if (!skb_may_tx_timestamp(sk, false)) return; /* Take a reference to prevent skb_orphan() from freeing the socket, * but only if the socket refcount is not zero. */ if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) { *skb_hwtstamps(skb) = *hwtstamps; __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND); sock_put(sk); } } EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp); void __skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps, struct sock *sk, int tstype) { struct sk_buff *skb; bool tsonly; if (!sk) return; tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY; if (!skb_may_tx_timestamp(sk, tsonly)) return; if (tsonly) { #ifdef CONFIG_INET if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) && sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) skb = tcp_get_timestamping_opt_stats(sk); else #endif skb = alloc_skb(0, GFP_ATOMIC); } else { skb = skb_clone(orig_skb, GFP_ATOMIC); } if (!skb) return; if (tsonly) { skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags; skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey; } if (hwtstamps) *skb_hwtstamps(skb) = *hwtstamps; else skb->tstamp = ktime_get_real(); __skb_complete_tx_timestamp(skb, sk, tstype); } EXPORT_SYMBOL_GPL(__skb_tstamp_tx); void skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps) { return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk, SCM_TSTAMP_SND); } EXPORT_SYMBOL_GPL(skb_tstamp_tx); void skb_complete_wifi_ack(struct sk_buff *skb, bool acked) { struct sock *sk = skb->sk; struct sock_exterr_skb *serr; int err = 1; skb->wifi_acked_valid = 1; skb->wifi_acked = acked; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS; /* Take a reference to prevent skb_orphan() from freeing the socket, * but only if the socket refcount is not zero. */ if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) { err = sock_queue_err_skb(sk, skb); sock_put(sk); } if (err) kfree_skb(skb); } EXPORT_SYMBOL_GPL(skb_complete_wifi_ack); /** * skb_partial_csum_set - set up and verify partial csum values for packet * @skb: the skb to set * @start: the number of bytes after skb->data to start checksumming. * @off: the offset from start to place the checksum. * * For untrusted partially-checksummed packets, we need to make sure the values * for skb->csum_start and skb->csum_offset are valid so we don't oops. * * This function checks and sets those values and skb->ip_summed: if this * returns false you should drop the packet. */ bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off) { if (unlikely(start > skb_headlen(skb)) || unlikely((int)start + off > skb_headlen(skb) - 2)) { net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n", start, off, skb_headlen(skb)); return false; } skb->ip_summed = CHECKSUM_PARTIAL; skb->csum_start = skb_headroom(skb) + start; skb->csum_offset = off; skb_set_transport_header(skb, start); return true; } EXPORT_SYMBOL_GPL(skb_partial_csum_set); static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len, unsigned int max) { if (skb_headlen(skb) >= len) return 0; /* If we need to pullup then pullup to the max, so we * won't need to do it again. */ if (max > skb->len) max = skb->len; if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL) return -ENOMEM; if (skb_headlen(skb) < len) return -EPROTO; return 0; } #define MAX_TCP_HDR_LEN (15 * 4) static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb, typeof(IPPROTO_IP) proto, unsigned int off) { switch (proto) { int err; case IPPROTO_TCP: err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr), off + MAX_TCP_HDR_LEN); if (!err && !skb_partial_csum_set(skb, off, offsetof(struct tcphdr, check))) err = -EPROTO; return err ? ERR_PTR(err) : &tcp_hdr(skb)->check; case IPPROTO_UDP: err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr), off + sizeof(struct udphdr)); if (!err && !skb_partial_csum_set(skb, off, offsetof(struct udphdr, check))) err = -EPROTO; return err ? ERR_PTR(err) : &udp_hdr(skb)->check; } return ERR_PTR(-EPROTO); } /* This value should be large enough to cover a tagged ethernet header plus * maximally sized IP and TCP or UDP headers. */ #define MAX_IP_HDR_LEN 128 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate) { unsigned int off; bool fragment; __sum16 *csum; int err; fragment = false; err = skb_maybe_pull_tail(skb, sizeof(struct iphdr), MAX_IP_HDR_LEN); if (err < 0) goto out; if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF)) fragment = true; off = ip_hdrlen(skb); err = -EPROTO; if (fragment) goto out; csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off); if (IS_ERR(csum)) return PTR_ERR(csum); if (recalculate) *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr, ip_hdr(skb)->daddr, skb->len - off, ip_hdr(skb)->protocol, 0); err = 0; out: return err; } /* This value should be large enough to cover a tagged ethernet header plus * an IPv6 header, all options, and a maximal TCP or UDP header. */ #define MAX_IPV6_HDR_LEN 256 #define OPT_HDR(type, skb, off) \ (type *)(skb_network_header(skb) + (off)) static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate) { int err; u8 nexthdr; unsigned int off; unsigned int len; bool fragment; bool done; __sum16 *csum; fragment = false; done = false; off = sizeof(struct ipv6hdr); err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN); if (err < 0) goto out; nexthdr = ipv6_hdr(skb)->nexthdr; len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len); while (off <= len && !done) { switch (nexthdr) { case IPPROTO_DSTOPTS: case IPPROTO_HOPOPTS: case IPPROTO_ROUTING: { struct ipv6_opt_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct ipv6_opt_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct ipv6_opt_hdr, skb, off); nexthdr = hp->nexthdr; off += ipv6_optlen(hp); break; } case IPPROTO_AH: { struct ip_auth_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct ip_auth_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct ip_auth_hdr, skb, off); nexthdr = hp->nexthdr; off += ipv6_authlen(hp); break; } case IPPROTO_FRAGMENT: { struct frag_hdr *hp; err = skb_maybe_pull_tail(skb, off + sizeof(struct frag_hdr), MAX_IPV6_HDR_LEN); if (err < 0) goto out; hp = OPT_HDR(struct frag_hdr, skb, off); if (hp->frag_off & htons(IP6_OFFSET | IP6_MF)) fragment = true; nexthdr = hp->nexthdr; off += sizeof(struct frag_hdr); break; } default: done = true; break; } } err = -EPROTO; if (!done || fragment) goto out; csum = skb_checksum_setup_ip(skb, nexthdr, off); if (IS_ERR(csum)) return PTR_ERR(csum); if (recalculate) *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, skb->len - off, nexthdr, 0); err = 0; out: return err; } /** * skb_checksum_setup - set up partial checksum offset * @skb: the skb to set up * @recalculate: if true the pseudo-header checksum will be recalculated */ int skb_checksum_setup(struct sk_buff *skb, bool recalculate) { int err; switch (skb->protocol) { case htons(ETH_P_IP): err = skb_checksum_setup_ipv4(skb, recalculate); break; case htons(ETH_P_IPV6): err = skb_checksum_setup_ipv6(skb, recalculate); break; default: err = -EPROTO; break; } return err; } EXPORT_SYMBOL(skb_checksum_setup); /** * skb_checksum_maybe_trim - maybe trims the given skb * @skb: the skb to check * @transport_len: the data length beyond the network header * * Checks whether the given skb has data beyond the given transport length. * If so, returns a cloned skb trimmed to this transport length. * Otherwise returns the provided skb. Returns NULL in error cases * (e.g. transport_len exceeds skb length or out-of-memory). * * Caller needs to set the skb transport header and free any returned skb if it * differs from the provided skb. */ static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb, unsigned int transport_len) { struct sk_buff *skb_chk; unsigned int len = skb_transport_offset(skb) + transport_len; int ret; if (skb->len < len) return NULL; else if (skb->len == len) return skb; skb_chk = skb_clone(skb, GFP_ATOMIC); if (!skb_chk) return NULL; ret = pskb_trim_rcsum(skb_chk, len); if (ret) { kfree_skb(skb_chk); return NULL; } return skb_chk; } /** * skb_checksum_trimmed - validate checksum of an skb * @skb: the skb to check * @transport_len: the data length beyond the network header * @skb_chkf: checksum function to use * * Applies the given checksum function skb_chkf to the provided skb. * Returns a checked and maybe trimmed skb. Returns NULL on error. * * If the skb has data beyond the given transport length, then a * trimmed & cloned skb is checked and returned. * * Caller needs to set the skb transport header and free any returned skb if it * differs from the provided skb. */ struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb, unsigned int transport_len, __sum16(*skb_chkf)(struct sk_buff *skb)) { struct sk_buff *skb_chk; unsigned int offset = skb_transport_offset(skb); __sum16 ret; skb_chk = skb_checksum_maybe_trim(skb, transport_len); if (!skb_chk) goto err; if (!pskb_may_pull(skb_chk, offset)) goto err; skb_pull_rcsum(skb_chk, offset); ret = skb_chkf(skb_chk); skb_push_rcsum(skb_chk, offset); if (ret) goto err; return skb_chk; err: if (skb_chk && skb_chk != skb) kfree_skb(skb_chk); return NULL; } EXPORT_SYMBOL(skb_checksum_trimmed); void __skb_warn_lro_forwarding(const struct sk_buff *skb) { net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n", skb->dev->name); } EXPORT_SYMBOL(__skb_warn_lro_forwarding); void kfree_skb_partial(struct sk_buff *skb, bool head_stolen) { if (head_stolen) { skb_release_head_state(skb); kmem_cache_free(skbuff_head_cache, skb); } else { __kfree_skb(skb); } } EXPORT_SYMBOL(kfree_skb_partial); /** * skb_try_coalesce - try to merge skb to prior one * @to: prior buffer * @from: buffer to add * @fragstolen: pointer to boolean * @delta_truesize: how much more was allocated than was requested */ bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from, bool *fragstolen, int *delta_truesize) { int i, delta, len = from->len; *fragstolen = false; if (skb_cloned(to)) return false; if (len <= skb_tailroom(to)) { if (len) BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len)); *delta_truesize = 0; return true; } if (skb_has_frag_list(to) || skb_has_frag_list(from)) return false; if (skb_headlen(from) != 0) { struct page *page; unsigned int offset; if (skb_shinfo(to)->nr_frags + skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) return false; if (skb_head_is_locked(from)) return false; delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff)); page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); skb_fill_page_desc(to, skb_shinfo(to)->nr_frags, page, offset, skb_headlen(from)); *fragstolen = true; } else { if (skb_shinfo(to)->nr_frags + skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS) return false; delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from)); } WARN_ON_ONCE(delta < len); memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags, skb_shinfo(from)->frags, skb_shinfo(from)->nr_frags * sizeof(skb_frag_t)); skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags; if (!skb_cloned(from)) skb_shinfo(from)->nr_frags = 0; /* if the skb is not cloned this does nothing * since we set nr_frags to 0. */ for (i = 0; i < skb_shinfo(from)->nr_frags; i++) skb_frag_ref(from, i); to->truesize += delta; to->len += len; to->data_len += len; *delta_truesize = delta; return true; } EXPORT_SYMBOL(skb_try_coalesce); /** * skb_scrub_packet - scrub an skb * * @skb: buffer to clean * @xnet: packet is crossing netns * * skb_scrub_packet can be used after encapsulating or decapsulting a packet * into/from a tunnel. Some information have to be cleared during these * operations. * skb_scrub_packet can also be used to clean a skb before injecting it in * another namespace (@xnet == true). We have to clear all information in the * skb that could impact namespace isolation. */ void skb_scrub_packet(struct sk_buff *skb, bool xnet) { skb->tstamp = 0; skb->pkt_type = PACKET_HOST; skb->skb_iif = 0; skb->ignore_df = 0; skb_dst_drop(skb); secpath_reset(skb); nf_reset(skb); nf_reset_trace(skb); if (!xnet) return; skb_orphan(skb); skb->mark = 0; } EXPORT_SYMBOL_GPL(skb_scrub_packet); /** * skb_gso_transport_seglen - Return length of individual segments of a gso packet * * @skb: GSO skb * * skb_gso_transport_seglen is used to determine the real size of the * individual segments, including Layer4 headers (TCP/UDP). * * The MAC/L2 or network (IP, IPv6) headers are not accounted for. */ unsigned int skb_gso_transport_seglen(const struct sk_buff *skb) { const struct skb_shared_info *shinfo = skb_shinfo(skb); unsigned int thlen = 0; if (skb->encapsulation) { thlen = skb_inner_transport_header(skb) - skb_transport_header(skb); if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) thlen += inner_tcp_hdrlen(skb); } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) { thlen = tcp_hdrlen(skb); } else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) { thlen = sizeof(struct sctphdr); } /* UFO sets gso_size to the size of the fragmentation * payload, i.e. the size of the L4 (UDP) header is already * accounted for. */ return thlen + shinfo->gso_size; } EXPORT_SYMBOL_GPL(skb_gso_transport_seglen); /** * skb_gso_validate_mtu - Return in case such skb fits a given MTU * * @skb: GSO skb * @mtu: MTU to validate against * * skb_gso_validate_mtu validates if a given skb will fit a wanted MTU * once split. */ bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu) { const struct skb_shared_info *shinfo = skb_shinfo(skb); const struct sk_buff *iter; unsigned int hlen; hlen = skb_gso_network_seglen(skb); if (shinfo->gso_size != GSO_BY_FRAGS) return hlen <= mtu; /* Undo this so we can re-use header sizes */ hlen -= GSO_BY_FRAGS; skb_walk_frags(skb, iter) { if (hlen + skb_headlen(iter) > mtu) return false; } return true; } EXPORT_SYMBOL_GPL(skb_gso_validate_mtu); static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb) { if (skb_cow(skb, skb_headroom(skb)) < 0) { kfree_skb(skb); return NULL; } memmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN, 2 * ETH_ALEN); skb->mac_header += VLAN_HLEN; return skb; } struct sk_buff *skb_vlan_untag(struct sk_buff *skb) { struct vlan_hdr *vhdr; u16 vlan_tci; if (unlikely(skb_vlan_tag_present(skb))) { /* vlan_tci is already set-up so leave this for another time */ return skb; } skb = skb_share_check(skb, GFP_ATOMIC); if (unlikely(!skb)) goto err_free; if (unlikely(!pskb_may_pull(skb, VLAN_HLEN))) goto err_free; vhdr = (struct vlan_hdr *)skb->data; vlan_tci = ntohs(vhdr->h_vlan_TCI); __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci); skb_pull_rcsum(skb, VLAN_HLEN); vlan_set_encap_proto(skb, vhdr); skb = skb_reorder_vlan_header(skb); if (unlikely(!skb)) goto err_free; skb_reset_network_header(skb); skb_reset_transport_header(skb); skb_reset_mac_len(skb); return skb; err_free: kfree_skb(skb); return NULL; } EXPORT_SYMBOL(skb_vlan_untag); int skb_ensure_writable(struct sk_buff *skb, int write_len) { if (!pskb_may_pull(skb, write_len)) return -ENOMEM; if (!skb_cloned(skb) || skb_clone_writable(skb, write_len)) return 0; return pskb_expand_head(skb, 0, 0, GFP_ATOMIC); } EXPORT_SYMBOL(skb_ensure_writable); /* remove VLAN header from packet and update csum accordingly. * expects a non skb_vlan_tag_present skb with a vlan tag payload */ int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci) { struct vlan_hdr *vhdr; int offset = skb->data - skb_mac_header(skb); int err; if (WARN_ONCE(offset, "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n", offset)) { return -EINVAL; } err = skb_ensure_writable(skb, VLAN_ETH_HLEN); if (unlikely(err)) return err; skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN); vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN); *vlan_tci = ntohs(vhdr->h_vlan_TCI); memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN); __skb_pull(skb, VLAN_HLEN); vlan_set_encap_proto(skb, vhdr); skb->mac_header += VLAN_HLEN; if (skb_network_offset(skb) < ETH_HLEN) skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_len(skb); return err; } EXPORT_SYMBOL(__skb_vlan_pop); /* Pop a vlan tag either from hwaccel or from payload. * Expects skb->data at mac header. */ int skb_vlan_pop(struct sk_buff *skb) { u16 vlan_tci; __be16 vlan_proto; int err; if (likely(skb_vlan_tag_present(skb))) { skb->vlan_tci = 0; } else { if (unlikely(!eth_type_vlan(skb->protocol))) return 0; err = __skb_vlan_pop(skb, &vlan_tci); if (err) return err; } /* move next vlan tag to hw accel tag */ if (likely(!eth_type_vlan(skb->protocol))) return 0; vlan_proto = skb->protocol; err = __skb_vlan_pop(skb, &vlan_tci); if (unlikely(err)) return err; __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci); return 0; } EXPORT_SYMBOL(skb_vlan_pop); /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present). * Expects skb->data at mac header. */ int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) { if (skb_vlan_tag_present(skb)) { int offset = skb->data - skb_mac_header(skb); int err; if (WARN_ONCE(offset, "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n", offset)) { return -EINVAL; } err = __vlan_insert_tag(skb, skb->vlan_proto, skb_vlan_tag_get(skb)); if (err) return err; skb->protocol = skb->vlan_proto; skb->mac_len += VLAN_HLEN; skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN); } __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci); return 0; } EXPORT_SYMBOL(skb_vlan_push); /** * alloc_skb_with_frags - allocate skb with page frags * * @header_len: size of linear part * @data_len: needed length in frags * @max_page_order: max page order desired. * @errcode: pointer to error code if any * @gfp_mask: allocation mask * * This can be used to allocate a paged skb, given a maximal order for frags. */ struct sk_buff *alloc_skb_with_frags(unsigned long header_len, unsigned long data_len, int max_page_order, int *errcode, gfp_t gfp_mask) { int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; unsigned long chunk; struct sk_buff *skb; struct page *page; gfp_t gfp_head; int i; *errcode = -EMSGSIZE; /* Note this test could be relaxed, if we succeed to allocate * high order pages... */ if (npages > MAX_SKB_FRAGS) return NULL; gfp_head = gfp_mask; if (gfp_head & __GFP_DIRECT_RECLAIM) gfp_head |= __GFP_REPEAT; *errcode = -ENOBUFS; skb = alloc_skb(header_len, gfp_head); if (!skb) return NULL; skb->truesize += npages << PAGE_SHIFT; for (i = 0; npages > 0; i++) { int order = max_page_order; while (order) { if (npages >= 1 << order) { page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, order); if (page) goto fill_page; /* Do not retry other high order allocations */ order = 1; max_page_order = 0; } order--; } page = alloc_page(gfp_mask); if (!page) goto failure; fill_page: chunk = min_t(unsigned long, data_len, PAGE_SIZE << order); skb_fill_page_desc(skb, i, page, 0, chunk); data_len -= chunk; npages -= 1 << order; } return skb; failure: kfree_skb(skb); return NULL; } EXPORT_SYMBOL(alloc_skb_with_frags); /* carve out the first off bytes from skb when off < headlen */ static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off, const int headlen, gfp_t gfp_mask) { int i; int size = skb_end_offset(skb); int new_hlen = headlen - off; u8 *data; size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) return -ENOMEM; size = SKB_WITH_OVERHEAD(ksize(data)); /* Copy real data, and all frags */ skb_copy_from_linear_data_offset(skb, off, data, new_hlen); skb->len -= off; memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); if (skb_cloned(skb)) { /* drop the old head gracefully */ if (skb_orphan_frags(skb, gfp_mask)) { kfree(data); return -ENOMEM; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) skb_frag_ref(skb, i); if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); skb_release_data(skb); } else { /* we can reuse existing recount- all we did was * relocate values */ skb_free_head(skb); } skb->head = data; skb->data = data; skb->head_frag = 0; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; #else skb->end = skb->head + size; #endif skb_set_tail_pointer(skb, skb_headlen(skb)); skb_headers_offset_update(skb, 0); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; atomic_set(&skb_shinfo(skb)->dataref, 1); return 0; } static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp); /* carve out the first eat bytes from skb's frag_list. May recurse into * pskb_carve() */ static int pskb_carve_frag_list(struct sk_buff *skb, struct skb_shared_info *shinfo, int eat, gfp_t gfp_mask) { struct sk_buff *list = shinfo->frag_list; struct sk_buff *clone = NULL; struct sk_buff *insp = NULL; do { if (!list) { pr_err("Not enough bytes to eat. Want %d\n", eat); return -EFAULT; } if (list->len <= eat) { /* Eaten as whole. */ eat -= list->len; list = list->next; insp = list; } else { /* Eaten partially. */ if (skb_shared(list)) { clone = skb_clone(list, gfp_mask); if (!clone) return -ENOMEM; insp = list->next; list = clone; } else { /* This may be pulled without problems. */ insp = list; } if (pskb_carve(list, eat, gfp_mask) < 0) { kfree_skb(clone); return -ENOMEM; } break; } } while (eat); /* Free pulled out fragments. */ while ((list = shinfo->frag_list) != insp) { shinfo->frag_list = list->next; kfree_skb(list); } /* And insert new clone at head. */ if (clone) { clone->next = list; shinfo->frag_list = clone; } return 0; } /* carve off first len bytes from skb. Split line (off) is in the * non-linear part of skb */ static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off, int pos, gfp_t gfp_mask) { int i, k = 0; int size = skb_end_offset(skb); u8 *data; const int nfrags = skb_shinfo(skb)->nr_frags; struct skb_shared_info *shinfo; size = SKB_DATA_ALIGN(size); if (skb_pfmemalloc(skb)) gfp_mask |= __GFP_MEMALLOC; data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), gfp_mask, NUMA_NO_NODE, NULL); if (!data) return -ENOMEM; size = SKB_WITH_OVERHEAD(ksize(data)); memcpy((struct skb_shared_info *)(data + size), skb_shinfo(skb), offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags])); if (skb_orphan_frags(skb, gfp_mask)) { kfree(data); return -ENOMEM; } shinfo = (struct skb_shared_info *)(data + size); for (i = 0; i < nfrags; i++) { int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (pos + fsize > off) { shinfo->frags[k] = skb_shinfo(skb)->frags[i]; if (pos < off) { /* Split frag. * We have two variants in this case: * 1. Move all the frag to the second * part, if it is possible. F.e. * this approach is mandatory for TUX, * where splitting is expensive. * 2. Split is accurately. We make this. */ shinfo->frags[0].page_offset += off - pos; skb_frag_size_sub(&shinfo->frags[0], off - pos); } skb_frag_ref(skb, i); k++; } pos += fsize; } shinfo->nr_frags = k; if (skb_has_frag_list(skb)) skb_clone_fraglist(skb); if (k == 0) { /* split line is in frag list */ pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask); } skb_release_data(skb); skb->head = data; skb->head_frag = 0; skb->data = data; #ifdef NET_SKBUFF_DATA_USES_OFFSET skb->end = size; #else skb->end = skb->head + size; #endif skb_reset_tail_pointer(skb); skb_headers_offset_update(skb, 0); skb->cloned = 0; skb->hdr_len = 0; skb->nohdr = 0; skb->len -= off; skb->data_len = skb->len; atomic_set(&skb_shinfo(skb)->dataref, 1); return 0; } /* remove len bytes from the beginning of the skb */ static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp) { int headlen = skb_headlen(skb); if (len < headlen) return pskb_carve_inside_header(skb, len, headlen, gfp); else return pskb_carve_inside_nonlinear(skb, len, headlen, gfp); } /* Extract to_copy bytes starting at off from skb, and return this in * a new skb */ struct sk_buff *pskb_extract(struct sk_buff *skb, int off, int to_copy, gfp_t gfp) { struct sk_buff *clone = skb_clone(skb, gfp); if (!clone) return NULL; if (pskb_carve(clone, off, gfp) < 0 || pskb_trim(clone, to_copy)) { kfree_skb(clone); return NULL; } return clone; } EXPORT_SYMBOL(pskb_extract); /** * skb_condense - try to get rid of fragments/frag_list if possible * @skb: buffer * * Can be used to save memory before skb is added to a busy queue. * If packet has bytes in frags and enough tail room in skb->head, * pull all of them, so that we can free the frags right now and adjust * truesize. * Notes: * We do not reallocate skb->head thus can not fail. * Caller must re-evaluate skb->truesize if needed. */ void skb_condense(struct sk_buff *skb) { if (skb->data_len) { if (skb->data_len > skb->end - skb->tail || skb_cloned(skb)) return; /* Nice, we can free page frag(s) right now */ __pskb_pull_tail(skb, skb->data_len); } /* At this point, skb->truesize might be over estimated, * because skb had a fragment, and fragments do not tell * their truesize. * When we pulled its content into skb->head, fragment * was freed, but __pskb_pull_tail() could not possibly * adjust skb->truesize, not knowing the frag truesize. */ skb->truesize = SKB_TRUESIZE(skb_end_offset(skb)); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3255_0
crossvul-cpp_data_bad_5338_0
/* * HID support for Linux * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2012 Jiri Kosina */ /* * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <asm/unaligned.h> #include <asm/byteorder.h> #include <linux/input.h> #include <linux/wait.h> #include <linux/vmalloc.h> #include <linux/sched.h> #include <linux/semaphore.h> #include <linux/hid.h> #include <linux/hiddev.h> #include <linux/hid-debug.h> #include <linux/hidraw.h> #include "hid-ids.h" /* * Version Information */ #define DRIVER_DESC "HID core driver" #define DRIVER_LICENSE "GPL" int hid_debug = 0; module_param_named(debug, hid_debug, int, 0600); MODULE_PARM_DESC(debug, "toggle HID debugging messages"); EXPORT_SYMBOL_GPL(hid_debug); static int hid_ignore_special_drivers = 0; module_param_named(ignore_special_drivers, hid_ignore_special_drivers, int, 0600); MODULE_PARM_DESC(ignore_special_drivers, "Ignore any special drivers and handle all devices by generic driver"); /* * Register a new report for a device. */ struct hid_report *hid_register_report(struct hid_device *device, unsigned type, unsigned id) { struct hid_report_enum *report_enum = device->report_enum + type; struct hid_report *report; if (id >= HID_MAX_IDS) return NULL; if (report_enum->report_id_hash[id]) return report_enum->report_id_hash[id]; report = kzalloc(sizeof(struct hid_report), GFP_KERNEL); if (!report) return NULL; if (id != 0) report_enum->numbered = 1; report->id = id; report->type = type; report->size = 0; report->device = device; report_enum->report_id_hash[id] = report; list_add_tail(&report->list, &report_enum->report_list); return report; } EXPORT_SYMBOL_GPL(hid_register_report); /* * Register a new field for this report. */ static struct hid_field *hid_register_field(struct hid_report *report, unsigned usages, unsigned values) { struct hid_field *field; if (report->maxfield == HID_MAX_FIELDS) { hid_err(report->device, "too many fields in report\n"); return NULL; } field = kzalloc((sizeof(struct hid_field) + usages * sizeof(struct hid_usage) + values * sizeof(unsigned)), GFP_KERNEL); if (!field) return NULL; field->index = report->maxfield++; report->field[field->index] = field; field->usage = (struct hid_usage *)(field + 1); field->value = (s32 *)(field->usage + usages); field->report = report; return field; } /* * Open a collection. The type/usage is pushed on the stack. */ static int open_collection(struct hid_parser *parser, unsigned type) { struct hid_collection *collection; unsigned usage; usage = parser->local.usage[0]; if (parser->collection_stack_ptr == HID_COLLECTION_STACK_SIZE) { hid_err(parser->device, "collection stack overflow\n"); return -EINVAL; } if (parser->device->maxcollection == parser->device->collection_size) { collection = kmalloc(sizeof(struct hid_collection) * parser->device->collection_size * 2, GFP_KERNEL); if (collection == NULL) { hid_err(parser->device, "failed to reallocate collection array\n"); return -ENOMEM; } memcpy(collection, parser->device->collection, sizeof(struct hid_collection) * parser->device->collection_size); memset(collection + parser->device->collection_size, 0, sizeof(struct hid_collection) * parser->device->collection_size); kfree(parser->device->collection); parser->device->collection = collection; parser->device->collection_size *= 2; } parser->collection_stack[parser->collection_stack_ptr++] = parser->device->maxcollection; collection = parser->device->collection + parser->device->maxcollection++; collection->type = type; collection->usage = usage; collection->level = parser->collection_stack_ptr - 1; if (type == HID_COLLECTION_APPLICATION) parser->device->maxapplication++; return 0; } /* * Close a collection. */ static int close_collection(struct hid_parser *parser) { if (!parser->collection_stack_ptr) { hid_err(parser->device, "collection stack underflow\n"); return -EINVAL; } parser->collection_stack_ptr--; return 0; } /* * Climb up the stack, search for the specified collection type * and return the usage. */ static unsigned hid_lookup_collection(struct hid_parser *parser, unsigned type) { struct hid_collection *collection = parser->device->collection; int n; for (n = parser->collection_stack_ptr - 1; n >= 0; n--) { unsigned index = parser->collection_stack[n]; if (collection[index].type == type) return collection[index].usage; } return 0; /* we know nothing about this usage type */ } /* * Add a usage to the temporary parser table. */ static int hid_add_usage(struct hid_parser *parser, unsigned usage) { if (parser->local.usage_index >= HID_MAX_USAGES) { hid_err(parser->device, "usage index exceeded\n"); return -1; } parser->local.usage[parser->local.usage_index] = usage; parser->local.collection_index[parser->local.usage_index] = parser->collection_stack_ptr ? parser->collection_stack[parser->collection_stack_ptr - 1] : 0; parser->local.usage_index++; return 0; } /* * Register a new field for this report. */ static int hid_add_field(struct hid_parser *parser, unsigned report_type, unsigned flags) { struct hid_report *report; struct hid_field *field; unsigned usages; unsigned offset; unsigned i; report = hid_register_report(parser->device, report_type, parser->global.report_id); if (!report) { hid_err(parser->device, "hid_register_report failed\n"); return -1; } /* Handle both signed and unsigned cases properly */ if ((parser->global.logical_minimum < 0 && parser->global.logical_maximum < parser->global.logical_minimum) || (parser->global.logical_minimum >= 0 && (__u32)parser->global.logical_maximum < (__u32)parser->global.logical_minimum)) { dbg_hid("logical range invalid 0x%x 0x%x\n", parser->global.logical_minimum, parser->global.logical_maximum); return -1; } offset = report->size; report->size += parser->global.report_size * parser->global.report_count; if (!parser->local.usage_index) /* Ignore padding fields */ return 0; usages = max_t(unsigned, parser->local.usage_index, parser->global.report_count); field = hid_register_field(report, usages, parser->global.report_count); if (!field) return 0; field->physical = hid_lookup_collection(parser, HID_COLLECTION_PHYSICAL); field->logical = hid_lookup_collection(parser, HID_COLLECTION_LOGICAL); field->application = hid_lookup_collection(parser, HID_COLLECTION_APPLICATION); for (i = 0; i < usages; i++) { unsigned j = i; /* Duplicate the last usage we parsed if we have excess values */ if (i >= parser->local.usage_index) j = parser->local.usage_index - 1; field->usage[i].hid = parser->local.usage[j]; field->usage[i].collection_index = parser->local.collection_index[j]; field->usage[i].usage_index = i; } field->maxusage = usages; field->flags = flags; field->report_offset = offset; field->report_type = report_type; field->report_size = parser->global.report_size; field->report_count = parser->global.report_count; field->logical_minimum = parser->global.logical_minimum; field->logical_maximum = parser->global.logical_maximum; field->physical_minimum = parser->global.physical_minimum; field->physical_maximum = parser->global.physical_maximum; field->unit_exponent = parser->global.unit_exponent; field->unit = parser->global.unit; return 0; } /* * Read data value from item. */ static u32 item_udata(struct hid_item *item) { switch (item->size) { case 1: return item->data.u8; case 2: return item->data.u16; case 4: return item->data.u32; } return 0; } static s32 item_sdata(struct hid_item *item) { switch (item->size) { case 1: return item->data.s8; case 2: return item->data.s16; case 4: return item->data.s32; } return 0; } /* * Process a global item. */ static int hid_parser_global(struct hid_parser *parser, struct hid_item *item) { __s32 raw_value; switch (item->tag) { case HID_GLOBAL_ITEM_TAG_PUSH: if (parser->global_stack_ptr == HID_GLOBAL_STACK_SIZE) { hid_err(parser->device, "global environment stack overflow\n"); return -1; } memcpy(parser->global_stack + parser->global_stack_ptr++, &parser->global, sizeof(struct hid_global)); return 0; case HID_GLOBAL_ITEM_TAG_POP: if (!parser->global_stack_ptr) { hid_err(parser->device, "global environment stack underflow\n"); return -1; } memcpy(&parser->global, parser->global_stack + --parser->global_stack_ptr, sizeof(struct hid_global)); return 0; case HID_GLOBAL_ITEM_TAG_USAGE_PAGE: parser->global.usage_page = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_LOGICAL_MINIMUM: parser->global.logical_minimum = item_sdata(item); return 0; case HID_GLOBAL_ITEM_TAG_LOGICAL_MAXIMUM: if (parser->global.logical_minimum < 0) parser->global.logical_maximum = item_sdata(item); else parser->global.logical_maximum = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_PHYSICAL_MINIMUM: parser->global.physical_minimum = item_sdata(item); return 0; case HID_GLOBAL_ITEM_TAG_PHYSICAL_MAXIMUM: if (parser->global.physical_minimum < 0) parser->global.physical_maximum = item_sdata(item); else parser->global.physical_maximum = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_UNIT_EXPONENT: /* Many devices provide unit exponent as a two's complement * nibble due to the common misunderstanding of HID * specification 1.11, 6.2.2.7 Global Items. Attempt to handle * both this and the standard encoding. */ raw_value = item_sdata(item); if (!(raw_value & 0xfffffff0)) parser->global.unit_exponent = hid_snto32(raw_value, 4); else parser->global.unit_exponent = raw_value; return 0; case HID_GLOBAL_ITEM_TAG_UNIT: parser->global.unit = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_REPORT_SIZE: parser->global.report_size = item_udata(item); if (parser->global.report_size > 128) { hid_err(parser->device, "invalid report_size %d\n", parser->global.report_size); return -1; } return 0; case HID_GLOBAL_ITEM_TAG_REPORT_COUNT: parser->global.report_count = item_udata(item); if (parser->global.report_count > HID_MAX_USAGES) { hid_err(parser->device, "invalid report_count %d\n", parser->global.report_count); return -1; } return 0; case HID_GLOBAL_ITEM_TAG_REPORT_ID: parser->global.report_id = item_udata(item); if (parser->global.report_id == 0 || parser->global.report_id >= HID_MAX_IDS) { hid_err(parser->device, "report_id %u is invalid\n", parser->global.report_id); return -1; } return 0; default: hid_err(parser->device, "unknown global tag 0x%x\n", item->tag); return -1; } } /* * Process a local item. */ static int hid_parser_local(struct hid_parser *parser, struct hid_item *item) { __u32 data; unsigned n; __u32 count; data = item_udata(item); switch (item->tag) { case HID_LOCAL_ITEM_TAG_DELIMITER: if (data) { /* * We treat items before the first delimiter * as global to all usage sets (branch 0). * In the moment we process only these global * items and the first delimiter set. */ if (parser->local.delimiter_depth != 0) { hid_err(parser->device, "nested delimiters\n"); return -1; } parser->local.delimiter_depth++; parser->local.delimiter_branch++; } else { if (parser->local.delimiter_depth < 1) { hid_err(parser->device, "bogus close delimiter\n"); return -1; } parser->local.delimiter_depth--; } return 0; case HID_LOCAL_ITEM_TAG_USAGE: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; return hid_add_usage(parser, data); case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; parser->local.usage_minimum = data; return 0; case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; count = data - parser->local.usage_minimum; if (count + parser->local.usage_index >= HID_MAX_USAGES) { /* * We do not warn if the name is not set, we are * actually pre-scanning the device. */ if (dev_name(&parser->device->dev)) hid_warn(parser->device, "ignoring exceeding usage max\n"); data = HID_MAX_USAGES - parser->local.usage_index + parser->local.usage_minimum - 1; if (data <= 0) { hid_err(parser->device, "no more usage index available\n"); return -1; } } for (n = parser->local.usage_minimum; n <= data; n++) if (hid_add_usage(parser, n)) { dbg_hid("hid_add_usage failed\n"); return -1; } return 0; default: dbg_hid("unknown local item tag 0x%x\n", item->tag); return 0; } return 0; } /* * Process a main item. */ static int hid_parser_main(struct hid_parser *parser, struct hid_item *item) { __u32 data; int ret; data = item_udata(item); switch (item->tag) { case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION: ret = open_collection(parser, data & 0xff); break; case HID_MAIN_ITEM_TAG_END_COLLECTION: ret = close_collection(parser); break; case HID_MAIN_ITEM_TAG_INPUT: ret = hid_add_field(parser, HID_INPUT_REPORT, data); break; case HID_MAIN_ITEM_TAG_OUTPUT: ret = hid_add_field(parser, HID_OUTPUT_REPORT, data); break; case HID_MAIN_ITEM_TAG_FEATURE: ret = hid_add_field(parser, HID_FEATURE_REPORT, data); break; default: hid_err(parser->device, "unknown main item tag 0x%x\n", item->tag); ret = 0; } memset(&parser->local, 0, sizeof(parser->local)); /* Reset the local parser environment */ return ret; } /* * Process a reserved item. */ static int hid_parser_reserved(struct hid_parser *parser, struct hid_item *item) { dbg_hid("reserved item type, tag 0x%x\n", item->tag); return 0; } /* * Free a report and all registered fields. The field->usage and * field->value table's are allocated behind the field, so we need * only to free(field) itself. */ static void hid_free_report(struct hid_report *report) { unsigned n; for (n = 0; n < report->maxfield; n++) kfree(report->field[n]); kfree(report); } /* * Close report. This function returns the device * state to the point prior to hid_open_report(). */ static void hid_close_report(struct hid_device *device) { unsigned i, j; for (i = 0; i < HID_REPORT_TYPES; i++) { struct hid_report_enum *report_enum = device->report_enum + i; for (j = 0; j < HID_MAX_IDS; j++) { struct hid_report *report = report_enum->report_id_hash[j]; if (report) hid_free_report(report); } memset(report_enum, 0, sizeof(*report_enum)); INIT_LIST_HEAD(&report_enum->report_list); } kfree(device->rdesc); device->rdesc = NULL; device->rsize = 0; kfree(device->collection); device->collection = NULL; device->collection_size = 0; device->maxcollection = 0; device->maxapplication = 0; device->status &= ~HID_STAT_PARSED; } /* * Free a device structure, all reports, and all fields. */ static void hid_device_release(struct device *dev) { struct hid_device *hid = to_hid_device(dev); hid_close_report(hid); kfree(hid->dev_rdesc); kfree(hid); } /* * Fetch a report description item from the data stream. We support long * items, though they are not used yet. */ static u8 *fetch_item(__u8 *start, __u8 *end, struct hid_item *item) { u8 b; if ((end - start) <= 0) return NULL; b = *start++; item->type = (b >> 2) & 3; item->tag = (b >> 4) & 15; if (item->tag == HID_ITEM_TAG_LONG) { item->format = HID_ITEM_FORMAT_LONG; if ((end - start) < 2) return NULL; item->size = *start++; item->tag = *start++; if ((end - start) < item->size) return NULL; item->data.longdata = start; start += item->size; return start; } item->format = HID_ITEM_FORMAT_SHORT; item->size = b & 3; switch (item->size) { case 0: return start; case 1: if ((end - start) < 1) return NULL; item->data.u8 = *start++; return start; case 2: if ((end - start) < 2) return NULL; item->data.u16 = get_unaligned_le16(start); start = (__u8 *)((__le16 *)start + 1); return start; case 3: item->size++; if ((end - start) < 4) return NULL; item->data.u32 = get_unaligned_le32(start); start = (__u8 *)((__le32 *)start + 1); return start; } return NULL; } static void hid_scan_input_usage(struct hid_parser *parser, u32 usage) { struct hid_device *hid = parser->device; if (usage == HID_DG_CONTACTID) hid->group = HID_GROUP_MULTITOUCH; } static void hid_scan_feature_usage(struct hid_parser *parser, u32 usage) { if (usage == 0xff0000c5 && parser->global.report_count == 256 && parser->global.report_size == 8) parser->scan_flags |= HID_SCAN_FLAG_MT_WIN_8; } static void hid_scan_collection(struct hid_parser *parser, unsigned type) { struct hid_device *hid = parser->device; int i; if (((parser->global.usage_page << 16) == HID_UP_SENSOR) && type == HID_COLLECTION_PHYSICAL) hid->group = HID_GROUP_SENSOR_HUB; if (hid->vendor == USB_VENDOR_ID_MICROSOFT && (hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_2 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_JP || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_3 || hid->product == USB_DEVICE_ID_MS_POWER_COVER) && hid->group == HID_GROUP_MULTITOUCH) hid->group = HID_GROUP_GENERIC; if ((parser->global.usage_page << 16) == HID_UP_GENDESK) for (i = 0; i < parser->local.usage_index; i++) if (parser->local.usage[i] == HID_GD_POINTER) parser->scan_flags |= HID_SCAN_FLAG_GD_POINTER; if ((parser->global.usage_page << 16) >= HID_UP_MSVENDOR) parser->scan_flags |= HID_SCAN_FLAG_VENDOR_SPECIFIC; } static int hid_scan_main(struct hid_parser *parser, struct hid_item *item) { __u32 data; int i; data = item_udata(item); switch (item->tag) { case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION: hid_scan_collection(parser, data & 0xff); break; case HID_MAIN_ITEM_TAG_END_COLLECTION: break; case HID_MAIN_ITEM_TAG_INPUT: /* ignore constant inputs, they will be ignored by hid-input */ if (data & HID_MAIN_ITEM_CONSTANT) break; for (i = 0; i < parser->local.usage_index; i++) hid_scan_input_usage(parser, parser->local.usage[i]); break; case HID_MAIN_ITEM_TAG_OUTPUT: break; case HID_MAIN_ITEM_TAG_FEATURE: for (i = 0; i < parser->local.usage_index; i++) hid_scan_feature_usage(parser, parser->local.usage[i]); break; } /* Reset the local parser environment */ memset(&parser->local, 0, sizeof(parser->local)); return 0; } /* * Scan a report descriptor before the device is added to the bus. * Sets device groups and other properties that determine what driver * to load. */ static int hid_scan_report(struct hid_device *hid) { struct hid_parser *parser; struct hid_item item; __u8 *start = hid->dev_rdesc; __u8 *end = start + hid->dev_rsize; static int (*dispatch_type[])(struct hid_parser *parser, struct hid_item *item) = { hid_scan_main, hid_parser_global, hid_parser_local, hid_parser_reserved }; parser = vzalloc(sizeof(struct hid_parser)); if (!parser) return -ENOMEM; parser->device = hid; hid->group = HID_GROUP_GENERIC; /* * The parsing is simpler than the one in hid_open_report() as we should * be robust against hid errors. Those errors will be raised by * hid_open_report() anyway. */ while ((start = fetch_item(start, end, &item)) != NULL) dispatch_type[item.type](parser, &item); /* * Handle special flags set during scanning. */ if ((parser->scan_flags & HID_SCAN_FLAG_MT_WIN_8) && (hid->group == HID_GROUP_MULTITOUCH)) hid->group = HID_GROUP_MULTITOUCH_WIN_8; /* * Vendor specific handlings */ switch (hid->vendor) { case USB_VENDOR_ID_WACOM: hid->group = HID_GROUP_WACOM; break; case USB_VENDOR_ID_SYNAPTICS: if (hid->group == HID_GROUP_GENERIC) if ((parser->scan_flags & HID_SCAN_FLAG_VENDOR_SPECIFIC) && (parser->scan_flags & HID_SCAN_FLAG_GD_POINTER)) /* * hid-rmi should take care of them, * not hid-generic */ hid->group = HID_GROUP_RMI; break; } vfree(parser); return 0; } /** * hid_parse_report - parse device report * * @device: hid device * @start: report start * @size: report size * * Allocate the device report as read by the bus driver. This function should * only be called from parse() in ll drivers. */ int hid_parse_report(struct hid_device *hid, __u8 *start, unsigned size) { hid->dev_rdesc = kmemdup(start, size, GFP_KERNEL); if (!hid->dev_rdesc) return -ENOMEM; hid->dev_rsize = size; return 0; } EXPORT_SYMBOL_GPL(hid_parse_report); static const char * const hid_report_names[] = { "HID_INPUT_REPORT", "HID_OUTPUT_REPORT", "HID_FEATURE_REPORT", }; /** * hid_validate_values - validate existing device report's value indexes * * @device: hid device * @type: which report type to examine * @id: which report ID to examine (0 for first) * @field_index: which report field to examine * @report_counts: expected number of values * * Validate the number of values in a given field of a given report, after * parsing. */ struct hid_report *hid_validate_values(struct hid_device *hid, unsigned int type, unsigned int id, unsigned int field_index, unsigned int report_counts) { struct hid_report *report; if (type > HID_FEATURE_REPORT) { hid_err(hid, "invalid HID report type %u\n", type); return NULL; } if (id >= HID_MAX_IDS) { hid_err(hid, "invalid HID report id %u\n", id); return NULL; } /* * Explicitly not using hid_get_report() here since it depends on * ->numbered being checked, which may not always be the case when * drivers go to access report values. */ if (id == 0) { /* * Validating on id 0 means we should examine the first * report in the list. */ report = list_entry( hid->report_enum[type].report_list.next, struct hid_report, list); } else { report = hid->report_enum[type].report_id_hash[id]; } if (!report) { hid_err(hid, "missing %s %u\n", hid_report_names[type], id); return NULL; } if (report->maxfield <= field_index) { hid_err(hid, "not enough fields in %s %u\n", hid_report_names[type], id); return NULL; } if (report->field[field_index]->report_count < report_counts) { hid_err(hid, "not enough values in %s %u field %u\n", hid_report_names[type], id, field_index); return NULL; } return report; } EXPORT_SYMBOL_GPL(hid_validate_values); /** * hid_open_report - open a driver-specific device report * * @device: hid device * * Parse a report description into a hid_device structure. Reports are * enumerated, fields are attached to these reports. * 0 returned on success, otherwise nonzero error value. * * This function (or the equivalent hid_parse() macro) should only be * called from probe() in drivers, before starting the device. */ int hid_open_report(struct hid_device *device) { struct hid_parser *parser; struct hid_item item; unsigned int size; __u8 *start; __u8 *buf; __u8 *end; int ret; static int (*dispatch_type[])(struct hid_parser *parser, struct hid_item *item) = { hid_parser_main, hid_parser_global, hid_parser_local, hid_parser_reserved }; if (WARN_ON(device->status & HID_STAT_PARSED)) return -EBUSY; start = device->dev_rdesc; if (WARN_ON(!start)) return -ENODEV; size = device->dev_rsize; buf = kmemdup(start, size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; if (device->driver->report_fixup) start = device->driver->report_fixup(device, buf, &size); else start = buf; start = kmemdup(start, size, GFP_KERNEL); kfree(buf); if (start == NULL) return -ENOMEM; device->rdesc = start; device->rsize = size; parser = vzalloc(sizeof(struct hid_parser)); if (!parser) { ret = -ENOMEM; goto err; } parser->device = device; end = start + size; device->collection = kcalloc(HID_DEFAULT_NUM_COLLECTIONS, sizeof(struct hid_collection), GFP_KERNEL); if (!device->collection) { ret = -ENOMEM; goto err; } device->collection_size = HID_DEFAULT_NUM_COLLECTIONS; ret = -EINVAL; while ((start = fetch_item(start, end, &item)) != NULL) { if (item.format != HID_ITEM_FORMAT_SHORT) { hid_err(device, "unexpected long global item\n"); goto err; } if (dispatch_type[item.type](parser, &item)) { hid_err(device, "item %u %u %u %u parsing failed\n", item.format, (unsigned)item.size, (unsigned)item.type, (unsigned)item.tag); goto err; } if (start == end) { if (parser->collection_stack_ptr) { hid_err(device, "unbalanced collection at end of report description\n"); goto err; } if (parser->local.delimiter_depth) { hid_err(device, "unbalanced delimiter at end of report description\n"); goto err; } vfree(parser); device->status |= HID_STAT_PARSED; return 0; } } hid_err(device, "item fetching failed at offset %d\n", (int)(end - start)); err: vfree(parser); hid_close_report(device); return ret; } EXPORT_SYMBOL_GPL(hid_open_report); /* * Convert a signed n-bit integer to signed 32-bit integer. Common * cases are done through the compiler, the screwed things has to be * done by hand. */ static s32 snto32(__u32 value, unsigned n) { switch (n) { case 8: return ((__s8)value); case 16: return ((__s16)value); case 32: return ((__s32)value); } return value & (1 << (n - 1)) ? value | (-1 << n) : value; } s32 hid_snto32(__u32 value, unsigned n) { return snto32(value, n); } EXPORT_SYMBOL_GPL(hid_snto32); /* * Convert a signed 32-bit integer to a signed n-bit integer. */ static u32 s32ton(__s32 value, unsigned n) { s32 a = value >> (n - 1); if (a && a != -1) return value < 0 ? 1 << (n - 1) : (1 << (n - 1)) - 1; return value & ((1 << n) - 1); } /* * Extract/implement a data field from/to a little endian report (bit array). * * Code sort-of follows HID spec: * http://www.usb.org/developers/hidpage/HID1_11.pdf * * While the USB HID spec allows unlimited length bit fields in "report * descriptors", most devices never use more than 16 bits. * One model of UPS is claimed to report "LINEV" as a 32-bit field. * Search linux-kernel and linux-usb-devel archives for "hid-core extract". */ static u32 __extract(u8 *report, unsigned offset, int n) { unsigned int idx = offset / 8; unsigned int bit_nr = 0; unsigned int bit_shift = offset % 8; int bits_to_copy = 8 - bit_shift; u32 value = 0; u32 mask = n < 32 ? (1U << n) - 1 : ~0U; while (n > 0) { value |= ((u32)report[idx] >> bit_shift) << bit_nr; n -= bits_to_copy; bit_nr += bits_to_copy; bits_to_copy = 8; bit_shift = 0; idx++; } return value & mask; } u32 hid_field_extract(const struct hid_device *hid, u8 *report, unsigned offset, unsigned n) { if (n > 32) { hid_warn(hid, "hid_field_extract() called with n (%d) > 32! (%s)\n", n, current->comm); n = 32; } return __extract(report, offset, n); } EXPORT_SYMBOL_GPL(hid_field_extract); /* * "implement" : set bits in a little endian bit stream. * Same concepts as "extract" (see comments above). * The data mangled in the bit stream remains in little endian * order the whole time. It make more sense to talk about * endianness of register values by considering a register * a "cached" copy of the little endian bit stream. */ static void __implement(u8 *report, unsigned offset, int n, u32 value) { unsigned int idx = offset / 8; unsigned int size = offset + n; unsigned int bit_shift = offset % 8; int bits_to_set = 8 - bit_shift; u8 bit_mask = 0xff << bit_shift; while (n - bits_to_set >= 0) { report[idx] &= ~bit_mask; report[idx] |= value << bit_shift; value >>= bits_to_set; n -= bits_to_set; bits_to_set = 8; bit_mask = 0xff; bit_shift = 0; idx++; } /* last nibble */ if (n) { if (size % 8) bit_mask &= (1U << (size % 8)) - 1; report[idx] &= ~bit_mask; report[idx] |= (value << bit_shift) & bit_mask; } } static void implement(const struct hid_device *hid, u8 *report, unsigned offset, unsigned n, u32 value) { u64 m; if (n > 32) { hid_warn(hid, "%s() called with n (%d) > 32! (%s)\n", __func__, n, current->comm); n = 32; } m = (1ULL << n) - 1; if (value > m) hid_warn(hid, "%s() called with too large value %d! (%s)\n", __func__, value, current->comm); WARN_ON(value > m); value &= m; __implement(report, offset, n, value); } /* * Search an array for a value. */ static int search(__s32 *array, __s32 value, unsigned n) { while (n--) { if (*array++ == value) return 0; } return -1; } /** * hid_match_report - check if driver's raw_event should be called * * @hid: hid device * @report_type: type to match against * * compare hid->driver->report_table->report_type to report->type */ static int hid_match_report(struct hid_device *hid, struct hid_report *report) { const struct hid_report_id *id = hid->driver->report_table; if (!id) /* NULL means all */ return 1; for (; id->report_type != HID_TERMINATOR; id++) if (id->report_type == HID_ANY_ID || id->report_type == report->type) return 1; return 0; } /** * hid_match_usage - check if driver's event should be called * * @hid: hid device * @usage: usage to match against * * compare hid->driver->usage_table->usage_{type,code} to * usage->usage_{type,code} */ static int hid_match_usage(struct hid_device *hid, struct hid_usage *usage) { const struct hid_usage_id *id = hid->driver->usage_table; if (!id) /* NULL means all */ return 1; for (; id->usage_type != HID_ANY_ID - 1; id++) if ((id->usage_hid == HID_ANY_ID || id->usage_hid == usage->hid) && (id->usage_type == HID_ANY_ID || id->usage_type == usage->type) && (id->usage_code == HID_ANY_ID || id->usage_code == usage->code)) return 1; return 0; } static void hid_process_event(struct hid_device *hid, struct hid_field *field, struct hid_usage *usage, __s32 value, int interrupt) { struct hid_driver *hdrv = hid->driver; int ret; if (!list_empty(&hid->debug_list)) hid_dump_input(hid, usage, value); if (hdrv && hdrv->event && hid_match_usage(hid, usage)) { ret = hdrv->event(hid, field, usage, value); if (ret != 0) { if (ret < 0) hid_err(hid, "%s's event failed with %d\n", hdrv->name, ret); return; } } if (hid->claimed & HID_CLAIMED_INPUT) hidinput_hid_event(hid, field, usage, value); if (hid->claimed & HID_CLAIMED_HIDDEV && interrupt && hid->hiddev_hid_event) hid->hiddev_hid_event(hid, field, usage, value); } /* * Analyse a received field, and fetch the data from it. The field * content is stored for next report processing (we do differential * reporting to the layer). */ static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); } /* * Output the field into the report. */ static void hid_output_field(const struct hid_device *hid, struct hid_field *field, __u8 *data) { unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; unsigned n; for (n = 0; n < count; n++) { if (field->logical_minimum < 0) /* signed values */ implement(hid, data, offset + n * size, size, s32ton(field->value[n], size)); else /* unsigned values */ implement(hid, data, offset + n * size, size, field->value[n]); } } /* * Create a report. 'data' has to be allocated using * hid_alloc_report_buf() so that it has proper size. */ void hid_output_report(struct hid_report *report, __u8 *data) { unsigned n; if (report->id > 0) *data++ = report->id; memset(data, 0, ((report->size - 1) >> 3) + 1); for (n = 0; n < report->maxfield; n++) hid_output_field(report->device, report->field[n], data); } EXPORT_SYMBOL_GPL(hid_output_report); /* * Allocator for buffer that is going to be passed to hid_output_report() */ u8 *hid_alloc_report_buf(struct hid_report *report, gfp_t flags) { /* * 7 extra bytes are necessary to achieve proper functionality * of implement() working on 8 byte chunks */ int len = hid_report_len(report) + 7; return kmalloc(len, flags); } EXPORT_SYMBOL_GPL(hid_alloc_report_buf); /* * Set a field value. The report this field belongs to has to be * created and transferred to the device, to set this value in the * device. */ int hid_set_field(struct hid_field *field, unsigned offset, __s32 value) { unsigned size; if (!field) return -1; size = field->report_size; hid_dump_input(field->report->device, field->usage + offset, value); if (offset >= field->report_count) { hid_err(field->report->device, "offset (%d) exceeds report_count (%d)\n", offset, field->report_count); return -1; } if (field->logical_minimum < 0) { if (value != snto32(s32ton(value, size), size)) { hid_err(field->report->device, "value %d is out of range\n", value); return -1; } } field->value[offset] = value; return 0; } EXPORT_SYMBOL_GPL(hid_set_field); static struct hid_report *hid_get_report(struct hid_report_enum *report_enum, const u8 *data) { struct hid_report *report; unsigned int n = 0; /* Normally report number is 0 */ /* Device uses numbered reports, data[0] is report number */ if (report_enum->numbered) n = *data; report = report_enum->report_id_hash[n]; if (report == NULL) dbg_hid("undefined report_id %u received\n", n); return report; } /* * Implement a generic .request() callback, using .raw_request() * DO NOT USE in hid drivers directly, but through hid_hw_request instead. */ void __hid_request(struct hid_device *hid, struct hid_report *report, int reqtype) { char *buf; int ret; int len; buf = hid_alloc_report_buf(report, GFP_KERNEL); if (!buf) return; len = hid_report_len(report); if (reqtype == HID_REQ_SET_REPORT) hid_output_report(report, buf); ret = hid->ll_driver->raw_request(hid, report->id, buf, len, report->type, reqtype); if (ret < 0) { dbg_hid("unable to complete request: %d\n", ret); goto out; } if (reqtype == HID_REQ_GET_REPORT) hid_input_report(hid, report->type, buf, ret, 0); out: kfree(buf); } EXPORT_SYMBOL_GPL(__hid_request); int hid_report_raw_event(struct hid_device *hid, int type, u8 *data, int size, int interrupt) { struct hid_report_enum *report_enum = hid->report_enum + type; struct hid_report *report; struct hid_driver *hdrv; unsigned int a; int rsize, csize = size; u8 *cdata = data; int ret = 0; report = hid_get_report(report_enum, data); if (!report) goto out; if (report_enum->numbered) { cdata++; csize--; } rsize = ((report->size - 1) >> 3) + 1; if (rsize > HID_MAX_BUFFER_SIZE) rsize = HID_MAX_BUFFER_SIZE; if (csize < rsize) { dbg_hid("report %d is too short, (%d < %d)\n", report->id, csize, rsize); memset(cdata + csize, 0, rsize - csize); } if ((hid->claimed & HID_CLAIMED_HIDDEV) && hid->hiddev_report_event) hid->hiddev_report_event(hid, report); if (hid->claimed & HID_CLAIMED_HIDRAW) { ret = hidraw_report_event(hid, data, size); if (ret) goto out; } if (hid->claimed != HID_CLAIMED_HIDRAW && report->maxfield) { for (a = 0; a < report->maxfield; a++) hid_input_field(hid, report->field[a], cdata, interrupt); hdrv = hid->driver; if (hdrv && hdrv->report) hdrv->report(hid, report); } if (hid->claimed & HID_CLAIMED_INPUT) hidinput_report_event(hid, report); out: return ret; } EXPORT_SYMBOL_GPL(hid_report_raw_event); /** * hid_input_report - report data from lower layer (usb, bt...) * * @hid: hid device * @type: HID report type (HID_*_REPORT) * @data: report contents * @size: size of data parameter * @interrupt: distinguish between interrupt and control transfers * * This is data entry for lower layers. */ int hid_input_report(struct hid_device *hid, int type, u8 *data, int size, int interrupt) { struct hid_report_enum *report_enum; struct hid_driver *hdrv; struct hid_report *report; int ret = 0; if (!hid) return -ENODEV; if (down_trylock(&hid->driver_input_lock)) return -EBUSY; if (!hid->driver) { ret = -ENODEV; goto unlock; } report_enum = hid->report_enum + type; hdrv = hid->driver; if (!size) { dbg_hid("empty report\n"); ret = -1; goto unlock; } /* Avoid unnecessary overhead if debugfs is disabled */ if (!list_empty(&hid->debug_list)) hid_dump_report(hid, type, data, size); report = hid_get_report(report_enum, data); if (!report) { ret = -1; goto unlock; } if (hdrv && hdrv->raw_event && hid_match_report(hid, report)) { ret = hdrv->raw_event(hid, report, data, size); if (ret < 0) goto unlock; } ret = hid_report_raw_event(hid, type, data, size, interrupt); unlock: up(&hid->driver_input_lock); return ret; } EXPORT_SYMBOL_GPL(hid_input_report); static bool hid_match_one_id(struct hid_device *hdev, const struct hid_device_id *id) { return (id->bus == HID_BUS_ANY || id->bus == hdev->bus) && (id->group == HID_GROUP_ANY || id->group == hdev->group) && (id->vendor == HID_ANY_ID || id->vendor == hdev->vendor) && (id->product == HID_ANY_ID || id->product == hdev->product); } const struct hid_device_id *hid_match_id(struct hid_device *hdev, const struct hid_device_id *id) { for (; id->bus; id++) if (hid_match_one_id(hdev, id)) return id; return NULL; } static const struct hid_device_id hid_hiddev_list[] = { { HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS1) }, { } }; static bool hid_hiddev(struct hid_device *hdev) { return !!hid_match_id(hdev, hid_hiddev_list); } static ssize_t read_report_descriptor(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct hid_device *hdev = to_hid_device(dev); if (off >= hdev->rsize) return 0; if (off + count > hdev->rsize) count = hdev->rsize - off; memcpy(buf, hdev->rdesc + off, count); return count; } static ssize_t show_country(struct device *dev, struct device_attribute *attr, char *buf) { struct hid_device *hdev = to_hid_device(dev); return sprintf(buf, "%02x\n", hdev->country & 0xff); } static struct bin_attribute dev_bin_attr_report_desc = { .attr = { .name = "report_descriptor", .mode = 0444 }, .read = read_report_descriptor, .size = HID_MAX_DESCRIPTOR_SIZE, }; static struct device_attribute dev_attr_country = { .attr = { .name = "country", .mode = 0444 }, .show = show_country, }; int hid_connect(struct hid_device *hdev, unsigned int connect_mask) { static const char *types[] = { "Device", "Pointer", "Mouse", "Device", "Joystick", "Gamepad", "Keyboard", "Keypad", "Multi-Axis Controller" }; const char *type, *bus; char buf[64] = ""; unsigned int i; int len; int ret; if (hdev->quirks & HID_QUIRK_HIDDEV_FORCE) connect_mask |= (HID_CONNECT_HIDDEV_FORCE | HID_CONNECT_HIDDEV); if (hdev->quirks & HID_QUIRK_HIDINPUT_FORCE) connect_mask |= HID_CONNECT_HIDINPUT_FORCE; if (hdev->bus != BUS_USB) connect_mask &= ~HID_CONNECT_HIDDEV; if (hid_hiddev(hdev)) connect_mask |= HID_CONNECT_HIDDEV_FORCE; if ((connect_mask & HID_CONNECT_HIDINPUT) && !hidinput_connect(hdev, connect_mask & HID_CONNECT_HIDINPUT_FORCE)) hdev->claimed |= HID_CLAIMED_INPUT; if ((connect_mask & HID_CONNECT_HIDDEV) && hdev->hiddev_connect && !hdev->hiddev_connect(hdev, connect_mask & HID_CONNECT_HIDDEV_FORCE)) hdev->claimed |= HID_CLAIMED_HIDDEV; if ((connect_mask & HID_CONNECT_HIDRAW) && !hidraw_connect(hdev)) hdev->claimed |= HID_CLAIMED_HIDRAW; if (connect_mask & HID_CONNECT_DRIVER) hdev->claimed |= HID_CLAIMED_DRIVER; /* Drivers with the ->raw_event callback set are not required to connect * to any other listener. */ if (!hdev->claimed && !hdev->driver->raw_event) { hid_err(hdev, "device has no listeners, quitting\n"); return -ENODEV; } if ((hdev->claimed & HID_CLAIMED_INPUT) && (connect_mask & HID_CONNECT_FF) && hdev->ff_init) hdev->ff_init(hdev); len = 0; if (hdev->claimed & HID_CLAIMED_INPUT) len += sprintf(buf + len, "input"); if (hdev->claimed & HID_CLAIMED_HIDDEV) len += sprintf(buf + len, "%shiddev%d", len ? "," : "", hdev->minor); if (hdev->claimed & HID_CLAIMED_HIDRAW) len += sprintf(buf + len, "%shidraw%d", len ? "," : "", ((struct hidraw *)hdev->hidraw)->minor); type = "Device"; for (i = 0; i < hdev->maxcollection; i++) { struct hid_collection *col = &hdev->collection[i]; if (col->type == HID_COLLECTION_APPLICATION && (col->usage & HID_USAGE_PAGE) == HID_UP_GENDESK && (col->usage & 0xffff) < ARRAY_SIZE(types)) { type = types[col->usage & 0xffff]; break; } } switch (hdev->bus) { case BUS_USB: bus = "USB"; break; case BUS_BLUETOOTH: bus = "BLUETOOTH"; break; case BUS_I2C: bus = "I2C"; break; default: bus = "<UNKNOWN>"; } ret = device_create_file(&hdev->dev, &dev_attr_country); if (ret) hid_warn(hdev, "can't create sysfs country code attribute err: %d\n", ret); hid_info(hdev, "%s: %s HID v%x.%02x %s [%s] on %s\n", buf, bus, hdev->version >> 8, hdev->version & 0xff, type, hdev->name, hdev->phys); return 0; } EXPORT_SYMBOL_GPL(hid_connect); void hid_disconnect(struct hid_device *hdev) { device_remove_file(&hdev->dev, &dev_attr_country); if (hdev->claimed & HID_CLAIMED_INPUT) hidinput_disconnect(hdev); if (hdev->claimed & HID_CLAIMED_HIDDEV) hdev->hiddev_disconnect(hdev); if (hdev->claimed & HID_CLAIMED_HIDRAW) hidraw_disconnect(hdev); hdev->claimed = 0; } EXPORT_SYMBOL_GPL(hid_disconnect); /* * A list of devices for which there is a specialized driver on HID bus. * * Please note that for multitouch devices (driven by hid-multitouch driver), * there is a proper autodetection and autoloading in place (based on presence * of HID_DG_CONTACTID), so those devices don't need to be added to this list, * as we are doing the right thing in hid_scan_usage(). * * Autodetection for (USB) HID sensor hubs exists too. If a collection of type * physical is found inside a usage page of type sensor, hid-sensor-hub will be * used as a driver. See hid_scan_report(). */ static const struct hid_device_id hid_have_special_driver[] = { { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_WCP32PU) }, { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_X5_005D) }, { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_RP_649) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACRUX, 0x0802) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACRUX, 0xf705) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MIGHTYMOUSE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MAGICMOUSE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MAGICTRACKPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL2) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL3) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL4) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL5) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_JIS) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_JIS) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER1_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_AUREAL, USB_DEVICE_ID_AUREAL_W01RN) }, { HID_USB_DEVICE(USB_VENDOR_ID_BELKIN, USB_DEVICE_ID_FLIP_KVM) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185BFM, 0x2208) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x5506) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2PC, 0x1850) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2BFM, 0x5500) }, { HID_USB_DEVICE(USB_VENDOR_ID_BTC, USB_DEVICE_ID_BTC_EMPREX_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_BTC, USB_DEVICE_ID_BTC_EMPREX_REMOTE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION_SOLAR) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_TACTICAL_PAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_WIRELESS) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_WIRELESS2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_AK1D) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_ACER_SWITCH12) }, { HID_USB_DEVICE(USB_VENDOR_ID_CORSAIR, USB_DEVICE_ID_CORSAIR_K90) }, { HID_USB_DEVICE(USB_VENDOR_ID_CREATIVELABS, USB_DEVICE_ID_PRODIKEYS_PCMIDI) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_CP2112) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_1) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_4) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DRAGONRISE, 0x0006) }, { HID_USB_DEVICE(USB_VENDOR_ID_DRAGONRISE, 0x0011) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_ELECOM, USB_DEVICE_ID_ELECOM_BM084) }, { HID_USB_DEVICE(USB_VENDOR_ID_ELO, 0x0009) }, { HID_USB_DEVICE(USB_VENDOR_ID_ELO, 0x0030) }, { HID_USB_DEVICE(USB_VENDOR_ID_EMS, USB_DEVICE_ID_EMS_TRIO_LINKER_PLUS_II) }, { HID_USB_DEVICE(USB_VENDOR_ID_EZKEY, USB_DEVICE_ID_BTC_8193) }, { HID_USB_DEVICE(USB_VENDOR_ID_GAMERON, USB_DEVICE_ID_GAMERON_DUAL_PSX_ADAPTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_GAMERON, USB_DEVICE_ID_GAMERON_DUAL_PCS_ADAPTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_GEMBIRD, USB_DEVICE_ID_GEMBIRD_JPD_DUALFORCE2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0003) }, { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK, USB_DEVICE_ID_HOLTEK_ON_LINE_GRIP) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A04A) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A067) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A070) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A072) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A081) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A0C2) }, { HID_USB_DEVICE(USB_VENDOR_ID_HUION, USB_DEVICE_ID_HUION_TABLET) }, { HID_USB_DEVICE(USB_VENDOR_ID_JESS2, USB_DEVICE_ID_JESS2_COLOR_RUMBLE_PAD) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_ION, USB_DEVICE_ID_ICADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KENSINGTON, USB_DEVICE_ID_KS_SLIMBLADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KEYTOUCH, USB_DEVICE_ID_KEYTOUCH_IEC) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_MANTICORE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GX_IMPERATOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_ERGO_525V) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_I405X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_MOUSEPEN_I608X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_MOUSEPEN_I608X_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M610X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_PENSKETCH_M912) }, { HID_USB_DEVICE(USB_VENDOR_ID_LABTEC, USB_DEVICE_ID_LABTEC_WIRELESS_KEYBOARD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LCPOWER, USB_DEVICE_ID_LCPOWER_LC1000 ) }, #if IS_ENABLED(CONFIG_HID_LENOVO) { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TPKBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_CUSBKBD) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_CBTKBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TPPRODOCK) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_MX3000_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RECEIVER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_HARMONY_PS3) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_T651) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_DESKTOP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_EDGE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_MINI) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_ELITE_KBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_CORDLESS_DESKTOP_LX500) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_EXTREME_3D) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD_CORD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G29_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_F3D) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_FFG ) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FORCE3D_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FLIGHT_SYSTEM_G940) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFP_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFGT_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G25_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G27_WHEEL) }, #if IS_ENABLED(CONFIG_HID_LOGITECH_DJ) { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER_2) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WII_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACETRAVELLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACENAVIGATOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD_BOOTLOADER) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_COMFORT_MOUSE_4500) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_SIDEWINDER_GV) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE4K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE4K_JP) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE7K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_LK6K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_PRESENTER_8K_USB) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_DIGITAL_MEDIA_3K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_WIRELESS_OPTICAL_DESKTOP_3_0) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_OFFICE_KB) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_JP) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_POWER_COVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) }, { HID_USB_DEVICE(USB_VENDOR_ID_MSI, USB_DEVICE_ID_MSI_GT683R_LED_PANEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_1) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_4) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_5) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_6) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_7) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_8) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_9) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_10) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_11) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_12) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_13) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_14) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_15) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_16) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_17) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_18) }, { HID_USB_DEVICE(USB_VENDOR_ID_ORTEK, USB_DEVICE_ID_ORTEK_PKB1700) }, { HID_USB_DEVICE(USB_VENDOR_ID_ORTEK, USB_DEVICE_ID_ORTEK_WKB2000) }, { HID_USB_DEVICE(USB_VENDOR_ID_PENMOUNT, USB_DEVICE_ID_PENMOUNT_6000) }, { HID_USB_DEVICE(USB_VENDOR_ID_PETALYNX, USB_DEVICE_ID_PETALYNX_MAXTER_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_PLANTRONICS, HID_ANY_ID) }, { HID_USB_DEVICE(USB_VENDOR_ID_PRIMAX, USB_DEVICE_ID_PRIMAX_KEYBOARD) }, #if IS_ENABLED(CONFIG_HID_ROCCAT) { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ARVO) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ISKU) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ISKUFX) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPURE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPURE_OPTICAL) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEXTD) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KOVAPLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_LUA) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_PYRA_WIRED) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_PYRA_WIRELESS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK_GLOW) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_SAVU) }, #endif #if IS_ENABLED(CONFIG_HID_SAITEK) { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_PS1000) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_RAT7_OLD) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_RAT7) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_MMO7) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_RAT5) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_RAT9) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_IR_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_WIRELESS_KBD_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SKYCABLE, USB_DEVICE_ID_SKYCABLE_WIRELESS_PRESENTER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_PS3_BDREMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_BUZZ_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_WIRELESS_BUZZ_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_BDREMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGX_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGP_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_STEELSERIES, USB_DEVICE_ID_STEELSERIES_SRWS1) }, { HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) }, { HID_USB_DEVICE(USB_VENDOR_ID_THINGM, USB_DEVICE_ID_BLINK1) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb300) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb304) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb323) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb324) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb651) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb653) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb654) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb65a) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE_BT) }, { HID_USB_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE) }, { HID_USB_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_TOPSEED, USB_DEVICE_ID_TOPSEED_CYBERLINK) }, { HID_USB_DEVICE(USB_VENDOR_ID_TOPSEED2, USB_DEVICE_ID_TOPSEED2_RF_COMBO) }, { HID_USB_DEVICE(USB_VENDOR_ID_TWINHAN, USB_DEVICE_ID_TWINHAN_IR_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_PF1209) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP4030U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP5540U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP8060U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP1062) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_WIRELESS_TABLET_TWHL850) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_TWHA60) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_SMARTJOY_PLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_SUPER_JOY_BOX_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_DUAL_USB_JOYPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_JOY_BOX_3_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_DUAL_BOX_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_JOY_BOX_5_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_PLAYDOTCOM, USB_DEVICE_ID_PLAYDOTCOM_EMS_USBII) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SLIM_TABLET_5_8_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SLIM_TABLET_12_1_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_Q_PAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_PID_0038) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_MEDIA_TABLET_10_6_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_MEDIA_TABLET_14_1_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SIRIUS_BATTERY_FREE_TABLET) }, { HID_USB_DEVICE(USB_VENDOR_ID_X_TENSIONS, USB_DEVICE_ID_SPEEDLINK_VAD_CEZANNE) }, { HID_USB_DEVICE(USB_VENDOR_ID_XIN_MO, USB_DEVICE_ID_XIN_MO_DUAL_ARCADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZEROPLUS, 0x0005) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZEROPLUS, 0x0030) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZYDACRON, USB_DEVICE_ID_ZYDACRON_REMOTE_CONTROL) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_PRESENTER_8K_BT) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, USB_DEVICE_ID_NINTENDO_WIIMOTE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, USB_DEVICE_ID_NINTENDO_WIIMOTE2) }, { HID_USB_DEVICE(USB_VENDOR_ID_RAZER, USB_DEVICE_ID_RAZER_BLADE_14) }, { } }; struct hid_dynid { struct list_head list; struct hid_device_id id; }; /** * store_new_id - add a new HID device ID to this driver and re-probe devices * @driver: target device driver * @buf: buffer for scanning device ID data * @count: input size * * Adds a new dynamic hid device ID to this driver, * and causes the driver to probe for all devices again. */ static ssize_t store_new_id(struct device_driver *drv, const char *buf, size_t count) { struct hid_driver *hdrv = to_hid_driver(drv); struct hid_dynid *dynid; __u32 bus, vendor, product; unsigned long driver_data = 0; int ret; ret = sscanf(buf, "%x %x %x %lx", &bus, &vendor, &product, &driver_data); if (ret < 3) return -EINVAL; dynid = kzalloc(sizeof(*dynid), GFP_KERNEL); if (!dynid) return -ENOMEM; dynid->id.bus = bus; dynid->id.group = HID_GROUP_ANY; dynid->id.vendor = vendor; dynid->id.product = product; dynid->id.driver_data = driver_data; spin_lock(&hdrv->dyn_lock); list_add_tail(&dynid->list, &hdrv->dyn_list); spin_unlock(&hdrv->dyn_lock); ret = driver_attach(&hdrv->driver); return ret ? : count; } static DRIVER_ATTR(new_id, S_IWUSR, NULL, store_new_id); static void hid_free_dynids(struct hid_driver *hdrv) { struct hid_dynid *dynid, *n; spin_lock(&hdrv->dyn_lock); list_for_each_entry_safe(dynid, n, &hdrv->dyn_list, list) { list_del(&dynid->list); kfree(dynid); } spin_unlock(&hdrv->dyn_lock); } static const struct hid_device_id *hid_match_device(struct hid_device *hdev, struct hid_driver *hdrv) { struct hid_dynid *dynid; spin_lock(&hdrv->dyn_lock); list_for_each_entry(dynid, &hdrv->dyn_list, list) { if (hid_match_one_id(hdev, &dynid->id)) { spin_unlock(&hdrv->dyn_lock); return &dynid->id; } } spin_unlock(&hdrv->dyn_lock); return hid_match_id(hdev, hdrv->id_table); } static int hid_bus_match(struct device *dev, struct device_driver *drv) { struct hid_driver *hdrv = to_hid_driver(drv); struct hid_device *hdev = to_hid_device(dev); return hid_match_device(hdev, hdrv) != NULL; } static int hid_device_probe(struct device *dev) { struct hid_driver *hdrv = to_hid_driver(dev->driver); struct hid_device *hdev = to_hid_device(dev); const struct hid_device_id *id; int ret = 0; if (down_interruptible(&hdev->driver_lock)) return -EINTR; if (down_interruptible(&hdev->driver_input_lock)) { ret = -EINTR; goto unlock_driver_lock; } hdev->io_started = false; if (!hdev->driver) { id = hid_match_device(hdev, hdrv); if (id == NULL) { ret = -ENODEV; goto unlock; } hdev->driver = hdrv; if (hdrv->probe) { ret = hdrv->probe(hdev, id); } else { /* default probe */ ret = hid_open_report(hdev); if (!ret) ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); } if (ret) { hid_close_report(hdev); hdev->driver = NULL; } } unlock: if (!hdev->io_started) up(&hdev->driver_input_lock); unlock_driver_lock: up(&hdev->driver_lock); return ret; } static int hid_device_remove(struct device *dev) { struct hid_device *hdev = to_hid_device(dev); struct hid_driver *hdrv; int ret = 0; if (down_interruptible(&hdev->driver_lock)) return -EINTR; if (down_interruptible(&hdev->driver_input_lock)) { ret = -EINTR; goto unlock_driver_lock; } hdev->io_started = false; hdrv = hdev->driver; if (hdrv) { if (hdrv->remove) hdrv->remove(hdev); else /* default remove */ hid_hw_stop(hdev); hid_close_report(hdev); hdev->driver = NULL; } if (!hdev->io_started) up(&hdev->driver_input_lock); unlock_driver_lock: up(&hdev->driver_lock); return ret; } static ssize_t modalias_show(struct device *dev, struct device_attribute *a, char *buf) { struct hid_device *hdev = container_of(dev, struct hid_device, dev); return scnprintf(buf, PAGE_SIZE, "hid:b%04Xg%04Xv%08Xp%08X\n", hdev->bus, hdev->group, hdev->vendor, hdev->product); } static DEVICE_ATTR_RO(modalias); static struct attribute *hid_dev_attrs[] = { &dev_attr_modalias.attr, NULL, }; static struct bin_attribute *hid_dev_bin_attrs[] = { &dev_bin_attr_report_desc, NULL }; static const struct attribute_group hid_dev_group = { .attrs = hid_dev_attrs, .bin_attrs = hid_dev_bin_attrs, }; __ATTRIBUTE_GROUPS(hid_dev); static int hid_uevent(struct device *dev, struct kobj_uevent_env *env) { struct hid_device *hdev = to_hid_device(dev); if (add_uevent_var(env, "HID_ID=%04X:%08X:%08X", hdev->bus, hdev->vendor, hdev->product)) return -ENOMEM; if (add_uevent_var(env, "HID_NAME=%s", hdev->name)) return -ENOMEM; if (add_uevent_var(env, "HID_PHYS=%s", hdev->phys)) return -ENOMEM; if (add_uevent_var(env, "HID_UNIQ=%s", hdev->uniq)) return -ENOMEM; if (add_uevent_var(env, "MODALIAS=hid:b%04Xg%04Xv%08Xp%08X", hdev->bus, hdev->group, hdev->vendor, hdev->product)) return -ENOMEM; return 0; } static struct bus_type hid_bus_type = { .name = "hid", .dev_groups = hid_dev_groups, .match = hid_bus_match, .probe = hid_device_probe, .remove = hid_device_remove, .uevent = hid_uevent, }; /* a list of devices that shouldn't be handled by HID core at all */ static const struct hid_device_id hid_ignore_list[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_ACECAD_FLAIR) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_ACECAD_302) }, { HID_USB_DEVICE(USB_VENDOR_ID_ADS_TECH, USB_DEVICE_ID_ADS_TECH_RADIO_SI470X) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_01) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_10) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_20) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_21) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_22) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_23) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_24) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIRCABLE, USB_DEVICE_ID_AIRCABLE1) }, { HID_USB_DEVICE(USB_VENDOR_ID_ALCOR, USB_DEVICE_ID_ALCOR_USBRS232) }, { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_LCM)}, { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_LCM2)}, { HID_USB_DEVICE(USB_VENDOR_ID_AVERMEDIA, USB_DEVICE_ID_AVER_FM_MR800) }, { HID_USB_DEVICE(USB_VENDOR_ID_AXENTIA, USB_DEVICE_ID_AXENTIA_FM_RADIO) }, { HID_USB_DEVICE(USB_VENDOR_ID_BERKSHIRE, USB_DEVICE_ID_BERKSHIRE_PCWD) }, { HID_USB_DEVICE(USB_VENDOR_ID_CIDC, 0x0103) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_RADIO_SI470X) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_RADIO_SI4713) }, { HID_USB_DEVICE(USB_VENDOR_ID_CMEDIA, USB_DEVICE_ID_CM109) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_HIDCOM) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_ULTRAMOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DEALEXTREAME, USB_DEVICE_ID_DEALEXTREAME_RADIO_SI4701) }, { HID_USB_DEVICE(USB_VENDOR_ID_DELORME, USB_DEVICE_ID_DELORME_EARTHMATE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DELORME, USB_DEVICE_ID_DELORME_EM_LT20) }, { HID_USB_DEVICE(USB_VENDOR_ID_DREAM_CHEEKY, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_DREAM_CHEEKY, 0x000a) }, { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, 0x0400) }, { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, 0x0401) }, { HID_USB_DEVICE(USB_VENDOR_ID_ESSENTIAL_REALITY, USB_DEVICE_ID_ESSENTIAL_REALITY_P5) }, { HID_USB_DEVICE(USB_VENDOR_ID_ETT, USB_DEVICE_ID_TC5UH) }, { HID_USB_DEVICE(USB_VENDOR_ID_ETT, USB_DEVICE_ID_TC4UM) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0001) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0002) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_SUPER_Q2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_GOGOPEN) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_PENPOWER) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRETAGMACBETH, USB_DEVICE_ID_GRETAGMACBETH_HUEY) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_POWERMATE) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_SOUNDKNOB) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_RADIOSHARK) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_90) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_100) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_101) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_103) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_104) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_105) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_106) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_107) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_108) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_200) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_201) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_202) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_203) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_204) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_205) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_206) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_207) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_300) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_301) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_302) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_303) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_304) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_305) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_306) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_307) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_308) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_309) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_400) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_401) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_402) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_403) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_404) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_405) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_500) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_501) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_502) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_503) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_504) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1000) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1001) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1002) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1003) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1004) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1005) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1006) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1007) }, { HID_USB_DEVICE(USB_VENDOR_ID_IMATION, USB_DEVICE_ID_DISC_STAKKA) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_SPEAK_410) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_SPEAK_510) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_GN9350E) }, { HID_USB_DEVICE(USB_VENDOR_ID_KBGEAR, USB_DEVICE_ID_KBGEAR_JAMSTUDIO) }, { HID_USB_DEVICE(USB_VENDOR_ID_KWORLD, USB_DEVICE_ID_KWORLD_RADIO_FM700) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_GPEN_560) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_KYE, 0x0058) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_CASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_CASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POCKETCASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POCKETCASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOBILECASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOBILECASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYVOLTAGE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYCURRENT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYTIME) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYTEMPERATURE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYPH) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_JWM) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_DMMP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIC) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIB) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_VIDEOCOM) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_COM3LAB) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_TELEPORT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_NETWORKANALYSER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POWERCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MACHINETEST) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOSTANALYSER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOSTANALYSER2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_ABSESP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_AUTODATABUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MCT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_HYBRID) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_HEATCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_BEATPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_MCC, USB_DEVICE_ID_MCC_PMD1024LS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MCC, USB_DEVICE_ID_MCC_PMD1208LS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICKIT1) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICKIT2) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICK16F1454) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICK16F1454_V2) }, { HID_USB_DEVICE(USB_VENDOR_ID_NATIONAL_SEMICONDUCTOR, USB_DEVICE_ID_N_S_HARMONY) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 20) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 30) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 100) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 108) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 118) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 200) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 300) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 400) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 500) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0001) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0002) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0003) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_PHILIPS, USB_DEVICE_ID_PHILIPS_IEEE802154_DONGLE) }, { HID_USB_DEVICE(USB_VENDOR_ID_POWERCOM, USB_DEVICE_ID_POWERCOM_UPS) }, #if defined(CONFIG_MOUSE_SYNAPTICS_USB) || defined(CONFIG_MOUSE_SYNAPTICS_USB_MODULE) { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_INT_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_CPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_STICK) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_WP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_COMP_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_WTP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_DPAD) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_YEALINK, USB_DEVICE_ID_YEALINK_P1K_P4K_B2K) }, { HID_USB_DEVICE(USB_VENDOR_ID_RISO_KAGAKU, USB_DEVICE_ID_RI_KA_WEBMAIL) }, { } }; /** * hid_mouse_ignore_list - mouse devices which should not be handled by the hid layer * * There are composite devices for which we want to ignore only a certain * interface. This is a list of devices for which only the mouse interface will * be ignored. This allows a dedicated driver to take care of the interface. */ static const struct hid_device_id hid_mouse_ignore_list[] = { /* appletouch driver */ { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER1_TP_ONLY) }, { } }; bool hid_ignore(struct hid_device *hdev) { if (hdev->quirks & HID_QUIRK_NO_IGNORE) return false; if (hdev->quirks & HID_QUIRK_IGNORE) return true; switch (hdev->vendor) { case USB_VENDOR_ID_CODEMERCS: /* ignore all Code Mercenaries IOWarrior devices */ if (hdev->product >= USB_DEVICE_ID_CODEMERCS_IOW_FIRST && hdev->product <= USB_DEVICE_ID_CODEMERCS_IOW_LAST) return true; break; case USB_VENDOR_ID_LOGITECH: if (hdev->product >= USB_DEVICE_ID_LOGITECH_HARMONY_FIRST && hdev->product <= USB_DEVICE_ID_LOGITECH_HARMONY_LAST) return true; /* * The Keene FM transmitter USB device has the same USB ID as * the Logitech AudioHub Speaker, but it should ignore the hid. * Check if the name is that of the Keene device. * For reference: the name of the AudioHub is * "HOLTEK AudioHub Speaker". */ if (hdev->product == USB_DEVICE_ID_LOGITECH_AUDIOHUB && !strcmp(hdev->name, "HOLTEK B-LINK USB Audio ")) return true; break; case USB_VENDOR_ID_SOUNDGRAPH: if (hdev->product >= USB_DEVICE_ID_SOUNDGRAPH_IMON_FIRST && hdev->product <= USB_DEVICE_ID_SOUNDGRAPH_IMON_LAST) return true; break; case USB_VENDOR_ID_HANWANG: if (hdev->product >= USB_DEVICE_ID_HANWANG_TABLET_FIRST && hdev->product <= USB_DEVICE_ID_HANWANG_TABLET_LAST) return true; break; case USB_VENDOR_ID_JESS: if (hdev->product == USB_DEVICE_ID_JESS_YUREX && hdev->type == HID_TYPE_USBNONE) return true; break; case USB_VENDOR_ID_VELLEMAN: /* These are not HID devices. They are handled by comedi. */ if ((hdev->product >= USB_DEVICE_ID_VELLEMAN_K8055_FIRST && hdev->product <= USB_DEVICE_ID_VELLEMAN_K8055_LAST) || (hdev->product >= USB_DEVICE_ID_VELLEMAN_K8061_FIRST && hdev->product <= USB_DEVICE_ID_VELLEMAN_K8061_LAST)) return true; break; case USB_VENDOR_ID_ATMEL_V_USB: /* Masterkit MA901 usb radio based on Atmel tiny85 chip and * it has the same USB ID as many Atmel V-USB devices. This * usb radio is handled by radio-ma901.c driver so we want * ignore the hid. Check the name, bus, product and ignore * if we have MA901 usb radio. */ if (hdev->product == USB_DEVICE_ID_ATMEL_V_USB && hdev->bus == BUS_USB && strncmp(hdev->name, "www.masterkit.ru MA901", 22) == 0) return true; break; } if (hdev->type == HID_TYPE_USBMOUSE && hid_match_id(hdev, hid_mouse_ignore_list)) return true; return !!hid_match_id(hdev, hid_ignore_list); } EXPORT_SYMBOL_GPL(hid_ignore); int hid_add_device(struct hid_device *hdev) { static atomic_t id = ATOMIC_INIT(0); int ret; if (WARN_ON(hdev->status & HID_STAT_ADDED)) return -EBUSY; /* we need to kill them here, otherwise they will stay allocated to * wait for coming driver */ if (hid_ignore(hdev)) return -ENODEV; /* * Check for the mandatory transport channel. */ if (!hdev->ll_driver->raw_request) { hid_err(hdev, "transport driver missing .raw_request()\n"); return -EINVAL; } /* * Read the device report descriptor once and use as template * for the driver-specific modifications. */ ret = hdev->ll_driver->parse(hdev); if (ret) return ret; if (!hdev->dev_rdesc) return -ENODEV; /* * Scan generic devices for group information */ if (hid_ignore_special_drivers || (!hdev->group && !hid_match_id(hdev, hid_have_special_driver))) { ret = hid_scan_report(hdev); if (ret) hid_warn(hdev, "bad device descriptor (%d)\n", ret); } /* XXX hack, any other cleaner solution after the driver core * is converted to allow more than 20 bytes as the device name? */ dev_set_name(&hdev->dev, "%04X:%04X:%04X.%04X", hdev->bus, hdev->vendor, hdev->product, atomic_inc_return(&id)); hid_debug_register(hdev, dev_name(&hdev->dev)); ret = device_add(&hdev->dev); if (!ret) hdev->status |= HID_STAT_ADDED; else hid_debug_unregister(hdev); return ret; } EXPORT_SYMBOL_GPL(hid_add_device); /** * hid_allocate_device - allocate new hid device descriptor * * Allocate and initialize hid device, so that hid_destroy_device might be * used to free it. * * New hid_device pointer is returned on success, otherwise ERR_PTR encoded * error value. */ struct hid_device *hid_allocate_device(void) { struct hid_device *hdev; int ret = -ENOMEM; hdev = kzalloc(sizeof(*hdev), GFP_KERNEL); if (hdev == NULL) return ERR_PTR(ret); device_initialize(&hdev->dev); hdev->dev.release = hid_device_release; hdev->dev.bus = &hid_bus_type; device_enable_async_suspend(&hdev->dev); hid_close_report(hdev); init_waitqueue_head(&hdev->debug_wait); INIT_LIST_HEAD(&hdev->debug_list); spin_lock_init(&hdev->debug_list_lock); sema_init(&hdev->driver_lock, 1); sema_init(&hdev->driver_input_lock, 1); return hdev; } EXPORT_SYMBOL_GPL(hid_allocate_device); static void hid_remove_device(struct hid_device *hdev) { if (hdev->status & HID_STAT_ADDED) { device_del(&hdev->dev); hid_debug_unregister(hdev); hdev->status &= ~HID_STAT_ADDED; } kfree(hdev->dev_rdesc); hdev->dev_rdesc = NULL; hdev->dev_rsize = 0; } /** * hid_destroy_device - free previously allocated device * * @hdev: hid device * * If you allocate hid_device through hid_allocate_device, you should ever * free by this function. */ void hid_destroy_device(struct hid_device *hdev) { hid_remove_device(hdev); put_device(&hdev->dev); } EXPORT_SYMBOL_GPL(hid_destroy_device); int __hid_register_driver(struct hid_driver *hdrv, struct module *owner, const char *mod_name) { int ret; hdrv->driver.name = hdrv->name; hdrv->driver.bus = &hid_bus_type; hdrv->driver.owner = owner; hdrv->driver.mod_name = mod_name; INIT_LIST_HEAD(&hdrv->dyn_list); spin_lock_init(&hdrv->dyn_lock); ret = driver_register(&hdrv->driver); if (ret) return ret; ret = driver_create_file(&hdrv->driver, &driver_attr_new_id); if (ret) driver_unregister(&hdrv->driver); return ret; } EXPORT_SYMBOL_GPL(__hid_register_driver); void hid_unregister_driver(struct hid_driver *hdrv) { driver_remove_file(&hdrv->driver, &driver_attr_new_id); driver_unregister(&hdrv->driver); hid_free_dynids(hdrv); } EXPORT_SYMBOL_GPL(hid_unregister_driver); int hid_check_keys_pressed(struct hid_device *hid) { struct hid_input *hidinput; int i; if (!(hid->claimed & HID_CLAIMED_INPUT)) return 0; list_for_each_entry(hidinput, &hid->inputs, list) { for (i = 0; i < BITS_TO_LONGS(KEY_MAX); i++) if (hidinput->input->key[i]) return 1; } return 0; } EXPORT_SYMBOL_GPL(hid_check_keys_pressed); static int __init hid_init(void) { int ret; if (hid_debug) pr_warn("hid_debug is now used solely for parser and driver debugging.\n" "debugfs is now used for inspecting the device (report descriptor, reports)\n"); ret = bus_register(&hid_bus_type); if (ret) { pr_err("can't register hid bus\n"); goto err; } ret = hidraw_init(); if (ret) goto err_bus; hid_debug_init(); return 0; err_bus: bus_unregister(&hid_bus_type); err: return ret; } static void __exit hid_exit(void) { hid_debug_exit(); hidraw_exit(); bus_unregister(&hid_bus_type); } module_init(hid_init); module_exit(hid_exit); MODULE_AUTHOR("Andreas Gal"); MODULE_AUTHOR("Vojtech Pavlik"); MODULE_AUTHOR("Jiri Kosina"); MODULE_LICENSE(DRIVER_LICENSE);
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5338_0
crossvul-cpp_data_good_2691_1
/* * Copyright (c) 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Original code by Matt Thomas, Digital Equipment Corporation * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete IS-IS & CLNP support. */ /* \summary: ISO CLNS, ESIS, and ISIS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ether.h" #include "nlpid.h" #include "extract.h" #include "gmpls.h" #include "oui.h" #include "signature.h" static const char tstr[] = " [|isis]"; /* * IS-IS is defined in ISO 10589. Look there for protocol definitions. */ #define SYSTEM_ID_LEN ETHER_ADDR_LEN #define NODE_ID_LEN SYSTEM_ID_LEN+1 #define LSP_ID_LEN SYSTEM_ID_LEN+2 #define ISIS_VERSION 1 #define ESIS_VERSION 1 #define CLNP_VERSION 1 #define ISIS_PDU_TYPE_MASK 0x1F #define ESIS_PDU_TYPE_MASK 0x1F #define CLNP_PDU_TYPE_MASK 0x1F #define CLNP_FLAG_MASK 0xE0 #define ISIS_LAN_PRIORITY_MASK 0x7F #define ISIS_PDU_L1_LAN_IIH 15 #define ISIS_PDU_L2_LAN_IIH 16 #define ISIS_PDU_PTP_IIH 17 #define ISIS_PDU_L1_LSP 18 #define ISIS_PDU_L2_LSP 20 #define ISIS_PDU_L1_CSNP 24 #define ISIS_PDU_L2_CSNP 25 #define ISIS_PDU_L1_PSNP 26 #define ISIS_PDU_L2_PSNP 27 static const struct tok isis_pdu_values[] = { { ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"}, { ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"}, { ISIS_PDU_PTP_IIH, "p2p IIH"}, { ISIS_PDU_L1_LSP, "L1 LSP"}, { ISIS_PDU_L2_LSP, "L2 LSP"}, { ISIS_PDU_L1_CSNP, "L1 CSNP"}, { ISIS_PDU_L2_CSNP, "L2 CSNP"}, { ISIS_PDU_L1_PSNP, "L1 PSNP"}, { ISIS_PDU_L2_PSNP, "L2 PSNP"}, { 0, NULL} }; /* * A TLV is a tuple of a type, length and a value and is normally used for * encoding information in all sorts of places. This is an enumeration of * the well known types. * * list taken from rfc3359 plus some memory from veterans ;-) */ #define ISIS_TLV_AREA_ADDR 1 /* iso10589 */ #define ISIS_TLV_IS_REACH 2 /* iso10589 */ #define ISIS_TLV_ESNEIGH 3 /* iso10589 */ #define ISIS_TLV_PART_DIS 4 /* iso10589 */ #define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */ #define ISIS_TLV_ISNEIGH 6 /* iso10589 */ #define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */ #define ISIS_TLV_PADDING 8 /* iso10589 */ #define ISIS_TLV_LSP 9 /* iso10589 */ #define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */ #define ISIS_TLV_CHECKSUM 12 /* rfc3358 */ #define ISIS_TLV_CHECKSUM_MINLEN 2 #define ISIS_TLV_POI 13 /* rfc6232 */ #define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */ #define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2 #define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */ #define ISIS_TLV_DECNET_PHASE4 42 #define ISIS_TLV_LUCENT_PRIVATE 66 #define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */ #define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */ #define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */ #define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */ #define ISIS_TLV_IDRP_INFO_MINLEN 1 #define ISIS_TLV_IPADDR 132 /* rfc1195 */ #define ISIS_TLV_IPAUTH 133 /* rfc1195 */ #define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_HOSTNAME 137 /* rfc2763 */ #define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */ #define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */ #define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */ #define ISIS_TLV_NORTEL_PRIVATE1 176 #define ISIS_TLV_NORTEL_PRIVATE2 177 #define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */ #define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1 #define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2 #define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED_MINLEN 2 #define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */ #define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */ #define ISIS_TLV_IIH_SEQNR_MINLEN 4 #define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */ #define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3 static const struct tok isis_tlv_values[] = { { ISIS_TLV_AREA_ADDR, "Area address(es)"}, { ISIS_TLV_IS_REACH, "IS Reachability"}, { ISIS_TLV_ESNEIGH, "ES Neighbor(s)"}, { ISIS_TLV_PART_DIS, "Partition DIS"}, { ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"}, { ISIS_TLV_ISNEIGH, "IS Neighbor(s)"}, { ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"}, { ISIS_TLV_PADDING, "Padding"}, { ISIS_TLV_LSP, "LSP entries"}, { ISIS_TLV_AUTH, "Authentication"}, { ISIS_TLV_CHECKSUM, "Checksum"}, { ISIS_TLV_POI, "Purge Originator Identifier"}, { ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"}, { ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"}, { ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"}, { ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"}, { ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"}, { ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"}, { ISIS_TLV_PROTOCOLS, "Protocols supported"}, { ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"}, { ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"}, { ISIS_TLV_IPADDR, "IPv4 Interface address(es)"}, { ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"}, { ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"}, { ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"}, { ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"}, { ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"}, { ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"}, { ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"}, { ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"}, { ISIS_TLV_HOSTNAME, "Hostname"}, { ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"}, { ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"}, { ISIS_TLV_MT_SUPPORTED, "Multi Topology"}, { ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"}, { ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"}, { ISIS_TLV_IP6_REACH, "IPv6 reachability"}, { ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"}, { ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"}, { ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"}, { ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"}, { 0, NULL } }; #define ESIS_OPTION_PROTOCOLS 129 #define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */ #define ESIS_OPTION_SECURITY 197 /* iso9542 */ #define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */ #define ESIS_OPTION_PRIORITY 205 /* iso9542 */ #define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */ #define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */ static const struct tok esis_option_values[] = { { ESIS_OPTION_PROTOCOLS, "Protocols supported"}, { ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" }, { ESIS_OPTION_SECURITY, "Security" }, { ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" }, { ESIS_OPTION_PRIORITY, "Priority" }, { ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" }, { ESIS_OPTION_SNPA_MASK, "SNPA Mask" }, { 0, NULL } }; #define CLNP_OPTION_DISCARD_REASON 193 #define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */ #define CLNP_OPTION_SECURITY 197 /* iso8473 */ #define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */ #define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */ #define CLNP_OPTION_PADDING 204 /* iso8473 */ #define CLNP_OPTION_PRIORITY 205 /* iso8473 */ static const struct tok clnp_option_values[] = { { CLNP_OPTION_DISCARD_REASON, "Discard Reason"}, { CLNP_OPTION_PRIORITY, "Priority"}, { CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"}, { CLNP_OPTION_SECURITY, "Security"}, { CLNP_OPTION_SOURCE_ROUTING, "Source Routing"}, { CLNP_OPTION_ROUTE_RECORDING, "Route Recording"}, { CLNP_OPTION_PADDING, "Padding"}, { 0, NULL } }; static const struct tok clnp_option_rfd_class_values[] = { { 0x0, "General"}, { 0x8, "Address"}, { 0x9, "Source Routeing"}, { 0xa, "Lifetime"}, { 0xb, "PDU Discarded"}, { 0xc, "Reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_general_values[] = { { 0x0, "Reason not specified"}, { 0x1, "Protocol procedure error"}, { 0x2, "Incorrect checksum"}, { 0x3, "PDU discarded due to congestion"}, { 0x4, "Header syntax error (cannot be parsed)"}, { 0x5, "Segmentation needed but not permitted"}, { 0x6, "Incomplete PDU received"}, { 0x7, "Duplicate option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_address_values[] = { { 0x0, "Destination address unreachable"}, { 0x1, "Destination address unknown"}, { 0, NULL } }; static const struct tok clnp_option_rfd_source_routeing_values[] = { { 0x0, "Unspecified source routeing error"}, { 0x1, "Syntax error in source routeing field"}, { 0x2, "Unknown address in source routeing field"}, { 0x3, "Path not acceptable"}, { 0, NULL } }; static const struct tok clnp_option_rfd_lifetime_values[] = { { 0x0, "Lifetime expired while data unit in transit"}, { 0x1, "Lifetime expired during reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_pdu_discard_values[] = { { 0x0, "Unsupported option not specified"}, { 0x1, "Unsupported protocol version"}, { 0x2, "Unsupported security option"}, { 0x3, "Unsupported source routeing option"}, { 0x4, "Unsupported recording of route option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_reassembly_values[] = { { 0x0, "Reassembly interference"}, { 0, NULL } }; /* array of 16 error-classes */ static const struct tok *clnp_option_rfd_error_class[] = { clnp_option_rfd_general_values, NULL, NULL, NULL, NULL, NULL, NULL, NULL, clnp_option_rfd_address_values, clnp_option_rfd_source_routeing_values, clnp_option_rfd_lifetime_values, clnp_option_rfd_pdu_discard_values, clnp_option_rfd_reassembly_values, NULL, NULL, NULL }; #define CLNP_OPTION_OPTION_QOS_MASK 0x3f #define CLNP_OPTION_SCOPE_MASK 0xc0 #define CLNP_OPTION_SCOPE_SA_SPEC 0x40 #define CLNP_OPTION_SCOPE_DA_SPEC 0x80 #define CLNP_OPTION_SCOPE_GLOBAL 0xc0 static const struct tok clnp_option_scope_values[] = { { CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"}, { CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"}, { CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_values[] = { { 0x0, "partial"}, { 0x1, "complete"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_string_values[] = { { CLNP_OPTION_SOURCE_ROUTING, "source routing"}, { CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"}, { 0, NULL } }; static const struct tok clnp_option_qos_global_values[] = { { 0x20, "reserved"}, { 0x10, "sequencing vs. delay"}, { 0x08, "congested"}, { 0x04, "delay vs. cost"}, { 0x02, "error vs. delay"}, { 0x01, "error vs. cost"}, { 0, NULL } }; #define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */ #define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */ #define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */ static const struct tok isis_ext_is_reach_subtlv_values[] = { { ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" }, { ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" }, { ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" }, { ISIS_SUBTLV_SPB_METRIC, "SPB Metric" }, { 250, "Reserved for cisco specific extensions" }, { 251, "Reserved for cisco specific extensions" }, { 252, "Reserved for cisco specific extensions" }, { 253, "Reserved for cisco specific extensions" }, { 254, "Reserved for cisco specific extensions" }, { 255, "Reserved for future expansion" }, { 0, NULL } }; #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */ static const struct tok isis_ext_ip_reach_subtlv_values[] = { { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" }, { 0, NULL } }; static const struct tok isis_subtlv_link_attribute_values[] = { { 0x01, "Local Protection Available" }, { 0x02, "Link excluded from local protection path" }, { 0x04, "Local maintenance required"}, { 0, NULL } }; #define ISIS_SUBTLV_AUTH_SIMPLE 1 #define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */ #define ISIS_SUBTLV_AUTH_MD5 54 #define ISIS_SUBTLV_AUTH_MD5_LEN 16 #define ISIS_SUBTLV_AUTH_PRIVATE 255 static const struct tok isis_subtlv_auth_values[] = { { ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"}, { ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"}, { ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"}, { ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"}, { 0, NULL } }; #define ISIS_SUBTLV_IDRP_RES 0 #define ISIS_SUBTLV_IDRP_LOCAL 1 #define ISIS_SUBTLV_IDRP_ASN 2 static const struct tok isis_subtlv_idrp_values[] = { { ISIS_SUBTLV_IDRP_RES, "Reserved"}, { ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"}, { ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"}, { 0, NULL} }; #define ISIS_SUBTLV_SPB_MCID 4 #define ISIS_SUBTLV_SPB_DIGEST 5 #define ISIS_SUBTLV_SPB_BVID 6 #define ISIS_SUBTLV_SPB_INSTANCE 1 #define ISIS_SUBTLV_SPBM_SI 3 #define ISIS_SPB_MCID_LEN 51 #define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102 #define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33 #define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6 #define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19 #define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8 static const struct tok isis_mt_port_cap_subtlv_values[] = { { ISIS_SUBTLV_SPB_MCID, "SPB MCID" }, { ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" }, { ISIS_SUBTLV_SPB_BVID, "SPB BVID" }, { 0, NULL } }; static const struct tok isis_mt_capability_subtlv_values[] = { { ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" }, { ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" }, { 0, NULL } }; struct isis_spb_mcid { uint8_t format_id; uint8_t name[32]; uint8_t revision_lvl[2]; uint8_t digest[16]; }; struct isis_subtlv_spb_mcid { struct isis_spb_mcid mcid; struct isis_spb_mcid aux_mcid; }; struct isis_subtlv_spb_instance { uint8_t cist_root_id[8]; uint8_t cist_external_root_path_cost[4]; uint8_t bridge_priority[2]; uint8_t spsourceid[4]; uint8_t no_of_trees; }; #define CLNP_SEGMENT_PART 0x80 #define CLNP_MORE_SEGMENTS 0x40 #define CLNP_REQUEST_ER 0x20 static const struct tok clnp_flag_values[] = { { CLNP_SEGMENT_PART, "Segmentation permitted"}, { CLNP_MORE_SEGMENTS, "more Segments"}, { CLNP_REQUEST_ER, "request Error Report"}, { 0, NULL} }; #define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4) #define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3) #define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80) #define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78) #define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40) #define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20) #define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10) #define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8) #define ISIS_MASK_MTID(x) ((x)&0x0fff) #define ISIS_MASK_MTFLAGS(x) ((x)&0xf000) static const struct tok isis_mt_flag_values[] = { { 0x4000, "ATT bit set"}, { 0x8000, "Overload bit set"}, { 0, NULL} }; #define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80) #define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20) #define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40) #define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f) #define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1) static const struct tok isis_mt_values[] = { { 0, "IPv4 unicast"}, { 1, "In-Band Management"}, { 2, "IPv6 unicast"}, { 3, "Multicast"}, { 4095, "Development, Experimental or Proprietary"}, { 0, NULL } }; static const struct tok isis_iih_circuit_type_values[] = { { 1, "Level 1 only"}, { 2, "Level 2 only"}, { 3, "Level 1, Level 2"}, { 0, NULL} }; #define ISIS_LSP_TYPE_UNUSED0 0 #define ISIS_LSP_TYPE_LEVEL_1 1 #define ISIS_LSP_TYPE_UNUSED2 2 #define ISIS_LSP_TYPE_LEVEL_2 3 static const struct tok isis_lsp_istype_values[] = { { ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_1, "L1 IS"}, { ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_2, "L2 IS"}, { 0, NULL } }; /* * Katz's point to point adjacency TLV uses codes to tell us the state of * the remote adjacency. Enumerate them. */ #define ISIS_PTP_ADJ_UP 0 #define ISIS_PTP_ADJ_INIT 1 #define ISIS_PTP_ADJ_DOWN 2 static const struct tok isis_ptp_adjancey_values[] = { { ISIS_PTP_ADJ_UP, "Up" }, { ISIS_PTP_ADJ_INIT, "Initializing" }, { ISIS_PTP_ADJ_DOWN, "Down" }, { 0, NULL} }; struct isis_tlv_ptp_adj { uint8_t adjacency_state; uint8_t extd_local_circuit_id[4]; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; uint8_t neighbor_extd_local_circuit_id[4]; }; static void osi_print_cksum(netdissect_options *, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length); static int clnp_print(netdissect_options *, const uint8_t *, u_int); static void esis_print(netdissect_options *, const uint8_t *, u_int); static int isis_print(netdissect_options *, const uint8_t *, u_int); struct isis_metric_block { uint8_t metric_default; uint8_t metric_delay; uint8_t metric_expense; uint8_t metric_error; }; struct isis_tlv_is_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_nodeid[NODE_ID_LEN]; }; struct isis_tlv_es_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; }; struct isis_tlv_ip_reach { struct isis_metric_block isis_metric_block; uint8_t prefix[4]; uint8_t mask[4]; }; static const struct tok isis_is_reach_virtual_values[] = { { 0, "IsNotVirtual"}, { 1, "IsVirtual"}, { 0, NULL } }; static const struct tok isis_restart_flag_values[] = { { 0x1, "Restart Request"}, { 0x2, "Restart Acknowledgement"}, { 0x4, "Suppress adjacency advertisement"}, { 0, NULL } }; struct isis_common_header { uint8_t nlpid; uint8_t fixed_len; uint8_t version; /* Protocol version */ uint8_t id_length; uint8_t pdu_type; /* 3 MSbits are reserved */ uint8_t pdu_version; /* Packet format version */ uint8_t reserved; uint8_t max_area; }; struct isis_iih_lan_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t priority; uint8_t lan_id[NODE_ID_LEN]; }; struct isis_iih_ptp_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t circuit_id; }; struct isis_lsp_header { uint8_t pdu_len[2]; uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; uint8_t typeblock; }; struct isis_csnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; uint8_t start_lsp_id[LSP_ID_LEN]; uint8_t end_lsp_id[LSP_ID_LEN]; }; struct isis_psnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; }; struct isis_tlv_lsp { uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; }; #define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header)) #define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header)) #define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header)) #define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header)) #define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header)) #define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header)) void isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length) { if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */ ND_PRINT((ndo, "|OSI")); return; } if (ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p)); switch (*p) { case NLPID_CLNP: if (!clnp_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_ESIS: esis_print(ndo, p, length); return; case NLPID_ISIS: if (!isis_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_NULLNS: ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); break; case NLPID_Q933: q933_print(ndo, p + 1, length - 1); break; case NLPID_IP: ip_print(ndo, p + 1, length - 1); break; case NLPID_IP6: ip6_print(ndo, p + 1, length - 1); break; case NLPID_PPP: ppp_print(ndo, p + 1, length - 1); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p)); ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); if (length > 1) print_unknown_data(ndo, p, "\n\t", length); break; } } #define CLNP_PDU_ER 1 #define CLNP_PDU_DT 28 #define CLNP_PDU_MD 29 #define CLNP_PDU_ERQ 30 #define CLNP_PDU_ERP 31 static const struct tok clnp_pdu_values[] = { { CLNP_PDU_ER, "Error Report"}, { CLNP_PDU_MD, "MD"}, { CLNP_PDU_DT, "Data"}, { CLNP_PDU_ERQ, "Echo Request"}, { CLNP_PDU_ERP, "Echo Response"}, { 0, NULL } }; struct clnp_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t lifetime; /* units of 500ms */ uint8_t type; uint8_t segment_length[2]; uint8_t cksum[2]; }; struct clnp_segment_header_t { uint8_t data_unit_id[2]; uint8_t segment_offset[2]; uint8_t total_length[2]; }; /* * clnp_print * Decode CLNP packets. Return 0 on error. */ static int clnp_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr,*source_address,*dest_address; u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags; const struct clnp_header_t *clnp_header; const struct clnp_segment_header_t *clnp_segment_header; uint8_t rfd_error_major,rfd_error_minor; clnp_header = (const struct clnp_header_t *) pptr; ND_TCHECK(*clnp_header); li = clnp_header->length_indicator; optr = pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "CLNP")); /* * Sanity checking of the header. */ if (clnp_header->version != CLNP_VERSION) { ND_PRINT((ndo, "version %d packet not supported", clnp_header->version)); return (0); } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return (0); } if (li < sizeof(struct clnp_header_t)) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return (0); } /* FIXME further header sanity checking */ clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK; clnp_flags = clnp_header->type & CLNP_FLAG_MASK; pptr += sizeof(struct clnp_header_t); li -= sizeof(struct clnp_header_t); if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); dest_address_length = *pptr; pptr += 1; li -= 1; if (li < dest_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, dest_address_length); dest_address = pptr; pptr += dest_address_length; li -= dest_address_length; if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); source_address_length = *pptr; pptr += 1; li -= 1; if (li < source_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, source_address_length); source_address = pptr; pptr += source_address_length; li -= source_address_length; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s > %s, %s, length %u", ndo->ndo_eflag ? "" : ", ", isonsap_string(ndo, source_address, source_address_length), isonsap_string(ndo, dest_address, dest_address_length), tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type), length)); return (1); } ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x", tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type), clnp_header->length_indicator, clnp_header->version, clnp_header->lifetime/2, (clnp_header->lifetime%2)*5, EXTRACT_16BITS(clnp_header->segment_length), EXTRACT_16BITS(clnp_header->cksum))); osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7, clnp_header->length_indicator); ND_PRINT((ndo, "\n\tFlags [%s]", bittok2str(clnp_flag_values, "none", clnp_flags))); ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length), dest_address_length, isonsap_string(ndo, dest_address, dest_address_length))); if (clnp_flags & CLNP_SEGMENT_PART) { if (li < sizeof(const struct clnp_segment_header_t)) { ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part")); return (0); } clnp_segment_header = (const struct clnp_segment_header_t *) pptr; ND_TCHECK(*clnp_segment_header); ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u", EXTRACT_16BITS(clnp_segment_header->data_unit_id), EXTRACT_16BITS(clnp_segment_header->segment_offset), EXTRACT_16BITS(clnp_segment_header->total_length))); pptr+=sizeof(const struct clnp_segment_header_t); li-=sizeof(const struct clnp_segment_header_t); } /* now walk the options */ while (li >= 2) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return (0); } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return (0); } ND_TCHECK2(*pptr, opli); li -= opli; tptr = pptr; tlen = opli; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(clnp_option_values,"Unknown",op), op, opli)); /* * We've already checked that the entire option is present * in the captured packet with the ND_TCHECK2() call. * Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2() * checks. * We do, however, need to check tlen, to make sure we * don't run past the end of the option. */ switch (op) { case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */ case CLNP_OPTION_SOURCE_ROUTING: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "%s %s", tok2str(clnp_option_sr_rr_values,"Unknown",*tptr), tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op))); nsap_offset=*(tptr+1); if (nsap_offset == 0) { ND_PRINT((ndo, " Bad NSAP offset (0)")); break; } nsap_offset-=1; /* offset to nsap list */ if (nsap_offset > tlen) { ND_PRINT((ndo, " Bad NSAP offset (past end of option)")); break; } tptr+=nsap_offset; tlen-=nsap_offset; while (tlen > 0) { source_address_length=*tptr; if (tlen < source_address_length+1) { ND_PRINT((ndo, "\n\t NSAP address goes past end of option")); break; } if (source_address_length > 0) { source_address=(tptr+1); ND_TCHECK2(*source_address, source_address_length); ND_PRINT((ndo, "\n\t NSAP address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length))); } tlen-=source_address_length+1; } break; case CLNP_OPTION_PRIORITY: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "0x%1x", *tptr&0x0f)); break; case CLNP_OPTION_QOS_MAINTENANCE: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s", tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK))); if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL) ND_PRINT((ndo, "\n\t QoS Flags [%s]", bittok2str(clnp_option_qos_global_values, "none", *tptr&CLNP_OPTION_OPTION_QOS_MASK))); break; case CLNP_OPTION_SECURITY: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u", tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK), *(tptr+1))); break; case CLNP_OPTION_DISCARD_REASON: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } rfd_error_major = (*tptr&0xf0) >> 4; rfd_error_minor = *tptr&0x0f; ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)", tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major), rfd_error_major, tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor), rfd_error_minor)); break; case CLNP_OPTION_PADDING: ND_PRINT((ndo, "padding data")); break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } switch (clnp_pdu_type) { case CLNP_PDU_ER: /* fall through */ case CLNP_PDU_ERP: ND_TCHECK(*pptr); if (*(pptr) == NLPID_CLNP) { ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); /* FIXME recursion protection */ clnp_print(ndo, pptr, length - clnp_header->length_indicator); break; } case CLNP_PDU_DT: case CLNP_PDU_MD: case CLNP_PDU_ERQ: default: /* dump the PDU specific data */ if (length-(pptr-optr) > 0) { ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator)); print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr)); } } return (1); trunc: ND_PRINT((ndo, "[|clnp]")); return (1); } #define ESIS_PDU_REDIRECT 6 #define ESIS_PDU_ESH 2 #define ESIS_PDU_ISH 4 static const struct tok esis_pdu_values[] = { { ESIS_PDU_REDIRECT, "redirect"}, { ESIS_PDU_ESH, "ESH"}, { ESIS_PDU_ISH, "ISH"}, { 0, NULL } }; struct esis_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t reserved; uint8_t type; uint8_t holdtime[2]; uint8_t cksum[2]; }; static void esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (snpal == 6) ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal))); if (netal != 0) ND_PRINT((ndo, "\n\t NET (length: %u) %s", netal, isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*pptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: return; } static void isis_print_mcid(netdissect_options *ndo, const struct isis_spb_mcid *mcid) { int i; ND_TCHECK(*mcid); ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id)); if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend)) goto trunc; ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl))); ND_PRINT((ndo, ", Digest: ")); for(i=0;i<16;i++) ND_PRINT((ndo, "%.2x ", mcid->digest[i])); trunc: ND_PRINT((ndo, "%s", tstr)); } static int isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static int isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN); ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN); ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: ND_TCHECK2(*tptr, 8); ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } /* shared routine for printing system, node and lsp-ids */ static char * isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } /* print the 4-byte metric block which is common found in the old-style TLVs */ static int isis_print_metric_block(netdissect_options *ndo, const struct isis_metric_block *isis_metric_block) { ND_PRINT((ndo, ", Default Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay)) ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense)) ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error)) ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal")); return(1); /* everything is ok */ } static int isis_print_tlv_ip_reach(netdissect_options *ndo, const uint8_t *cp, const char *ident, int length) { int prefix_len; const struct isis_tlv_ip_reach *tlv_ip_reach; tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp; while (length > 0) { if ((size_t)length < sizeof(*tlv_ip_reach)) { ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)", length, (unsigned long)sizeof(*tlv_ip_reach))); return (0); } if (!ND_TTEST(*tlv_ip_reach)) return (0); prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask)); if (prefix_len == -1) ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), ipaddr_string(ndo, (tlv_ip_reach->mask)))); else ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), prefix_len)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s", ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up", ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay)) ND_PRINT((ndo, "%s Delay Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense)) ND_PRINT((ndo, "%s Expense Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error)) ND_PRINT((ndo, "%s Error Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal")); length -= sizeof(struct isis_tlv_ip_reach); tlv_ip_reach++; } return (1); } /* * this is the common IP-REACH subTLV decoder it is called * from various EXTD-IP REACH TLVs (135,235,236,237) */ static int isis_print_ip_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, int subt, int subl, const char *ident) { /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr,subl); switch(subt) { case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */ case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32: while (subl >= 4) { ND_PRINT((ndo, ", 0x%08x (=%u)", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr))); tptr+=4; subl-=4; } break; case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64: while (subl >= 8) { ND_PRINT((ndo, ", 0x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr+4))); tptr+=8; subl-=8; } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: ND_PRINT((ndo, "%s", ident)); ND_PRINT((ndo, "%s", tstr)); return(0); } /* * this is the common IS-REACH subTLV decoder it is called * from isis_print_ext_is_reach() */ static int isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } /* * this is the common IS-REACH decoder it is called * from various EXTD-IS REACH style TLVs (22,24,222) */ static int isis_print_ext_is_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, int tlv_type) { char ident_buffer[20]; int subtlv_type,subtlv_len,subtlv_sum_len; int proc_bytes = 0; /* how many bytes did we process ? */ if (!ND_TTEST2(*tptr, NODE_ID_LEN)) return(0); ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */ if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */ return(0); ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr))); tptr+=3; } if (!ND_TTEST2(*tptr, 1)) return(0); subtlv_sum_len=*(tptr++); /* read out subTLV length */ proc_bytes=NODE_ID_LEN+3+1; ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no ")); if (subtlv_sum_len) { ND_PRINT((ndo, " (%u)", subtlv_sum_len)); while (subtlv_sum_len>0) { if (!ND_TTEST2(*tptr,2)) return(0); subtlv_type=*(tptr++); subtlv_len=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer)) return(0); tptr+=subtlv_len; subtlv_sum_len-=(subtlv_len+2); proc_bytes+=(subtlv_len+2); } } return(proc_bytes); } /* * this is the common Multi Topology ID decoder * it is called from various MT-TLVs (222,229,235,237) */ static int isis_print_mtid(netdissect_options *ndo, const uint8_t *tptr, const char *ident) { if (!ND_TTEST2(*tptr, 2)) return(0); ND_PRINT((ndo, "%s%s", ident, tok2str(isis_mt_values, "Reserved for IETF Consensus", ISIS_MASK_MTID(EXTRACT_16BITS(tptr))))); ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]", ISIS_MASK_MTID(EXTRACT_16BITS(tptr)), bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr))))); return(2); } /* * this is the common extended IP reach decoder * it is called from TLVs (135,235,236,237) * we process the TLV and optional subTLVs and return * the amount of processed bytes */ static int isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } /* * Clear checksum and lifetime prior to signature verification. */ static void isis_clear_checksum_lifetime(void *header) { struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header; header_lsp->checksum[0] = 0; header_lsp->checksum[1] = 0; header_lsp->remaining_lifetime[0] = 0; header_lsp->remaining_lifetime[1] = 0; } /* * isis_print * Decode IS-IS packets. Return 0 on error. */ static int isis_print(netdissect_options *ndo, const uint8_t *p, u_int length) { const struct isis_common_header *isis_header; const struct isis_iih_lan_header *header_iih_lan; const struct isis_iih_ptp_header *header_iih_ptp; const struct isis_lsp_header *header_lsp; const struct isis_csnp_header *header_csnp; const struct isis_psnp_header *header_psnp; const struct isis_tlv_lsp *tlv_lsp; const struct isis_tlv_ptp_adj *tlv_ptp_adj; const struct isis_tlv_is_reach *tlv_is_reach; const struct isis_tlv_es_reach *tlv_es_reach; uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; uint8_t ext_is_len, ext_ip_len, mt_len; const uint8_t *optr, *pptr, *tptr; u_short packet_len,pdu_len, key_id; u_int i,vendor_id; int sigcheck; packet_len=length; optr = p; /* initialize the _o_riginal pointer to the packet start - need it for parsing the checksum TLV and authentication TLV verification */ isis_header = (const struct isis_common_header *)p; ND_TCHECK(*isis_header); if (length < ISIS_COMMON_HEADER_SIZE) goto trunc; pptr = p+(ISIS_COMMON_HEADER_SIZE); header_iih_lan = (const struct isis_iih_lan_header *)pptr; header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; header_lsp = (const struct isis_lsp_header *)pptr; header_csnp = (const struct isis_csnp_header *)pptr; header_psnp = (const struct isis_psnp_header *)pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "IS-IS")); /* * Sanity checking of the header. */ if (isis_header->version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->version)); return (0); } if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { ND_PRINT((ndo, "system ID length of %d is not supported", isis_header->id_length)); return (0); } if (isis_header->pdu_version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version)); return (0); } if (length < isis_header->fixed_len) { ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length)); return (0); } if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); return (0); } max_area = isis_header->max_area; switch(max_area) { case 0: max_area = 3; /* silly shit */ break; case 255: ND_PRINT((ndo, "bad packet -- 255 areas")); return (0); default: break; } id_length = isis_header->id_length; switch(id_length) { case 0: id_length = 6; /* silly shit again */ break; case 1: /* 1-8 are valid sys-ID lenghts */ case 2: case 3: case 4: case 5: case 6: case 7: case 8: break; case 255: id_length = 0; /* entirely useless */ break; default: break; } /* toss any non 6-byte sys-ID len PDUs */ if (id_length != 6 ) { ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length)); return (0); } pdu_type=isis_header->pdu_type; /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, "%s%s", ndo->ndo_eflag ? "" : ", ", tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type))); } else { /* ok they seem to want to know everything - lets fully decode it */ ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)", tok2str(isis_pdu_values, "unknown, type %u", pdu_type), isis_header->fixed_len, isis_header->version, isis_header->pdu_version, id_length, isis_header->id_length, max_area, isis_header->max_area)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */ return (0); /* for optionally debugging the common header */ } } switch (pdu_type) { case ISIS_PDU_L1_LAN_IIH: case ISIS_PDU_L2_LAN_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_lan); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", lan-id %s, prio %u", isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), header_iih_lan->priority)); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_lan->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_lan->circuit_type))); ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u", isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); break; case ISIS_PDU_PTP_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_ptp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_ptp->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_ptp->circuit_type))); ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u", header_iih_ptp->circuit_id, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); break; case ISIS_PDU_L1_LSP: case ISIS_PDU_L2_LSP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); return (0); } ND_TCHECK(*header_lsp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime), EXTRACT_16BITS(header_lsp->checksum))); osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, EXTRACT_16BITS(header_lsp->checksum), 12, length-12); ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s", pdu_len, ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : "")); if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : "")); ND_PRINT((ndo, "ATT bit set, ")); } ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : "")); ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)", ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); break; case ISIS_PDU_L1_CSNP: case ISIS_PDU_L2_CSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_csnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_csnp->source_id, NODE_ID_LEN), pdu_len)); ND_PRINT((ndo, "\n\t start lsp-id: %s", isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); ND_PRINT((ndo, "\n\t end lsp-id: %s", isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); break; case ISIS_PDU_L1_PSNP: case ISIS_PDU_L2_PSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { ND_PRINT((ndo, "- bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_psnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_psnp->source_id, NODE_ID_LEN), pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); break; default: if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", length %u", length)); return (1); } (void)print_unknown_data(ndo, pptr, "\n\t ", length); return (0); } /* * Now print the TLV's. */ while (packet_len > 0) { ND_TCHECK2(*pptr, 2); if (packet_len < 2) goto trunc; tlv_type = *pptr++; tlv_len = *pptr++; tmp =tlv_len; /* copy temporary len & pointer to packet data */ tptr = pptr; packet_len -= 2; /* first lets see if we know the TLVs name*/ ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u", tok2str(isis_tlv_values, "unknown", tlv_type), tlv_type, tlv_len)); if (tlv_len == 0) /* something is invalid */ continue; if (packet_len < tlv_len) goto trunc; /* now check if we have a decoder otherwise do a hexdump at the end*/ switch (tlv_type) { case ISIS_TLV_AREA_ADDR: ND_TCHECK2(*tptr, 1); alen = *tptr++; while (tmp && alen < tmp) { ND_TCHECK2(*tptr, alen); ND_PRINT((ndo, "\n\t Area address (length: %u): %s", alen, isonsap_string(ndo, tptr, alen))); tptr += alen; tmp -= alen + 1; if (tmp==0) /* if this is the last area address do not attemt a boundary check */ break; ND_TCHECK2(*tptr, 1); alen = *tptr++; } break; case ISIS_TLV_ISNEIGH: while (tmp >= ETHER_ADDR_LEN) { ND_TCHECK2(*tptr, ETHER_ADDR_LEN); ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN))); tmp -= ETHER_ADDR_LEN; tptr += ETHER_ADDR_LEN; } break; case ISIS_TLV_ISNEIGH_VARLEN: if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ goto trunctlv; lan_alen = *tptr++; /* LAN address length */ if (lan_alen == 0) { ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)")); break; } tmp --; ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen)); while (tmp >= lan_alen) { ND_TCHECK2(*tptr, lan_alen); ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen))); tmp -= lan_alen; tptr +=lan_alen; } break; case ISIS_TLV_PADDING: break; case ISIS_TLV_MT_IS_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; while (tmp >= 2+NODE_ID_LEN+3+1) { ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_ALIAS_ID: while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_EXT_IS_REACH: while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_REACH: ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ ND_PRINT((ndo, "\n\t %s", tok2str(isis_is_reach_virtual_values, "bogus virtual flag 0x%02x", *tptr++))); tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_is_reach)) { ND_TCHECK(*tlv_is_reach); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_is_reach); tlv_is_reach++; } break; case ISIS_TLV_ESNEIGH: tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_es_reach)) { ND_TCHECK(*tlv_es_reach); ND_PRINT((ndo, "\n\t ES Neighbor: %s", isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_es_reach); tlv_es_reach++; } break; /* those two TLVs share the same format */ case ISIS_TLV_INT_IP_REACH: case ISIS_TLV_EXT_IP_REACH: if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len)) return (1); break; case ISIS_TLV_EXTD_IP_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP6_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6ADDR: while (tmp>=sizeof(struct in6_addr)) { ND_TCHECK2(*tptr, sizeof(struct in6_addr)); ND_PRINT((ndo, "\n\t IPv6 interface address: %s", ip6addr_string(ndo, tptr))); tptr += sizeof(struct in6_addr); tmp -= sizeof(struct in6_addr); } break; case ISIS_TLV_AUTH: ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t %s: ", tok2str(isis_subtlv_auth_values, "unknown Authentication type 0x%02x", *tptr))); switch (*tptr) { case ISIS_SUBTLV_AUTH_SIMPLE: if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_SUBTLV_AUTH_MD5: for(i=1;i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1) ND_PRINT((ndo, ", (invalid subTLV) ")); sigcheck = signature_verify(ndo, optr, length, tptr + 1, isis_clear_checksum_lifetime, header_lsp); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); break; case ISIS_SUBTLV_AUTH_GENERIC: ND_TCHECK2(*(tptr + 1), 2); key_id = EXTRACT_16BITS((tptr+1)); ND_PRINT((ndo, "%u, password: ", key_id)); for(i=1 + sizeof(uint16_t);i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } break; case ISIS_SUBTLV_AUTH_PRIVATE: default: if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_PTP_ADJ: tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr; if(tmp>=1) { ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)", tok2str(isis_ptp_adjancey_values, "unknown", *tptr), *tptr)); tmp--; } if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); } if(tmp>=SYSTEM_ID_LEN) { ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t Neighbor System-ID: %s", isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); tmp-=SYSTEM_ID_LEN; } if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); } break; case ISIS_TLV_PROTOCOLS: ND_PRINT((ndo, "\n\t NLPID(s): ")); while (tmp>0) { ND_TCHECK2(*(tptr), 1); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (tmp>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; tmp--; } break; case ISIS_TLV_MT_PORT_CAP: { ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d", (EXTRACT_16BITS (tptr) >> 12), (EXTRACT_16BITS (tptr) & 0x0fff))); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); break; } case ISIS_TLV_MT_CAPABILITY: ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d", (EXTRACT_16BITS(tptr) >> 15) & 0x01, (EXTRACT_16BITS(tptr) >> 12) & 0x07, EXTRACT_16BITS(tptr) & 0x0fff)); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_capability_subtlv(ndo, tptr, tmp); break; case ISIS_TLV_TE_ROUTER_ID: ND_TCHECK2(*pptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr))); break; case ISIS_TLV_IPADDR: while (tmp>=sizeof(struct in_addr)) { ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr += sizeof(struct in_addr); tmp -= sizeof(struct in_addr); } break; case ISIS_TLV_HOSTNAME: ND_PRINT((ndo, "\n\t Hostname: ")); if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_TLV_SHARED_RISK_GROUP: if (tmp < NODE_ID_LEN) break; ND_TCHECK2(*tptr, NODE_ID_LEN); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); tmp-=(NODE_ID_LEN); if (tmp < 1) break; ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered")); tmp--; if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); while (tmp>=4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr))); tptr+=4; tmp-=4; } break; case ISIS_TLV_LSP: tlv_lsp = (const struct isis_tlv_lsp *)tptr; while(tmp>=sizeof(struct isis_tlv_lsp)) { ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); ND_PRINT((ndo, "\n\t lsp-id: %s", isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); ND_TCHECK2(tlv_lsp->sequence_number, 4); ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number))); ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); ND_TCHECK2(tlv_lsp->checksum, 2); ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum))); tmp-=sizeof(struct isis_tlv_lsp); tlv_lsp++; } break; case ISIS_TLV_CHECKSUM: if (tmp < ISIS_TLV_CHECKSUM_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr))); /* do not attempt to verify the checksum if it is zero * most likely a HMAC-MD5 TLV is also present and * to avoid conflicts the checksum TLV is zeroed. * see rfc3358 for details */ osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, length); break; case ISIS_TLV_POI: if (tlv_len >= SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s", isis_print_id(tptr + 1, SYSTEM_ID_LEN))); } if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Received from System-ID: %s", isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); } break; case ISIS_TLV_MT_SUPPORTED: if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) break; while (tmp>1) { /* length can only be a multiple of 2, otherwise there is something broken -> so decode down until length is 1 */ if (tmp!=1) { mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; } else { ND_PRINT((ndo, "\n\t invalid MT-ID")); break; } } break; case ISIS_TLV_RESTART_SIGNALING: /* first attempt to decode the flags */ if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); ND_PRINT((ndo, "\n\t Flags [%s]", bittok2str(isis_restart_flag_values, "none", *tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; /* is there anything other than the flags field? */ if (tmp == 0) break; if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; /* is there an additional sysid field present ?*/ if (tmp == SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN))); } break; case ISIS_TLV_IDRP_INFO: if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s", tok2str(isis_subtlv_idrp_values, "Unknown (0x%02x)", *tptr))); switch (*tptr++) { case ISIS_SUBTLV_IDRP_ASN: ND_TCHECK2(*tptr, 2); /* fetch AS number */ ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr))); break; case ISIS_SUBTLV_IDRP_LOCAL: case ISIS_SUBTLV_IDRP_RES: default: if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_LSP_BUFFERSIZE: if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr))); break; case ISIS_TLV_PART_DIS: while (tmp >= SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN))); tptr+=SYSTEM_ID_LEN; tmp-=SYSTEM_ID_LEN; } break; case ISIS_TLV_PREFIX_NEIGH: if (tmp < sizeof(struct isis_metric_block)) break; ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); ND_PRINT((ndo, "\n\t Metric Block")); isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); tptr+=sizeof(struct isis_metric_block); tmp-=sizeof(struct isis_metric_block); while(tmp>0) { ND_TCHECK2(*tptr, 1); prefix_len=*tptr++; /* read out prefix length in semioctets*/ if (prefix_len < 2) { ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len)); break; } tmp--; if (tmp < prefix_len/2) break; ND_TCHECK2(*tptr, prefix_len / 2); ND_PRINT((ndo, "\n\t\tAddress: %s/%u", isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); tptr+=prefix_len/2; tmp-=prefix_len/2; } break; case ISIS_TLV_IIH_SEQNR: if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr))); break; case ISIS_TLV_VENDOR_PRIVATE: if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ vendor_id = EXTRACT_24BITS(tptr); ND_PRINT((ndo, "\n\t Vendor: %s (%u)", tok2str(oui_values, "Unknown", vendor_id), vendor_id)); tptr+=3; tmp-=3; if (tmp > 0) /* hexdump the rest */ if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp)) return(0); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case ISIS_TLV_DECNET_PHASE4: case ISIS_TLV_LUCENT_PRIVATE: case ISIS_TLV_IPAUTH: case ISIS_TLV_NORTEL_PRIVATE1: case ISIS_TLV_NORTEL_PRIVATE2: default: if (ndo->ndo_vflag <= 1) { if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len)) return(0); } break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len)) return(0); } pptr += tlv_len; packet_len -= tlv_len; } if (packet_len != 0) { ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len)); } return (1); trunc: ND_PRINT((ndo, "%s", tstr)); return (1); trunctlv: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static void osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length) { uint16_t calculated_checksum; /* do not attempt to verify the checksum if it is zero, * if the offset is nonsense, * or the base pointer is not sane */ if (!checksum || checksum_offset < 0 || !ND_TTEST2(*(pptr + checksum_offset), 2) || (u_int)checksum_offset > length || !ND_TTEST2(*pptr, length)) { ND_PRINT((ndo, " (unverified)")); } else { #if 0 printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length); #endif calculated_checksum = create_osi_cksum(pptr, checksum_offset, length); if (checksum == calculated_checksum) { ND_PRINT((ndo, " (correct)")); } else { ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum)); } } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2691_1
crossvul-cpp_data_good_768_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L OOO CCCC AAA L EEEEE % % L O O C A A L E % % L O O C AAAAA L EEE % % L O O C A A L E % % LLLLL OOO CCCC A A LLLLL EEEEE % % % % % % MagickCore Image Locale Methods % % % % Software Design % % Cristy % % July 2003 % % % % % % 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/blob.h" #include "MagickCore/client.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/locale_.h" #include "MagickCore/locale-private.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT) # define MAGICKCORE_LOCALE_SUPPORT #endif #define LocaleFilename "locale.xml" /* Static declarations. */ static const char *LocaleMap = "<?xml version=\"1.0\"?>" "<localemap>" " <locale name=\"C\">" " <Exception>" " <Message name=\"\">" " </Message>" " </Exception>" " </locale>" "</localemap>"; #ifdef __VMS #define asciimap AsciiMap #endif #if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP) static const unsigned char AsciiMap[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }; #endif static SemaphoreInfo *locale_semaphore = (SemaphoreInfo *) NULL; static SplayTreeInfo *locale_cache = (SplayTreeInfo *) NULL; #if defined(MAGICKCORE_LOCALE_SUPPORT) static volatile locale_t c_locale = (locale_t) NULL; #endif /* Forward declarations. */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *), LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *, const size_t,ExceptionInfo *); #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCLocale() allocates the C locale object, or (locale_t) 0 with % errno set if it cannot be acquired. % % The format of the AcquireCLocale method is: % % locale_t AcquireCLocale(void) % */ static locale_t AcquireCLocale(void) { #if defined(MAGICKCORE_HAVE_NEWLOCALE) if (c_locale == (locale_t) NULL) c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0); #elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__) if (c_locale == (locale_t) NULL) c_locale=_create_locale(LC_ALL,"C"); #endif return(c_locale); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e L o c a l e S p l a y T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireLocaleSplayTree() caches one or more locale configurations which % provides a mapping between locale attributes and a locale tag. % % The format of the AcquireLocaleSplayTree method is: % % SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the font file tag. % % o locale: the actual locale. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyLocaleNode(void *locale_info) { register LocaleInfo *p; p=(LocaleInfo *) locale_info; if (p->path != (char *) NULL) p->path=DestroyString(p->path); if (p->tag != (char *) NULL) p->tag=DestroyString(p->tag); if (p->message != (char *) NULL) p->message=DestroyString(p->message); return(RelinquishMagickMemory(p)); } static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, const char *locale,ExceptionInfo *exception) { MagickStatusType status; SplayTreeInfo *cache; cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL, DestroyLocaleNode); status=MagickTrue; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetLocaleOptions(filename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); if (GetNumberOfNodesInSplayTree(cache) == 0) { options=GetLocaleOptions("english.xml",exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); } } #endif if (GetNumberOfNodesInSplayTree(cache) == 0) status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0, exception); return(cache); } #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCLocale() releases the resources allocated for a locale object % returned by a call to the AcquireCLocale() method. % % The format of the DestroyCLocale method is: % % void DestroyCLocale(void) % */ static void DestroyCLocale(void) { if (c_locale != (locale_t) NULL) freelocale(c_locale); c_locale=(locale_t) NULL; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyLocaleOptions() releases memory associated with an locale % messages. % % The format of the DestroyProfiles method is: % % LinkedListInfo *DestroyLocaleOptions(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *DestroyOptions(void *message) { return(DestroyStringInfo((StringInfo *) message)); } MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages) { assert(messages != (LinkedListInfo *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); return(DestroyLinkedList(messages,DestroyOptions)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleFile() prints formatted output of a variable argument list to a % file in the "C" locale. % % The format of the FormatLocaleFile method is: % % ssize_t FormatLocaleFile(FILE *file,const char *format,...) % % A description of each parameter follows. % % o file: the file. % % o format: A file describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleFileList(FILE *file, const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vfprintf_l(file,format,locale,operands); #else n=(ssize_t) vfprintf_l(file,locale,format,operands); #endif } #else #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vfprintf(file,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vfprintf(file,format,operands); #endif #endif return(n); } MagickExport ssize_t FormatLocaleFile(FILE *file, const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleFileList(file,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleString() prints formatted output of a variable argument list to % a string buffer in the "C" locale. % % The format of the FormatLocaleString method is: % % ssize_t FormatLocaleString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatLocaleString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string, const size_t length,const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vsnprintf_l(string,length,format,locale,operands); #else n=(ssize_t) vsnprintf_l(string,length,locale,format,operands); #endif } #elif defined(MAGICKCORE_HAVE_VSNPRINTF) #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vsnprintf(string,length,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vsnprintf(string,length,format,operands); #endif #else n=(ssize_t) vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return(n); } MagickExport ssize_t FormatLocaleString(char *magick_restrict string, const size_t length,const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t L o c a l e I n f o _ % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfo_() searches the locale list for the specified tag and if % found returns attributes for that element. % % The format of the GetLocaleInfo method is: % % const LocaleInfo *GetLocaleInfo_(const char *tag, % ExceptionInfo *exception) % % A description of each parameter follows: % % o tag: the locale tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag, ExceptionInfo *exception) { const LocaleInfo *locale_info; assert(exception != (ExceptionInfo *) NULL); if (IsLocaleTreeInstantiated(exception) == MagickFalse) return((const LocaleInfo *) NULL); LockSemaphoreInfo(locale_semaphore); if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0)) { ResetSplayTreeIterator(locale_cache); locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e I n f o L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfoList() returns any locale messages that match the % specified pattern. % % The format of the GetLocaleInfoList function is: % % const LocaleInfo **GetLocaleInfoList(const char *pattern, % size_t *number_messages,ExceptionInfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of locale messages in % the list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleInfoCompare(const void *x,const void *y) { const LocaleInfo **p, **q; p=(const LocaleInfo **) x, q=(const LocaleInfo **) y; if (LocaleCompare((*p)->path,(*q)->path) == 0) return(LocaleCompare((*p)->tag,(*q)->tag)); return(LocaleCompare((*p)->path,(*q)->path)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern, size_t *number_messages,ExceptionInfo *exception) { const LocaleInfo **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((const LocaleInfo **) NULL); messages=(const LocaleInfo **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (const LocaleInfo **) NULL) return((const LocaleInfo **) NULL); /* Generate locale list. */ LockSemaphoreInfo(locale_semaphore); ResetSplayTreeIterator(locale_cache); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=p; p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare); messages[i]=(LocaleInfo *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleList() returns any locale messages that match the specified % pattern. % % The format of the GetLocaleList function is: % % char **GetLocaleList(const char *pattern,size_t *number_messages, % Exceptioninfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of messages in the % list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleTagCompare(const void *x,const void *y) { register char **p, **q; p=(char **) x; q=(char **) y; return(LocaleCompare(*p,*q)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages, ExceptionInfo *exception) { char **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((char **) NULL); messages=(char **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (char **) NULL) return((char **) NULL); LockSemaphoreInfo(locale_semaphore); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=ConstantString(p->tag); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare); messages[i]=(char *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e M e s s a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleMessage() returns a message in the current locale that matches the % supplied tag. % % The format of the GetLocaleMessage method is: % % const char *GetLocaleMessage(const char *tag) % % A description of each parameter follows: % % o tag: Return a message that matches this tag in the current locale. % */ MagickExport const char *GetLocaleMessage(const char *tag) { char name[MagickLocaleExtent]; const LocaleInfo *locale_info; ExceptionInfo *exception; if ((tag == (const char *) NULL) || (*tag == '\0')) return(tag); exception=AcquireExceptionInfo(); (void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag); locale_info=GetLocaleInfo_(name,exception); exception=DestroyExceptionInfo(exception); if (locale_info != (const LocaleInfo *) NULL) return(locale_info->message); return(tag); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleOptions() returns any Magick configuration messages associated % with the specified filename. % % The format of the GetLocaleOptions method is: % % LinkedListInfo *GetLocaleOptions(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the locale file tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport LinkedListInfo *GetLocaleOptions(const char *filename, ExceptionInfo *exception) { char path[MagickPathExtent]; const char *element; LinkedListInfo *messages, *paths; StringInfo *xml; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); assert(exception != (ExceptionInfo *) NULL); (void) CopyMagickString(path,filename,MagickPathExtent); /* Load XML from configuration files to linked-list. */ messages=NewLinkedList(0); paths=GetConfigurePaths(filename,exception); if (paths != (LinkedListInfo *) NULL) { ResetLinkedListIterator(paths); element=(const char *) GetNextValueInLinkedList(paths); while (element != (const char *) NULL) { (void) FormatLocaleString(path,MagickPathExtent,"%s%s",element, filename); (void) LogMagickEvent(LocaleEvent,GetMagickModule(), "Searching for locale file: \"%s\"",path); xml=ConfigureFileToStringInfo(path); if (xml != (StringInfo *) NULL) (void) AppendValueToLinkedList(messages,xml); element=(const char *) GetNextValueInLinkedList(paths); } paths=DestroyLinkedList(paths,RelinquishMagickMemory); } #if defined(MAGICKCORE_WINDOWS_SUPPORT) { char *blob; blob=(char *) NTResourceToBlob(filename); if (blob != (char *) NULL) { xml=AcquireStringInfo(0); SetStringInfoLength(xml,strlen(blob)+1); SetStringInfoDatum(xml,(const unsigned char *) blob); blob=(char *) RelinquishMagickMemory(blob); SetStringInfoPath(xml,filename); (void) AppendValueToLinkedList(messages,xml); } } #endif ResetLinkedListIterator(messages); return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleValue() returns the message associated with the locale info. % % The format of the GetLocaleValue method is: % % const char *GetLocaleValue(const LocaleInfo *locale_info) % % A description of each parameter follows: % % o locale_info: The locale info. % */ MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(locale_info != (LocaleInfo *) NULL); assert(locale_info->signature == MagickCoreSignature); return(locale_info->message); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s L o c a l e T r e e I n s t a n t i a t e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsLocaleTreeInstantiated() determines if the locale tree is instantiated. % If not, it instantiates the tree and returns it. % % The format of the IsLocaleInstantiated method is: % % MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) % % A description of each parameter follows. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) { if (locale_cache == (SplayTreeInfo *) NULL) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache == (SplayTreeInfo *) NULL) { char *locale; register const char *p; locale=(char *) NULL; p=setlocale(LC_CTYPE,(const char *) NULL); if (p != (const char *) NULL) locale=ConstantString(p); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_ALL"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_MESSAGES"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_CTYPE"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LANG"); if (locale == (char *) NULL) locale=ConstantString("C"); locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception); locale=DestroyString(locale); } UnlockSemaphoreInfo(locale_semaphore); } return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n t e r p r e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretLocaleValue() interprets the string as a floating point number in % the "C" locale and returns its value as a double. If sentinal is not a null % pointer, the method also sets the value pointed by sentinal to point to the % first character after the number. % % The format of the InterpretLocaleValue method is: % % double InterpretLocaleValue(const char *value,char **sentinal) % % A description of each parameter follows: % % o value: the string value. % % o sentinal: if sentinal is not NULL, a pointer to the character after the % last character used in the conversion is stored in the location % referenced by sentinal. % */ MagickExport double InterpretLocaleValue(const char *magick_restrict string, char **magick_restrict sentinal) { char *q; double value; if ((*string == '0') && ((string[1] | 0x20)=='x')) value=(double) strtoul(string,&q,16); else { #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L) locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) value=strtod(string,&q); else value=strtod_l(string,&q,locale); #else value=strtod(string,&q); #endif } if (sentinal != (char **) NULL) *sentinal=q; return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t L o c a l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListLocaleInfo() lists the locale info to a file. % % The format of the ListLocaleInfo method is: % % MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to a FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListLocaleInfo(FILE *file, ExceptionInfo *exception) { const char *path; const LocaleInfo **locale_info; register ssize_t i; size_t number_messages; if (file == (const FILE *) NULL) file=stdout; number_messages=0; locale_info=GetLocaleInfoList("*",&number_messages,exception); if (locale_info == (const LocaleInfo **) NULL) return(MagickFalse); path=(const char *) NULL; for (i=0; i < (ssize_t) number_messages; i++) { if (locale_info[i]->stealth != MagickFalse) continue; if ((path == (const char *) NULL) || (LocaleCompare(path,locale_info[i]->path) != 0)) { if (locale_info[i]->path != (char *) NULL) (void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path); (void) FormatLocaleFile(file,"Tag/Message\n"); (void) FormatLocaleFile(file, "-------------------------------------------------" "------------------------------\n"); } path=locale_info[i]->path; (void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag); if (locale_info[i]->message != (char *) NULL) (void) FormatLocaleFile(file," %s",locale_info[i]->message); (void) FormatLocaleFile(file,"\n"); } (void) fflush(file); locale_info=(const LocaleInfo **) RelinquishMagickMemory((void *) locale_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o a d L o c a l e C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LoadLocaleCache() loads the locale configurations which provides a mapping % between locale attributes and a locale name. % % The format of the LoadLocaleCache method is: % % MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, % const char *filename,const size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o xml: The locale list in XML format. % % o filename: The locale list filename. % % o depth: depth of <include /> statements. % % o exception: return any errors or warnings in this structure. % */ static void ChopLocaleComponents(char *path,const size_t components) { register char *p; ssize_t count; if (*path == '\0') return; p=path+strlen(path)-1; if (*p == '/') *p='\0'; for (count=0; (count < (ssize_t) components) && (p > path); p--) if (*p == '/') { *p='\0'; count++; } if (count < (ssize_t) components) *path='\0'; } static void LocaleFatalErrorHandler( const ExceptionType magick_unused(severity), const char *reason,const char *description) { magick_unreferenced(severity); if (reason == (char *) NULL) return; (void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason); if (description != (char *) NULL) (void) FormatLocaleFile(stderr," (%s)",description); (void) FormatLocaleFile(stderr,".\n"); (void) fflush(stderr); exit(1); } static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception) { char keyword[MagickLocaleExtent], message[MagickLocaleExtent], tag[MagickLocaleExtent], *token; const char *q; FatalErrorHandler fatal_handler; LocaleInfo *locale_info; MagickStatusType status; register char *p; size_t extent; /* Read the locale configure file. */ (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading locale configure file \"%s\" ...",filename); if (xml == (const char *) NULL) return(MagickFalse); status=MagickTrue; locale_info=(LocaleInfo *) NULL; *tag='\0'; *message='\0'; *keyword='\0'; fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler); token=AcquireString(xml); extent=strlen(token)+MagickPathExtent; for (q=(char *) xml; *q != '\0'; ) { /* Interpret XML. */ GetNextToken(q,&q,extent,token); if (*token == '\0') break; (void) CopyMagickString(keyword,token,MagickLocaleExtent); if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0) { /* Doctype element. */ while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleNCompare(keyword,"<!--",4) == 0) { /* Comment element. */ while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleCompare(keyword,"<include") == 0) { /* Include element. */ while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"locale") == 0) { if (LocaleCompare(locale,token) != 0) break; continue; } if (LocaleCompare(keyword,"file") == 0) { if (depth > MagickMaxRecursionDepth) (void) ThrowMagickException(exception,GetMagickModule(), ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token); else { char path[MagickPathExtent], *file_xml; *path='\0'; GetPathComponent(filename,HeadPath,path); if (*path != '\0') (void) ConcatenateMagickString(path,DirectorySeparator, MagickPathExtent); if (*token == *DirectorySeparator) (void) CopyMagickString(path,token,MagickPathExtent); else (void) ConcatenateMagickString(path,token,MagickPathExtent); file_xml=FileToXML(path,~0UL); if (file_xml != (char *) NULL) { status&=LoadLocaleCache(cache,file_xml,path,locale, depth+1,exception); file_xml=DestroyString(file_xml); } } } } continue; } if (LocaleCompare(keyword,"<locale") == 0) { /* Locale element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); } continue; } if (LocaleCompare(keyword,"</locale>") == 0) { ChopLocaleComponents(tag,1); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (LocaleCompare(keyword,"<localemap>") == 0) continue; if (LocaleCompare(keyword,"</localemap>") == 0) continue; if (LocaleCompare(keyword,"<message") == 0) { /* Message element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"name") == 0) { (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); } } for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ; while (isspace((int) ((unsigned char) *p)) != 0) p++; q--; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; (void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2), MagickLocaleExtent)); locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info)); (void) memset(locale_info,0,sizeof(*locale_info)); locale_info->path=ConstantString(filename); locale_info->tag=ConstantString(tag); locale_info->message=ConstantString(message); locale_info->signature=MagickCoreSignature; status=AddValueToSplayTree(cache,locale_info->tag,locale_info); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", locale_info->tag); (void) ConcatenateMagickString(tag,message,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent); q++; continue; } if (LocaleCompare(keyword,"</message>") == 0) { ChopLocaleComponents(tag,2); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (*keyword == '<') { /* Subpath element. */ if (*(keyword+1) == '?') continue; if (*(keyword+1) == '/') { ChopLocaleComponents(tag,1); if (*tag != '\0') (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } token[strlen(token)-1]='\0'; (void) CopyMagickString(token,token+1,MagickLocaleExtent); (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } GetNextToken(q,(const char **) NULL,extent,token); if (*token != '=') continue; } token=(char *) RelinquishMagickMemory(token); (void) SetFatalErrorHandler(fatal_handler); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % LocaleCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The format of the LocaleCompare method is: % % int LocaleCompare(const char *p,const char *q) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % */ MagickExport int LocaleCompare(const char *p,const char *q) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRCASECMP) return(strcasecmp(p,q)); #else { register int c, d; for ( ; ; ) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if ((c == 0) || (AsciiMap[c] != AsciiMap[d])) break; p++; q++; } return(AsciiMap[c]-(int) AsciiMap[d]); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLower() transforms all of the characters in the supplied % null-terminated string, changing all uppercase letters to lowercase. % % The format of the LocaleLower method is: % % void LocaleLower(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to lower-case Locale. % */ MagickExport void LocaleLower(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleLowercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLowercase() convert to lowercase. % % The format of the LocaleLowercase method is: % % void LocaleLowercase(const int c) % % A description of each parameter follows: % % o If c is a uppercase letter, return its lowercase equivalent. % */ MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e N C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleNCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % % LocaleNCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The LocaleNCompare method makes the same comparison as LocaleCompare but % looks at a maximum of n bytes. Bytes following a null byte are not % compared. % % The format of the LocaleNCompare method is: % % int LocaleNCompare(const char *p,const char *q,const size_t n) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % % o length: the number of characters to compare in strings p and q. % */ MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRNCASECMP) return(strncasecmp(p,q,length)); #else { register int c, d; register size_t i; for (i=length; i != 0; i--) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if (AsciiMap[c] != AsciiMap[d]) return(AsciiMap[c]-(int) AsciiMap[d]); if (c == 0) return(0); p++; q++; } return(0); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUpper() transforms all of the characters in the supplied % null-terminated string, changing all lowercase letters to uppercase. % % The format of the LocaleUpper method is: % % void LocaleUpper(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to upper-case Locale. % */ MagickExport void LocaleUpper(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleUppercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUppercase() convert to uppercase. % % The format of the LocaleUppercase method is: % % void LocaleUppercase(const int c) % % A description of each parameter follows: % % o If c is a lowercase letter, return its uppercase equivalent. % */ MagickExport int LocaleUppercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentGenesis() instantiates the locale component. % % The format of the LocaleComponentGenesis method is: % % MagickBooleanType LocaleComponentGenesis(void) % */ MagickPrivate MagickBooleanType LocaleComponentGenesis(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) locale_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentTerminus() destroys the locale component. % % The format of the LocaleComponentTerminus method is: % % LocaleComponentTerminus(void) % */ MagickPrivate void LocaleComponentTerminus(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache != (SplayTreeInfo *) NULL) locale_cache=DestroySplayTree(locale_cache); #if defined(MAGICKCORE_LOCALE_SUPPORT) DestroyCLocale(); #endif UnlockSemaphoreInfo(locale_semaphore); RelinquishSemaphoreInfo(&locale_semaphore); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_768_1
crossvul-cpp_data_good_2572_0
/* * Monkey's Audio lossless audio decoder * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org> * based upon libdemac from Dave Chapman. * * 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 <inttypes.h> #include "libavutil/avassert.h" #include "libavutil/channel_layout.h" #include "libavutil/opt.h" #include "lossless_audiodsp.h" #include "avcodec.h" #include "bswapdsp.h" #include "bytestream.h" #include "internal.h" #include "get_bits.h" #include "unary.h" /** * @file * Monkey's Audio lossless audio decoder */ #define MAX_CHANNELS 2 #define MAX_BYTESPERSAMPLE 3 #define APE_FRAMECODE_MONO_SILENCE 1 #define APE_FRAMECODE_STEREO_SILENCE 3 #define APE_FRAMECODE_PSEUDO_STEREO 4 #define HISTORY_SIZE 512 #define PREDICTOR_ORDER 8 /** Total size of all predictor histories */ #define PREDICTOR_SIZE 50 #define YDELAYA (18 + PREDICTOR_ORDER*4) #define YDELAYB (18 + PREDICTOR_ORDER*3) #define XDELAYA (18 + PREDICTOR_ORDER*2) #define XDELAYB (18 + PREDICTOR_ORDER) #define YADAPTCOEFFSA 18 #define XADAPTCOEFFSA 14 #define YADAPTCOEFFSB 10 #define XADAPTCOEFFSB 5 /** * Possible compression levels * @{ */ enum APECompressionLevel { COMPRESSION_LEVEL_FAST = 1000, COMPRESSION_LEVEL_NORMAL = 2000, COMPRESSION_LEVEL_HIGH = 3000, COMPRESSION_LEVEL_EXTRA_HIGH = 4000, COMPRESSION_LEVEL_INSANE = 5000 }; /** @} */ #define APE_FILTER_LEVELS 3 /** Filter orders depending on compression level */ static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = { { 0, 0, 0 }, { 16, 0, 0 }, { 64, 0, 0 }, { 32, 256, 0 }, { 16, 256, 1280 } }; /** Filter fraction bits depending on compression level */ static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = { { 0, 0, 0 }, { 11, 0, 0 }, { 11, 0, 0 }, { 10, 13, 0 }, { 11, 13, 15 } }; /** Filters applied to the decoded data */ typedef struct APEFilter { int16_t *coeffs; ///< actual coefficients used in filtering int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients int16_t *historybuffer; ///< filter memory int16_t *delay; ///< filtered values int avg; } APEFilter; typedef struct APERice { uint32_t k; uint32_t ksum; } APERice; typedef struct APERangecoder { uint32_t low; ///< low end of interval uint32_t range; ///< length of interval uint32_t help; ///< bytes_to_follow resp. intermediate value unsigned int buffer; ///< buffer for input/output } APERangecoder; /** Filter histories */ typedef struct APEPredictor { int32_t *buf; int32_t lastA[2]; int32_t filterA[2]; int32_t filterB[2]; int32_t coeffsA[2][4]; ///< adaption coefficients int32_t coeffsB[2][5]; ///< adaption coefficients int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE]; unsigned int sample_pos; } APEPredictor; /** Decoder context */ typedef struct APEContext { AVClass *class; ///< class for AVOptions AVCodecContext *avctx; BswapDSPContext bdsp; LLAudDSPContext adsp; int channels; int samples; ///< samples left to decode in current frame int bps; int fileversion; ///< codec version, very important in decoding process int compression_level; ///< compression levels int fset; ///< which filter set to use (calculated from compression level) int flags; ///< global decoder flags uint32_t CRC; ///< frame CRC int frameflags; ///< frame flags APEPredictor predictor; ///< predictor used for final reconstruction int32_t *decoded_buffer; int decoded_size; int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel int blocks_per_loop; ///< maximum number of samples to decode for each call int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory APERangecoder rc; ///< rangecoder used to decode actual values APERice riceX; ///< rice code parameters for the second channel APERice riceY; ///< rice code parameters for the first channel APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction GetBitContext gb; uint8_t *data; ///< current frame data uint8_t *data_end; ///< frame data end int data_size; ///< frame data allocated size const uint8_t *ptr; ///< current position in frame data int error; void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode); void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode); void (*predictor_decode_mono)(struct APEContext *ctx, int count); void (*predictor_decode_stereo)(struct APEContext *ctx, int count); } APEContext; static void ape_apply_filters(APEContext *ctx, int32_t *decoded0, int32_t *decoded1, int count); static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode); static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode); static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode); static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode); static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode); static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode); static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode); static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode); static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode); static void predictor_decode_mono_3800(APEContext *ctx, int count); static void predictor_decode_stereo_3800(APEContext *ctx, int count); static void predictor_decode_mono_3930(APEContext *ctx, int count); static void predictor_decode_stereo_3930(APEContext *ctx, int count); static void predictor_decode_mono_3950(APEContext *ctx, int count); static void predictor_decode_stereo_3950(APEContext *ctx, int count); static av_cold int ape_decode_close(AVCodecContext *avctx) { APEContext *s = avctx->priv_data; int i; for (i = 0; i < APE_FILTER_LEVELS; i++) av_freep(&s->filterbuf[i]); av_freep(&s->decoded_buffer); av_freep(&s->data); s->decoded_size = s->data_size = 0; return 0; } static av_cold int ape_decode_init(AVCodecContext *avctx) { APEContext *s = avctx->priv_data; int i; if (avctx->extradata_size != 6) { av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n"); return AVERROR(EINVAL); } if (avctx->channels > 2) { av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n"); return AVERROR(EINVAL); } s->bps = avctx->bits_per_coded_sample; switch (s->bps) { case 8: avctx->sample_fmt = AV_SAMPLE_FMT_U8P; break; case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16P; break; case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32P; break; default: avpriv_request_sample(avctx, "%d bits per coded sample", s->bps); return AVERROR_PATCHWELCOME; } s->avctx = avctx; s->channels = avctx->channels; s->fileversion = AV_RL16(avctx->extradata); s->compression_level = AV_RL16(avctx->extradata + 2); s->flags = AV_RL16(avctx->extradata + 4); av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags); if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE || !s->compression_level || (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) { av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level); return AVERROR_INVALIDDATA; } s->fset = s->compression_level / 1000 - 1; for (i = 0; i < APE_FILTER_LEVELS; i++) { if (!ape_filter_orders[s->fset][i]) break; FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i], (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4, filter_alloc_fail); } if (s->fileversion < 3860) { s->entropy_decode_mono = entropy_decode_mono_0000; s->entropy_decode_stereo = entropy_decode_stereo_0000; } else if (s->fileversion < 3900) { s->entropy_decode_mono = entropy_decode_mono_3860; s->entropy_decode_stereo = entropy_decode_stereo_3860; } else if (s->fileversion < 3930) { s->entropy_decode_mono = entropy_decode_mono_3900; s->entropy_decode_stereo = entropy_decode_stereo_3900; } else if (s->fileversion < 3990) { s->entropy_decode_mono = entropy_decode_mono_3900; s->entropy_decode_stereo = entropy_decode_stereo_3930; } else { s->entropy_decode_mono = entropy_decode_mono_3990; s->entropy_decode_stereo = entropy_decode_stereo_3990; } if (s->fileversion < 3930) { s->predictor_decode_mono = predictor_decode_mono_3800; s->predictor_decode_stereo = predictor_decode_stereo_3800; } else if (s->fileversion < 3950) { s->predictor_decode_mono = predictor_decode_mono_3930; s->predictor_decode_stereo = predictor_decode_stereo_3930; } else { s->predictor_decode_mono = predictor_decode_mono_3950; s->predictor_decode_stereo = predictor_decode_stereo_3950; } ff_bswapdsp_init(&s->bdsp); ff_llauddsp_init(&s->adsp); avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO; return 0; filter_alloc_fail: ape_decode_close(avctx); return AVERROR(ENOMEM); } /** * @name APE range decoding functions * @{ */ #define CODE_BITS 32 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1)) #define SHIFT_BITS (CODE_BITS - 9) #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1) #define BOTTOM_VALUE (TOP_VALUE >> 8) /** Start the decoder */ static inline void range_start_decoding(APEContext *ctx) { ctx->rc.buffer = bytestream_get_byte(&ctx->ptr); ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS); ctx->rc.range = (uint32_t) 1 << EXTRA_BITS; } /** Perform normalization */ static inline void range_dec_normalize(APEContext *ctx) { while (ctx->rc.range <= BOTTOM_VALUE) { ctx->rc.buffer <<= 8; if(ctx->ptr < ctx->data_end) { ctx->rc.buffer += *ctx->ptr; ctx->ptr++; } else { ctx->error = 1; } ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF); ctx->rc.range <<= 8; } } /** * Calculate cumulative frequency for next symbol. Does NO update! * @param ctx decoder context * @param tot_f is the total frequency or (code_value)1<<shift * @return the cumulative frequency */ static inline int range_decode_culfreq(APEContext *ctx, int tot_f) { range_dec_normalize(ctx); ctx->rc.help = ctx->rc.range / tot_f; return ctx->rc.low / ctx->rc.help; } /** * Decode value with given size in bits * @param ctx decoder context * @param shift number of bits to decode */ static inline int range_decode_culshift(APEContext *ctx, int shift) { range_dec_normalize(ctx); ctx->rc.help = ctx->rc.range >> shift; return ctx->rc.low / ctx->rc.help; } /** * Update decoding state * @param ctx decoder context * @param sy_f the interval length (frequency of the symbol) * @param lt_f the lower end (frequency sum of < symbols) */ static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f) { ctx->rc.low -= ctx->rc.help * lt_f; ctx->rc.range = ctx->rc.help * sy_f; } /** Decode n bits (n <= 16) without modelling */ static inline int range_decode_bits(APEContext *ctx, int n) { int sym = range_decode_culshift(ctx, n); range_decode_update(ctx, 1, sym); return sym; } #define MODEL_ELEMENTS 64 /** * Fixed probabilities for symbols in Monkey Audio version 3.97 */ static const uint16_t counts_3970[22] = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, }; /** * Probability ranges for symbols in Monkey Audio version 3.97 */ static const uint16_t counts_diff_3970[21] = { 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756, 1104, 677, 415, 248, 150, 89, 54, 31, 19, 11, 7, 4, 2, }; /** * Fixed probabilities for symbols in Monkey Audio version 3.98 */ static const uint16_t counts_3980[22] = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, }; /** * Probability ranges for symbols in Monkey Audio version 3.98 */ static const uint16_t counts_diff_3980[21] = { 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536, 261, 119, 65, 31, 19, 10, 6, 3, 3, 2, 1, 1, 1, }; /** * Decode symbol * @param ctx decoder context * @param counts probability range start position * @param counts_diff probability range widths */ static inline int range_get_symbol(APEContext *ctx, const uint16_t counts[], const uint16_t counts_diff[]) { int symbol, cf; cf = range_decode_culshift(ctx, 16); if(cf > 65492){ symbol= cf - 65535 + 63; range_decode_update(ctx, 1, cf); if(cf > 65535) ctx->error=1; return symbol; } /* figure out the symbol inefficiently; a binary search would be much better */ for (symbol = 0; counts[symbol + 1] <= cf; symbol++); range_decode_update(ctx, counts_diff[symbol], counts[symbol]); return symbol; } /** @} */ // group rangecoder static inline void update_rice(APERice *rice, unsigned int x) { int lim = rice->k ? (1 << (rice->k + 4)) : 0; rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5); if (rice->ksum < lim) rice->k--; else if (rice->ksum >= (1 << (rice->k + 5))) rice->k++; } static inline int get_rice_ook(GetBitContext *gb, int k) { unsigned int x; x = get_unary(gb, 1, get_bits_left(gb)); if (k) x = (x << k) | get_bits(gb, k); return x; } static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb, APERice *rice) { unsigned int x, overflow; overflow = get_unary(gb, 1, get_bits_left(gb)); if (ctx->fileversion > 3880) { while (overflow >= 16) { overflow -= 16; rice->k += 4; } } if (!rice->k) x = overflow; else if(rice->k <= MIN_CACHE_BITS) { x = (overflow << rice->k) + get_bits(gb, rice->k); } else { av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k); return AVERROR_INVALIDDATA; } rice->ksum += x - (rice->ksum + 8 >> 4); if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0)) rice->k--; else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24) rice->k++; /* Convert to signed */ return ((x >> 1) ^ ((x & 1) - 1)) + 1; } static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice) { unsigned int x, overflow; int tmpk; overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970); if (overflow == (MODEL_ELEMENTS - 1)) { tmpk = range_decode_bits(ctx, 5); overflow = 0; } else tmpk = (rice->k < 1) ? 0 : rice->k - 1; if (tmpk <= 16 || ctx->fileversion < 3910) { if (tmpk > 23) { av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk); return AVERROR_INVALIDDATA; } x = range_decode_bits(ctx, tmpk); } else if (tmpk <= 31) { x = range_decode_bits(ctx, 16); x |= (range_decode_bits(ctx, tmpk - 16) << 16); } else { av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk); return AVERROR_INVALIDDATA; } x += overflow << tmpk; update_rice(rice, x); /* Convert to signed */ return ((x >> 1) ^ ((x & 1) - 1)) + 1; } static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice) { unsigned int x, overflow; int base, pivot; pivot = rice->ksum >> 5; if (pivot == 0) pivot = 1; overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980); if (overflow == (MODEL_ELEMENTS - 1)) { overflow = range_decode_bits(ctx, 16) << 16; overflow |= range_decode_bits(ctx, 16); } if (pivot < 0x10000) { base = range_decode_culfreq(ctx, pivot); range_decode_update(ctx, 1, base); } else { int base_hi = pivot, base_lo; int bbits = 0; while (base_hi & ~0xFFFF) { base_hi >>= 1; bbits++; } base_hi = range_decode_culfreq(ctx, base_hi + 1); range_decode_update(ctx, 1, base_hi); base_lo = range_decode_culfreq(ctx, 1 << bbits); range_decode_update(ctx, 1, base_lo); base = (base_hi << bbits) + base_lo; } x = base + overflow * pivot; update_rice(rice, x); /* Convert to signed */ return ((x >> 1) ^ ((x & 1) - 1)) + 1; } static void decode_array_0000(APEContext *ctx, GetBitContext *gb, int32_t *out, APERice *rice, int blockstodecode) { int i; int ksummax, ksummin; rice->ksum = 0; for (i = 0; i < FFMIN(blockstodecode, 5); i++) { out[i] = get_rice_ook(&ctx->gb, 10); rice->ksum += out[i]; } rice->k = av_log2(rice->ksum / 10) + 1; if (rice->k >= 24) return; for (; i < FFMIN(blockstodecode, 64); i++) { out[i] = get_rice_ook(&ctx->gb, rice->k); rice->ksum += out[i]; rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1; if (rice->k >= 24) return; } ksummax = 1 << rice->k + 7; ksummin = rice->k ? (1 << rice->k + 6) : 0; for (; i < blockstodecode; i++) { out[i] = get_rice_ook(&ctx->gb, rice->k); rice->ksum += out[i] - out[i - 64]; while (rice->ksum < ksummin) { rice->k--; ksummin = rice->k ? ksummin >> 1 : 0; ksummax >>= 1; } while (rice->ksum >= ksummax) { rice->k++; if (rice->k > 24) return; ksummax <<= 1; ksummin = ksummin ? ksummin << 1 : 128; } } for (i = 0; i < blockstodecode; i++) out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1; } static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode) { decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY, blockstodecode); } static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode) { decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY, blockstodecode); decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX, blockstodecode); } static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; while (blockstodecode--) *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY); } static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; int blocks = blockstodecode; while (blockstodecode--) *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY); while (blocks--) *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX); } static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; while (blockstodecode--) *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY); } static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; int blocks = blockstodecode; while (blockstodecode--) *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY); range_dec_normalize(ctx); // because of some implementation peculiarities we need to backpedal here ctx->ptr -= 1; range_start_decoding(ctx); while (blocks--) *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX); } static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; while (blockstodecode--) { *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY); *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX); } } static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; while (blockstodecode--) *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY); } static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode) { int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; while (blockstodecode--) { *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY); *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX); } } static int init_entropy_decoder(APEContext *ctx) { /* Read the CRC */ if (ctx->fileversion >= 3900) { if (ctx->data_end - ctx->ptr < 6) return AVERROR_INVALIDDATA; ctx->CRC = bytestream_get_be32(&ctx->ptr); } else { ctx->CRC = get_bits_long(&ctx->gb, 32); } /* Read the frame flags if they exist */ ctx->frameflags = 0; if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) { ctx->CRC &= ~0x80000000; if (ctx->data_end - ctx->ptr < 6) return AVERROR_INVALIDDATA; ctx->frameflags = bytestream_get_be32(&ctx->ptr); } /* Initialize the rice structs */ ctx->riceX.k = 10; ctx->riceX.ksum = (1 << ctx->riceX.k) * 16; ctx->riceY.k = 10; ctx->riceY.ksum = (1 << ctx->riceY.k) * 16; if (ctx->fileversion >= 3900) { /* The first 8 bits of input are ignored. */ ctx->ptr++; range_start_decoding(ctx); } return 0; } static const int32_t initial_coeffs_fast_3320[1] = { 375, }; static const int32_t initial_coeffs_a_3800[3] = { 64, 115, 64, }; static const int32_t initial_coeffs_b_3800[2] = { 740, 0 }; static const int32_t initial_coeffs_3930[4] = { 360, 317, -109, 98 }; static void init_predictor_decoder(APEContext *ctx) { APEPredictor *p = &ctx->predictor; /* Zero the history buffers */ memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; /* Initialize and zero the coefficients */ if (ctx->fileversion < 3930) { if (ctx->compression_level == COMPRESSION_LEVEL_FAST) { memcpy(p->coeffsA[0], initial_coeffs_fast_3320, sizeof(initial_coeffs_fast_3320)); memcpy(p->coeffsA[1], initial_coeffs_fast_3320, sizeof(initial_coeffs_fast_3320)); } else { memcpy(p->coeffsA[0], initial_coeffs_a_3800, sizeof(initial_coeffs_a_3800)); memcpy(p->coeffsA[1], initial_coeffs_a_3800, sizeof(initial_coeffs_a_3800)); } } else { memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930)); memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930)); } memset(p->coeffsB, 0, sizeof(p->coeffsB)); if (ctx->fileversion < 3930) { memcpy(p->coeffsB[0], initial_coeffs_b_3800, sizeof(initial_coeffs_b_3800)); memcpy(p->coeffsB[1], initial_coeffs_b_3800, sizeof(initial_coeffs_b_3800)); } p->filterA[0] = p->filterA[1] = 0; p->filterB[0] = p->filterB[1] = 0; p->lastA[0] = p->lastA[1] = 0; p->sample_pos = 0; } /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */ static inline int APESIGN(int32_t x) { return (x < 0) - (x > 0); } static av_always_inline int filter_fast_3320(APEPredictor *p, const int decoded, const int filter, const int delayA) { int32_t predictionA; p->buf[delayA] = p->lastA[filter]; if (p->sample_pos < 3) { p->lastA[filter] = decoded; p->filterA[filter] = decoded; return decoded; } predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1]; p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9); if ((decoded ^ predictionA) > 0) p->coeffsA[filter][0]++; else p->coeffsA[filter][0]--; p->filterA[filter] += p->lastA[filter]; return p->filterA[filter]; } static av_always_inline int filter_3800(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int start, const int shift) { int32_t predictionA, predictionB, sign; int32_t d0, d1, d2, d3, d4; p->buf[delayA] = p->lastA[filter]; p->buf[delayB] = p->filterB[filter]; if (p->sample_pos < start) { predictionA = decoded + p->filterA[filter]; p->lastA[filter] = decoded; p->filterB[filter] = decoded; p->filterA[filter] = predictionA; return predictionA; } d2 = p->buf[delayA]; d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1; d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3); d3 = p->buf[delayB] * 2 - p->buf[delayB - 1]; d4 = p->buf[delayB]; predictionA = d0 * p->coeffsA[filter][0] + d1 * p->coeffsA[filter][1] + d2 * p->coeffsA[filter][2]; sign = APESIGN(decoded); p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign; p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign; p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign; predictionB = d3 * p->coeffsB[filter][0] - d4 * p->coeffsB[filter][1]; p->lastA[filter] = decoded + (predictionA >> 11); sign = APESIGN(p->lastA[filter]); p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign; p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign; p->filterB[filter] = p->lastA[filter] + (predictionB >> shift); p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5); return p->filterA[filter]; } static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length) { int i, j; int32_t dotprod, sign; int32_t coeffs[256], delay[256]; if (order >= length) return; memset(coeffs, 0, order * sizeof(*coeffs)); for (i = 0; i < order; i++) delay[i] = buffer[i]; for (i = order; i < length; i++) { dotprod = 0; sign = APESIGN(buffer[i]); for (j = 0; j < order; j++) { dotprod += delay[j] * coeffs[j]; coeffs[j] += ((delay[j] >> 31) | 1) * sign; } buffer[i] -= dotprod >> shift; for (j = 0; j < order - 1; j++) delay[j] = delay[j + 1]; delay[order - 1] = buffer[i]; } } static void long_filter_ehigh_3830(int32_t *buffer, int length) { int i, j; int32_t dotprod, sign; int32_t coeffs[8] = { 0 }, delay[8] = { 0 }; for (i = 0; i < length; i++) { dotprod = 0; sign = APESIGN(buffer[i]); for (j = 7; j >= 0; j--) { dotprod += delay[j] * coeffs[j]; coeffs[j] += ((delay[j] >> 31) | 1) * sign; } for (j = 7; j > 0; j--) delay[j] = delay[j - 1]; delay[0] = buffer[i]; buffer[i] -= dotprod >> 9; } } static void predictor_decode_stereo_3800(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; int start = 4, shift = 10; if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) { start = 16; long_filter_high_3800(decoded0, 16, 9, count); long_filter_high_3800(decoded1, 16, 9, count); } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) { int order = 128, shift2 = 11; if (ctx->fileversion >= 3830) { order <<= 1; shift++; shift2++; long_filter_ehigh_3830(decoded0 + order, count - order); long_filter_ehigh_3830(decoded1 + order, count - order); } start = order; long_filter_high_3800(decoded0, order, shift2, count); long_filter_high_3800(decoded1, order, shift2, count); } while (count--) { int X = *decoded0, Y = *decoded1; if (ctx->compression_level == COMPRESSION_LEVEL_FAST) { *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA); decoded0++; *decoded1 = filter_fast_3320(p, X, 1, XDELAYA); decoded1++; } else { *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB, start, shift); decoded0++; *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB, start, shift); decoded1++; } /* Combined */ p->buf++; p->sample_pos++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } static void predictor_decode_mono_3800(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; int start = 4, shift = 10; if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) { start = 16; long_filter_high_3800(decoded0, 16, 9, count); } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) { int order = 128, shift2 = 11; if (ctx->fileversion >= 3830) { order <<= 1; shift++; shift2++; long_filter_ehigh_3830(decoded0 + order, count - order); } start = order; long_filter_high_3800(decoded0, order, shift2, count); } while (count--) { if (ctx->compression_level == COMPRESSION_LEVEL_FAST) { *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA); decoded0++; } else { *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB, start, shift); decoded0++; } /* Combined */ p->buf++; p->sample_pos++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } static av_always_inline int predictor_update_3930(APEPredictor *p, const int decoded, const int filter, const int delayA) { int32_t predictionA, sign; int32_t d0, d1, d2, d3; p->buf[delayA] = p->lastA[filter]; d0 = p->buf[delayA ]; d1 = p->buf[delayA ] - p->buf[delayA - 1]; d2 = p->buf[delayA - 1] - p->buf[delayA - 2]; d3 = p->buf[delayA - 2] - p->buf[delayA - 3]; predictionA = d0 * p->coeffsA[filter][0] + d1 * p->coeffsA[filter][1] + d2 * p->coeffsA[filter][2] + d3 * p->coeffsA[filter][3]; p->lastA[filter] = decoded + (predictionA >> 9); p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5); sign = APESIGN(decoded); p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign; p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign; p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign; p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign; return p->filterA[filter]; } static void predictor_decode_stereo_3930(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count); while (count--) { /* Predictor Y */ int Y = *decoded1, X = *decoded0; *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA); decoded0++; *decoded1 = predictor_update_3930(p, X, 1, XDELAYA); decoded1++; /* Combined */ p->buf++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } static void predictor_decode_mono_3930(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; ape_apply_filters(ctx, ctx->decoded[0], NULL, count); while (count--) { *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA); decoded0++; p->buf++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } static av_always_inline int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB) { int32_t predictionA, predictionB, sign; p->buf[delayA] = p->lastA[filter]; p->buf[adaptA] = APESIGN(p->buf[delayA]); p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1]; p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]); predictionA = p->buf[delayA ] * p->coeffsA[filter][0] + p->buf[delayA - 1] * p->coeffsA[filter][1] + p->buf[delayA - 2] * p->coeffsA[filter][2] + p->buf[delayA - 3] * p->coeffsA[filter][3]; /* Apply a scaled first-order filter compression */ p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5); p->buf[adaptB] = APESIGN(p->buf[delayB]); p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1]; p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]); p->filterB[filter] = p->filterA[filter ^ 1]; predictionB = p->buf[delayB ] * p->coeffsB[filter][0] + p->buf[delayB - 1] * p->coeffsB[filter][1] + p->buf[delayB - 2] * p->coeffsB[filter][2] + p->buf[delayB - 3] * p->coeffsB[filter][3] + p->buf[delayB - 4] * p->coeffsB[filter][4]; p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10); p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5); sign = APESIGN(decoded); p->coeffsA[filter][0] += p->buf[adaptA ] * sign; p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign; p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign; p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign; p->coeffsB[filter][0] += p->buf[adaptB ] * sign; p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign; p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign; p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign; p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign; return p->filterA[filter]; } static void predictor_decode_stereo_3950(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count); while (count--) { /* Predictor Y */ *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB); decoded0++; *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB); decoded1++; /* Combined */ p->buf++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } } } static void predictor_decode_mono_3950(APEContext *ctx, int count) { APEPredictor *p = &ctx->predictor; int32_t *decoded0 = ctx->decoded[0]; int32_t predictionA, currentA, A, sign; ape_apply_filters(ctx, ctx->decoded[0], NULL, count); currentA = p->lastA[0]; while (count--) { A = *decoded0; p->buf[YDELAYA] = currentA; p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1]; predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] + p->buf[YDELAYA - 1] * p->coeffsA[0][1] + p->buf[YDELAYA - 2] * p->coeffsA[0][2] + p->buf[YDELAYA - 3] * p->coeffsA[0][3]; currentA = A + (predictionA >> 10); p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]); p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]); sign = APESIGN(A); p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign; p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign; p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign; p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign; p->buf++; /* Have we filled the history buffer? */ if (p->buf == p->historybuffer + HISTORY_SIZE) { memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; } p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5); *(decoded0++) = p->filterA[0]; } p->lastA[0] = currentA; } static void do_init_filter(APEFilter *f, int16_t *buf, int order) { f->coeffs = buf; f->historybuffer = buf + order; f->delay = f->historybuffer + order * 2; f->adaptcoeffs = f->historybuffer + order; memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer)); memset(f->coeffs, 0, order * sizeof(*f->coeffs)); f->avg = 0; } static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order) { do_init_filter(&f[0], buf, order); do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order); } static void do_apply_filter(APEContext *ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits) { int res; int absres; while (count--) { /* round fixedpoint scalar product */ res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order, f->adaptcoeffs - order, order, APESIGN(*data)); res = (res + (1 << (fracbits - 1))) >> fracbits; res += *data; *data++ = res; /* Update the output history */ *f->delay++ = av_clip_int16(res); if (version < 3980) { /* Version ??? to < 3.98 files (untested) */ f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4; f->adaptcoeffs[-4] >>= 1; f->adaptcoeffs[-8] >>= 1; } else { /* Version 3.98 and later files */ /* Update the adaption coefficients */ absres = FFABS(res); if (absres) *f->adaptcoeffs = APESIGN(res) * (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3))); /* equivalent to the following code if (absres <= f->avg * 4 / 3) *f->adaptcoeffs = APESIGN(res) * 8; else if (absres <= f->avg * 3) *f->adaptcoeffs = APESIGN(res) * 16; else *f->adaptcoeffs = APESIGN(res) * 32; */ else *f->adaptcoeffs = 0; f->avg += (absres - f->avg) / 16; f->adaptcoeffs[-1] >>= 1; f->adaptcoeffs[-2] >>= 1; f->adaptcoeffs[-8] >>= 1; } f->adaptcoeffs++; /* Have we filled the history buffer? */ if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) { memmove(f->historybuffer, f->delay - (order * 2), (order * 2) * sizeof(*f->historybuffer)); f->delay = f->historybuffer + order * 2; f->adaptcoeffs = f->historybuffer + order; } } } static void apply_filter(APEContext *ctx, APEFilter *f, int32_t *data0, int32_t *data1, int count, int order, int fracbits) { do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits); if (data1) do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits); } static void ape_apply_filters(APEContext *ctx, int32_t *decoded0, int32_t *decoded1, int count) { int i; for (i = 0; i < APE_FILTER_LEVELS; i++) { if (!ape_filter_orders[ctx->fset][i]) break; apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]); } } static int init_frame_decoder(APEContext *ctx) { int i, ret; if ((ret = init_entropy_decoder(ctx)) < 0) return ret; init_predictor_decoder(ctx); for (i = 0; i < APE_FILTER_LEVELS; i++) { if (!ape_filter_orders[ctx->fset][i]) break; init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]); } return 0; } static void ape_unpack_mono(APEContext *ctx, int count) { if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) { /* We are pure silence, so we're done. */ av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n"); return; } ctx->entropy_decode_mono(ctx, count); /* Now apply the predictor decoding */ ctx->predictor_decode_mono(ctx, count); /* Pseudo-stereo - just copy left channel to right channel */ if (ctx->channels == 2) { memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1])); } } static void ape_unpack_stereo(APEContext *ctx, int count) { int32_t left, right; int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) { /* We are pure silence, so we're done. */ av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n"); return; } ctx->entropy_decode_stereo(ctx, count); /* Now apply the predictor decoding */ ctx->predictor_decode_stereo(ctx, count); /* Decorrelate and scale to output depth */ while (count--) { left = *decoded1 - (*decoded0 / 2); right = left + *decoded0; *(decoded0++) = left; *(decoded1++) = right; } } static int ape_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; const uint8_t *buf = avpkt->data; APEContext *s = avctx->priv_data; uint8_t *sample8; int16_t *sample16; int32_t *sample24; int i, ch, ret; int blockstodecode; uint64_t decoded_buffer_size; /* this should never be negative, but bad things will happen if it is, so check it just to make sure. */ av_assert0(s->samples >= 0); if(!s->samples){ uint32_t nblocks, offset; int buf_size; if (!avpkt->size) { *got_frame_ptr = 0; return 0; } if (avpkt->size < 8) { av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); return AVERROR_INVALIDDATA; } buf_size = avpkt->size & ~3; if (buf_size != avpkt->size) { av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. " "extra bytes at the end will be skipped.\n"); } if (s->fileversion < 3950) // previous versions overread two bytes buf_size += 2; av_fast_padded_malloc(&s->data, &s->data_size, buf_size); if (!s->data) return AVERROR(ENOMEM); s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf, buf_size >> 2); memset(s->data + (buf_size & ~3), 0, buf_size & 3); s->ptr = s->data; s->data_end = s->data + buf_size; nblocks = bytestream_get_be32(&s->ptr); offset = bytestream_get_be32(&s->ptr); if (s->fileversion >= 3900) { if (offset > 3) { av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n"); s->data = NULL; return AVERROR_INVALIDDATA; } if (s->data_end - s->ptr < offset) { av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); return AVERROR_INVALIDDATA; } s->ptr += offset; } else { if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0) return ret; if (s->fileversion > 3800) skip_bits_long(&s->gb, offset * 8); else skip_bits_long(&s->gb, offset); } if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) { av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n", nblocks); return AVERROR_INVALIDDATA; } /* Initialize the frame decoder */ if (init_frame_decoder(s) < 0) { av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n"); return AVERROR_INVALIDDATA; } s->samples = nblocks; } if (!s->data) { *got_frame_ptr = 0; return avpkt->size; } blockstodecode = FFMIN(s->blocks_per_loop, s->samples); // for old files coefficients were not interleaved, // so we need to decode all of them at once if (s->fileversion < 3930) blockstodecode = s->samples; /* reallocate decoded sample buffer if needed */ decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer); av_assert0(decoded_buffer_size <= INT_MAX); av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size); if (!s->decoded_buffer) return AVERROR(ENOMEM); memset(s->decoded_buffer, 0, s->decoded_size); s->decoded[0] = s->decoded_buffer; s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8); /* get output buffer */ frame->nb_samples = blockstodecode; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; s->error=0; if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO)) ape_unpack_mono(s, blockstodecode); else ape_unpack_stereo(s, blockstodecode); emms_c(); if (s->error) { s->samples=0; av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n"); return AVERROR_INVALIDDATA; } switch (s->bps) { case 8: for (ch = 0; ch < s->channels; ch++) { sample8 = (uint8_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff; } break; case 16: for (ch = 0; ch < s->channels; ch++) { sample16 = (int16_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample16++ = s->decoded[ch][i]; } break; case 24: for (ch = 0; ch < s->channels; ch++) { sample24 = (int32_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample24++ = s->decoded[ch][i] << 8; } break; } s->samples -= blockstodecode; *got_frame_ptr = 1; return !s->samples ? avpkt->size : 0; } static void ape_flush(AVCodecContext *avctx) { APEContext *s = avctx->priv_data; s->samples= 0; } #define OFFSET(x) offsetof(APEContext, x) #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM) static const AVOption options[] = { { "max_samples", "maximum number of samples decoded per call", OFFSET(blocks_per_loop), AV_OPT_TYPE_INT, { .i64 = 4608 }, 1, INT_MAX, PAR, "max_samples" }, { "all", "no maximum. decode all samples for each packet at once", 0, AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" }, { NULL}, }; static const AVClass ape_decoder_class = { .class_name = "APE decoder", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_ape_decoder = { .name = "ape", .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"), .type = AVMEDIA_TYPE_AUDIO, .id = AV_CODEC_ID_APE, .priv_data_size = sizeof(APEContext), .init = ape_decode_init, .close = ape_decode_close, .decode = ape_decode_frame, .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1, .flush = ape_flush, .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S32P, AV_SAMPLE_FMT_NONE }, .priv_class = &ape_decoder_class, };
./CrossVul/dataset_final_sorted/CWE-125/c/good_2572_0
crossvul-cpp_data_good_2900_0
/* radare - LGPL - Copyright 2009-2017 - pancake, nibble, dso */ // TODO: dlopen library and show address #include <r_bin.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_io.h> #include <config.h> R_LIB_VERSION (r_bin); #define bprintf if(binfile->rbin->verbose)eprintf #define DB a->sdb; #define RBINLISTFREE(x)\ if (x) { \ r_list_free (x);\ x = NULL;\ } #define REBASE_PADDR(o, l, type_t)\ do { \ RListIter *_it;\ type_t *_el;\ r_list_foreach ((l), _it, _el) { \ _el->paddr += (o)->loadaddr;\ }\ } while (0) #define ARCHS_KEY "archs" #if !defined(R_BIN_STATIC_PLUGINS) #define R_BIN_STATIC_PLUGINS 0 #endif #if !defined(R_BIN_XTR_STATIC_PLUGINS) #define R_BIN_XTR_STATIC_PLUGINS 0 #endif static RBinPlugin *bin_static_plugins[] = { R_BIN_STATIC_PLUGINS, NULL }; static RBinXtrPlugin *bin_xtr_static_plugins[] = { R_BIN_XTR_STATIC_PLUGINS, NULL }; static int is_data_section(RBinFile *a, RBinSection *s); static RList *get_strings(RBinFile *a, int min, int dump); static void r_bin_object_delete_items(RBinObject *o); static void r_bin_object_free(void /*RBinObject*/ *o_); // static int r_bin_object_set_items(RBinFile *binfile, RBinObject *o); static int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr); //static int remove_bin_file_by_binfile (RBin *bin, RBinFile * binfile); //static void r_bin_free_bin_files (RBin *bin); static void r_bin_file_free(void /*RBinFile*/ *bf_); static RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr); static RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr); int r_bin_load_io_at_offset_as_sz(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name, ut64 sz); static RBinPlugin *r_bin_get_binplugin_by_name(RBin *bin, const char *name); static RBinXtrPlugin *r_bin_get_xtrplugin_by_name(RBin *bin, const char *name); static RBinPlugin *r_bin_get_binplugin_any(RBin *bin); static RBinObject *r_bin_object_new(RBinFile *binfile, RBinPlugin *plugin, ut64 baseaddr, ut64 loadaddr, ut64 offset, ut64 sz); static RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr); static RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr); static int getoffset(RBin *bin, int type, int idx) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (plugin && plugin->get_offset) { return plugin->get_offset (a, type, idx); } return -1; } static const char *getname(RBin *bin, int type, int idx) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (plugin && plugin->get_name) { return plugin->get_name (a, type, idx); } return NULL; } static int r_bin_file_object_add(RBinFile *binfile, RBinObject *o) { if (!o) { return false; } r_list_append (binfile->objs, o); r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, o); return true; } static void binobj_set_baddr(RBinObject *o, ut64 baddr) { if (!o || baddr == UT64_MAX) { return; } o->baddr_shift = baddr - o->baddr; } static ut64 binobj_a2b(RBinObject *o, ut64 addr) { return addr + (o? o->baddr_shift: 0); } static void filterStrings (RBin *bin, RList *strings) { RBinString *ptr; RListIter *iter; r_list_foreach (strings, iter, ptr) { char *dec = (char *)r_base64_decode_dyn (ptr->string, -1); if (dec) { char *s = ptr->string; do { char *dec2 = (char *)r_base64_decode_dyn (s, -1); if (!dec2) { break; } if (!r_str_is_printable (dec2)) { free (dec2); break; } free (dec); s = dec = dec2; } while (true); if (r_str_is_printable (dec) && strlen (dec) > 3) { free (ptr->string); ptr->string = dec; ptr->type = R_STRING_TYPE_BASE64; } else { free (dec); } } } } R_API void r_bin_iobind(RBin *bin, RIO *io) { r_io_bind (io, &bin->iob); } // TODO: move these two function do a different file R_API RBinXtrData *r_bin_xtrdata_new(RBuffer *buf, ut64 offset, ut64 size, ut32 file_count, RBinXtrMetadata *metadata) { RBinXtrData *data = R_NEW0 (RBinXtrData); if (!data) { return NULL; } data->offset = offset; data->size = size; data->file_count = file_count; data->metadata = metadata; data->loaded = 0; data->buffer = malloc (size + 1); // data->laddr = 0; /// XXX if (!data->buffer) { free (data); return NULL; } memcpy (data->buffer, r_buf_buffer (buf), size); data->buffer[size] = 0; return data; } R_API const char *r_bin_string_type (int type) { switch (type) { case 'a': return "ascii"; case 'u': return "utf8"; case 'w': return "utf16le"; case 'W': return "utf32le"; case 'b': return "base64"; } return "ascii"; // XXX } R_API void r_bin_xtrdata_free(void /*RBinXtrData*/ *data_) { RBinXtrData *data = data_; if (data) { if (data->metadata) { free (data->metadata->libname); free (data->metadata->arch); free (data->metadata->machine); free (data->metadata); } free (data->file); free (data->buffer); free (data); } } R_API RBinObject *r_bin_file_object_get_cur(RBinFile *binfile) { return binfile? binfile->o: NULL; } R_API RBinObject *r_bin_object_get_cur(RBin *bin) { return bin ? r_bin_file_object_get_cur (r_bin_cur (bin)) : NULL; } R_API RBinPlugin *r_bin_file_cur_plugin(RBinFile *binfile) { return binfile && binfile->o? binfile->o->plugin: NULL; } R_API int r_bin_file_cur_set_plugin(RBinFile *binfile, RBinPlugin *plugin) { if (binfile && binfile->o) { binfile->o->plugin = plugin; return true; } return false; } // maybe too big sometimes? 2KB of stack eaten here.. #define R_STRING_SCAN_BUFFER_SIZE 2048 static int string_scan_range(RList *list, const ut8 *buf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (!buf || !min) { return -1; } while (needle < to) { rc = r_utf8_decode (buf + needle, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc; if ((to - needle) > 4) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r)) { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\e", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 28) { tmp[i + 0] = '\\'; tmp[i + 1] = " abtnvfr e"[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } if (list) { RBinString *new = R_NEW0 (RBinString); if (!new) { break; } new->type = str_type; new->length = runes; new->size = needle - str_start; new->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start > 1) { const ut8 *p = buf + str_start - 2; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start > 3) { const ut8 *p = buf + str_start - 4; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } new->paddr = new->vaddr = str_start; new->string = r_str_ndup ((const char *)tmp, i); r_list_append (list, new); } else { // DUMP TO STDOUT. raw dumping for rabin2 -zzz printf ("0x%08" PFMT64x " %s\n", str_start, tmp); } } } return count; } static void get_strings_range(RBinFile *arch, RList *list, int min, ut64 from, ut64 to) { RBinPlugin *plugin = r_bin_file_cur_plugin (arch); RBinString *ptr; RListIter *it; if (!arch || !arch->buf || !arch->buf->buf) { return; } if (!arch->rawstr) { if (!plugin || !plugin->info) { return; } } if (!min) { min = plugin? plugin->minstrlen: 4; } /* Some plugins return zero, fix it up */ if (!min) { min = 4; } if (min < 0) { return; } if (!to || to > arch->buf->length) { to = arch->buf->length; } if (arch->rawstr != 2) { ut64 size = to - from; // in case of dump ignore here if (arch->rbin->maxstrbuf && size && size > arch->rbin->maxstrbuf) { if (arch->rbin->verbose) { eprintf ("WARNING: bin_strings buffer is too big " "(0x%08" PFMT64x ")." " Use -zzz or set bin.maxstrbuf " "(RABIN2_MAXSTRBUF) in r2 (rabin2)\n", size); } return; } } if (string_scan_range (list, arch->buf->buf, min, from, to, -1) < 0) { return; } r_list_foreach (list, it, ptr) { RBinSection *s = r_bin_get_section_at (arch->o, ptr->paddr, false); if (s) { ptr->vaddr = s->vaddr + (ptr->paddr - s->paddr); } } } static int is_data_section(RBinFile *a, RBinSection *s) { if (s->has_strings || s->is_data) { return true; } if (s->is_data) { return true; } // Rust return (strstr (s->name, "_const") != NULL); } static RList *get_strings(RBinFile *a, int min, int dump) { RListIter *iter; RBinSection *section; RBinObject *o = a? a->o: NULL; RList *ret; if (!o) { return NULL; } if (dump) { /* dump to stdout, not stored in list */ ret = NULL; } else { ret = r_list_newf (r_bin_string_free); if (!ret) { return NULL; } } if (o->sections && !r_list_empty (o->sections) && !a->rawstr) { r_list_foreach (o->sections, iter, section) { if (is_data_section (a, section)) { get_strings_range (a, ret, min, section->paddr, section->paddr + section->size); } } r_list_foreach (o->sections, iter, section) { RBinString *s; RListIter *iter2; /* load objc/swift strings */ const int bits = (a->o && a->o->info) ? a->o->info->bits : 32; const int cfstr_size = (bits == 64) ? 32 : 16; const int cfstr_offs = (bits == 64) ? 16 : 8; if (strstr (section->name, "__cfstring")) { int i; // XXX do not walk if bin.strings == 0 ut8 *p; for (i = 0; i < section->size; i += cfstr_size) { ut8 buf[32]; if (!r_buf_read_at ( a->buf, section->paddr + i + cfstr_offs, buf, sizeof (buf))) { break; } p = buf; ut64 cfstr_vaddr = section->vaddr + i; ut64 cstr_vaddr = (bits == 64) ? r_read_le64 (p) : r_read_le32 (p); r_list_foreach (ret, iter2, s) { if (s->vaddr == cstr_vaddr) { RBinString *new = R_NEW0 (RBinString); new->type = s->type; new->length = s->length; new->size = s->size; new->ordinal = s->ordinal; new->paddr = new->vaddr = cfstr_vaddr; new->string = r_str_newf ("cstr.%s", s->string); r_list_append (ret, new); break; } } } } } } else { get_strings_range (a, ret, min, 0, a->size); } return ret; } R_API RList* r_bin_raw_strings(RBinFile *a, int min) { RList *l = NULL; if (a) { int tmp = a->rawstr; a->rawstr = 2; l = get_strings (a, min, 0); a->rawstr = tmp; } return l; } R_API int r_bin_dump_strings(RBinFile *a, int min) { get_strings (a, min, 1); return 0; } /* This is very slow if there are lot of symbols */ R_API int r_bin_load_languages(RBinFile *binfile) { if (r_bin_lang_rust (binfile)) { return R_BIN_NM_RUST; } if (r_bin_lang_swift (binfile)) { return R_BIN_NM_SWIFT; } if (r_bin_lang_objc (binfile)) { return R_BIN_NM_OBJC; } if (r_bin_lang_cxx (binfile)) { return R_BIN_NM_CXX; } if (r_bin_lang_dlang (binfile)) { return R_BIN_NM_DLANG; } if (r_bin_lang_msvc (binfile)) { return R_BIN_NM_MSVC; } return R_BIN_NM_NONE; } static void mem_free(void *data) { RBinMem *mem = (RBinMem *)data; if (mem && mem->mirrors) { mem->mirrors->free = mem_free; r_list_free (mem->mirrors); mem->mirrors = NULL; } free (mem); } static void r_bin_object_delete_items(RBinObject *o) { ut32 i = 0; if (!o) { return; } r_list_free (o->entries); r_list_free (o->fields); r_list_free (o->imports); r_list_free (o->libs); r_list_free (o->relocs); r_list_free (o->sections); r_list_free (o->strings); r_list_free (o->symbols); r_list_free (o->classes); r_list_free (o->lines); sdb_free (o->kv); if (o->mem) { o->mem->free = mem_free; } r_list_free (o->mem); o->mem = NULL; o->entries = NULL; o->fields = NULL; o->imports = NULL; o->libs = NULL; o->relocs = NULL; o->sections = NULL; o->strings = NULL; o->symbols = NULL; o->classes = NULL; o->lines = NULL; o->info = NULL; o->kv = NULL; for (i = 0; i < R_BIN_SYM_LAST; i++) { free (o->binsym[i]); o->binsym[i] = NULL; } } R_API void r_bin_info_free(RBinInfo *rb) { if (!rb) { return; } free (rb->intrp); free (rb->file); free (rb->type); free (rb->bclass); free (rb->rclass); free (rb->arch); free (rb->cpu); free (rb->machine); free (rb->os); free (rb->subsystem); free (rb->rpath); free (rb->guid); free (rb->debug_file_name); free (rb); } R_API void r_bin_import_free(void *_imp) { RBinImport *imp = (RBinImport *)_imp; if (imp) { R_FREE (imp->name); R_FREE (imp->classname); R_FREE (imp->descriptor); free (imp); } } R_API void r_bin_symbol_free(void *_sym) { RBinSymbol *sym = (RBinSymbol *)_sym; free (sym->name); free (sym->classname); free (sym); } R_API void r_bin_string_free(void *_str) { RBinString *str = (RBinString *)_str; free (str->string); free (str); } static void r_bin_object_free(void /*RBinObject*/ *o_) { RBinObject *o = o_; if (!o) { return; } r_bin_info_free (o->info); r_bin_object_delete_items (o); R_FREE (o); } static char *swiftField(const char *dn, const char *cn) { char *p = strstr (dn, ".getter_"); if (!p) { p = strstr (dn, ".setter_"); if (!p) { p = strstr (dn, ".method_"); } } if (p) { char *q = strstr (dn, cn); if (q && q[strlen (cn)] == '.') { q = strdup (q + strlen (cn) + 1); char *r = strchr (q, '.'); if (r) { *r = 0; } return q; } } return NULL; } R_API RList *r_bin_classes_from_symbols (RBinFile *bf, RBinObject *o) { RBinSymbol *sym; RListIter *iter; RList *symbols = o->symbols; RList *classes = o->classes; if (!classes) { classes = r_list_newf ((RListFree)r_bin_class_free); } r_list_foreach (symbols, iter, sym) { if (sym->name[0] != '_') { continue; } const char *cn = sym->classname; if (cn) { RBinClass *c = r_bin_class_new (bf, sym->classname, NULL, 0); if (!c) { continue; } // swift specific char *dn = sym->dname; char *fn = swiftField (dn, cn); if (fn) { // eprintf ("FIELD %s %s\n", cn, fn); RBinField *f = r_bin_field_new (sym->paddr, sym->vaddr, sym->size, fn, NULL, NULL); r_list_append (c->fields, f); free (fn); } else { char *mn = strstr (dn, ".."); if (mn) { // eprintf ("META %s %s\n", sym->classname, mn); } else { char *mn = strstr (dn, cn); if (mn && mn[strlen(cn)] == '.') { mn += strlen (cn) + 1; // eprintf ("METHOD %s %s\n", sym->classname, mn); r_list_append (c->methods, sym); } } } } } if (r_list_empty (classes)) { r_list_free (classes); return NULL; } return classes; } // XXX - change this to RBinObject instead of RBinFile // makes no sense to pass in a binfile and set the RBinObject // kinda a clunky functions R_API int r_bin_object_set_items(RBinFile *binfile, RBinObject *o) { RBinObject *old_o; RBinPlugin *cp; int i, minlen; RBin *bin; if (!binfile || !o || !o->plugin) { return false; } bin = binfile->rbin; old_o = binfile->o; cp = o->plugin; if (binfile->rbin->minstrlen > 0) { minlen = binfile->rbin->minstrlen; } else { minlen = cp->minstrlen; } binfile->o = o; if (cp->baddr) { ut64 old_baddr = o->baddr; o->baddr = cp->baddr (binfile); binobj_set_baddr (o, old_baddr); } if (cp->boffset) { o->boffset = cp->boffset (binfile); } // XXX: no way to get info from xtr pluginz? // Note, object size can not be set from here due to potential // inconsistencies if (cp->size) { o->size = cp->size (binfile); } if (cp->binsym) { for (i = 0; i < R_BIN_SYM_LAST; i++) { o->binsym[i] = cp->binsym (binfile, i); if (o->binsym[i]) { o->binsym[i]->paddr += o->loadaddr; } } } if (cp->entries) { o->entries = cp->entries (binfile); REBASE_PADDR (o, o->entries, RBinAddr); } if (cp->fields) { o->fields = cp->fields (binfile); if (o->fields) { o->fields->free = r_bin_field_free; REBASE_PADDR (o, o->fields, RBinField); } } if (cp->imports) { r_list_free (o->imports); o->imports = cp->imports (binfile); if (o->imports) { o->imports->free = r_bin_import_free; } } //if (bin->filter_rules & (R_BIN_REQ_SYMBOLS | R_BIN_REQ_IMPORTS)) { if (true) { if (cp->symbols) { o->symbols = cp->symbols (binfile); if (o->symbols) { o->symbols->free = r_bin_symbol_free; REBASE_PADDR (o, o->symbols, RBinSymbol); if (bin->filter) { r_bin_filter_symbols (o->symbols); } } } } //} o->info = cp->info? cp->info (binfile): NULL; if (cp->libs) { o->libs = cp->libs (binfile); } if (cp->sections) { // XXX sections are populated by call to size if (!o->sections) { o->sections = cp->sections (binfile); } REBASE_PADDR (o, o->sections, RBinSection); if (bin->filter) { r_bin_filter_sections (o->sections); } } if (bin->filter_rules & (R_BIN_REQ_RELOCS | R_BIN_REQ_IMPORTS)) { if (cp->relocs) { o->relocs = cp->relocs (binfile); REBASE_PADDR (o, o->relocs, RBinReloc); } } if (bin->filter_rules & R_BIN_REQ_STRINGS) { if (cp->strings) { o->strings = cp->strings (binfile); } else { o->strings = get_strings (binfile, minlen, 0); } if (bin->debase64) { filterStrings (bin, o->strings); } REBASE_PADDR (o, o->strings, RBinString); } if (bin->filter_rules & R_BIN_REQ_CLASSES) { if (cp->classes) { o->classes = cp->classes (binfile); if (r_bin_lang_swift (binfile)) { o->classes = r_bin_classes_from_symbols (binfile, o); } } else { o->classes = r_bin_classes_from_symbols (binfile, o); } if (bin->filter) { r_bin_filter_classes (o->classes); } } if (cp->lines) { o->lines = cp->lines (binfile); } if (cp->get_sdb) { Sdb* new_kv = cp->get_sdb (binfile); if (new_kv != o->kv) { sdb_free (o->kv); } o->kv = new_kv; } if (cp->mem) { o->mem = cp->mem (binfile); } if (bin->filter_rules & (R_BIN_REQ_SYMBOLS | R_BIN_REQ_IMPORTS)) { o->lang = r_bin_load_languages (binfile); } binfile->o = old_o; return true; } // XXX - this is a rather hacky way to do things, there may need to be a better // way. R_API int r_bin_load(RBin *bin, const char *file, ut64 baseaddr, ut64 loadaddr, int xtr_idx, int fd, int rawstr) { if (!bin) { return false; } // ALIAS? return r_bin_load_as (bin, file, baseaddr, loadaddr, // xtr_idx, fd, rawstr, 0, file); RIOBind *iob = &(bin->iob); if (!iob) { return false; } if (!iob->io) { iob->io = r_io_new (); //wtf if (!iob->io) { return false; } bin->io_owned = true; r_io_bind (iob->io, &bin->iob); //memleak? iob = &bin->iob; } if (!iob->desc_get (iob->io, fd)) { fd = iob->fd_open (iob->io, file, R_IO_READ, 0644); } bin->rawstr = rawstr; // Use the current RIODesc otherwise r_io_map_select can swap them later on if (fd < 0) { r_io_free (iob->io); memset (&bin->iob, 0, sizeof (bin->iob)); bin->io_owned = false; return false; } //Use the current RIODesc otherwise r_io_map_select can swap them later on return r_bin_load_io (bin, fd, baseaddr, loadaddr, xtr_idx); } R_API int r_bin_load_as(RBin *bin, const char *file, ut64 baseaddr, ut64 loadaddr, int xtr_idx, int fd, int rawstr, int fileoffset, const char *name) { RIOBind *iob = &(bin->iob); if (!iob || !iob->io) { return false; } if (fd < 0) { fd = iob->fd_open (iob->io, file, R_IO_READ, 0644); } if (fd < 0) { return false; } return r_bin_load_io_at_offset_as (bin, fd, baseaddr, loadaddr, xtr_idx, fileoffset, name); } R_API int r_bin_reload(RBin *bin, int fd, ut64 baseaddr) { RIOBind *iob = &(bin->iob); RList *the_obj_list = NULL; int res = false; RBinFile *bf = NULL; ut8 *buf_bytes = NULL; ut64 sz = UT64_MAX; if (!iob || !iob->io) { res = false; goto error; } const char *name = iob->fd_get_name (iob->io, fd); bf = r_bin_file_find_by_name (bin, name); if (!bf) { res = false; goto error; } the_obj_list = bf->objs; bf->objs = r_list_newf ((RListFree)r_bin_object_free); // invalidate current object reference bf->o = NULL; sz = iob->fd_size (iob->io, fd); if (sz == UT64_MAX || sz > (64 * 1024 * 1024)) { // too big, probably wrong eprintf ("Too big\n"); res = false; goto error; } if (sz == UT64_MAX && iob->fd_is_dbg (iob->io, fd)) { // attempt a local open and read // This happens when a plugin like debugger does not have a // fixed size. // if there is no fixed size or its MAXED, there is no way to // definitively // load the bin-properly. Many of the plugins require all // content and are not // stream based loaders int tfd = iob->fd_open (iob->io, name, R_IO_READ, 0); if (tfd < 0) { res = false; goto error; } sz = iob->fd_size (iob->io, tfd); if (sz == UT64_MAX) { iob->fd_close (iob->io, tfd); res = false; goto error; } buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { iob->fd_close (iob->io, tfd); res = false; goto error; } if (!iob->read_at (iob->io, 0LL, buf_bytes, sz)) { free (buf_bytes); iob->fd_close (iob->io, tfd); res = false; goto error; } iob->fd_close (iob->io, tfd); } else { buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { res = false; goto error; } if (!iob->fd_read_at (iob->io, fd, 0LL, buf_bytes, sz)) { free (buf_bytes); res = false; goto error; } } bool yes_plz_steal_ptr = true; r_bin_file_set_bytes (bf, buf_bytes, sz, yes_plz_steal_ptr); if (r_list_length (the_obj_list) == 1) { RBinObject *old_o = (RBinObject *)r_list_get_n (the_obj_list, 0); res = r_bin_load_io_at_offset_as (bin, fd, baseaddr, old_o->loadaddr, 0, old_o->boffset, NULL); } else { RListIter *iter = NULL; RBinObject *old_o; r_list_foreach (the_obj_list, iter, old_o) { // XXX - naive. do we need a way to prevent multiple "anys" from being opened? res = r_bin_load_io_at_offset_as (bin, fd, baseaddr, old_o->loadaddr, 0, old_o->boffset, old_o->plugin->name); } } bf->o = r_list_get_n (bf->objs, 0); error: r_list_free (the_obj_list); return res; } R_API int r_bin_load_io(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx) { return r_bin_load_io_at_offset_as (bin, fd, baseaddr, loadaddr, xtr_idx, 0, NULL); } R_API int r_bin_load_io_at_offset_as_sz(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name, ut64 sz) { RIOBind *iob = &(bin->iob); RIO *io = iob? iob->io: NULL; RListIter *it; ut8 *buf_bytes = NULL; RBinXtrPlugin *xtr; ut64 file_sz = UT64_MAX; RBinFile *binfile = NULL; int tfd = -1; if (!io || (fd < 0) || (st64)sz < 0) { return false; } bool is_debugger = iob->fd_is_dbg (io, fd); const char *fname = iob->fd_get_name (io, fd); if (loadaddr == UT64_MAX) { loadaddr = 0; } file_sz = iob->fd_size (io, fd); // file_sz = UT64_MAX happens when attaching to frida:// and other non-debugger io plugins which results in double opening if (is_debugger && file_sz == UT64_MAX) { tfd = iob->fd_open (io, fname, R_IO_READ, 0644); if (tfd >= 1) { file_sz = iob->fd_size (io, tfd); } } if (!sz) { sz = file_sz; } bin->file = fname; sz = R_MIN (file_sz, sz); if (!r_list_length (bin->binfiles)) { if (is_debugger) { //use the temporal RIODesc to read the content of the file instead //from the memory if (tfd >= 0) { buf_bytes = calloc (1, sz + 1); iob->fd_read_at (io, tfd, 0, buf_bytes, sz); // iob->fd_close (io, tfd); } } } if (!buf_bytes) { buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { return false; } ut64 seekaddr = is_debugger? baseaddr: loadaddr; if (!iob->fd_read_at (io, fd, seekaddr, buf_bytes, sz)) { sz = 0LL; } } if (!name && (st64)sz > 0) { // XXX - for the time being this is fine, but we may want to // change the name to something like // <xtr_name>:<bin_type_name> r_list_foreach (bin->binxtrs, it, xtr) { if (xtr && xtr->check_bytes (buf_bytes, sz)) { if (xtr && (xtr->extract_from_bytes || xtr->extractall_from_bytes)) { if (is_debugger && sz != file_sz) { R_FREE (buf_bytes); if (tfd < 0) { tfd = iob->fd_open (io, fname, R_IO_READ, 0); } sz = iob->fd_size (io, tfd); if (sz != UT64_MAX) { buf_bytes = calloc (1, sz + 1); if (buf_bytes) { (void) iob->fd_read_at (io, tfd, 0, buf_bytes, sz); } } //DOUBLECLOSE UAF : iob->fd_close (io, tfd); tfd = -1; // marking it closed } else if (sz != file_sz) { (void) iob->read_at (io, 0LL, buf_bytes, sz); } binfile = r_bin_file_xtr_load_bytes (bin, xtr, fname, buf_bytes, sz, file_sz, baseaddr, loadaddr, xtr_idx, fd, bin->rawstr); } xtr = NULL; } } } if (!binfile) { bool steal_ptr = true; // transfer buf_bytes ownership to binfile binfile = r_bin_file_new_from_bytes ( bin, fname, buf_bytes, sz, file_sz, bin->rawstr, baseaddr, loadaddr, fd, name, NULL, offset, steal_ptr); } return binfile? r_bin_file_set_cur_binfile (bin, binfile): false; } R_API bool r_bin_load_io_at_offset_as(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name) { // adding file_sz to help reduce the performance impact on the system // in this case the number of bytes read will be limited to 2MB // (MIN_LOAD_SIZE) // if it fails, the whole file is loaded. const ut64 MAX_LOAD_SIZE = 0; // 0xfffff; //128 * (1 << 10 << 10); int res = r_bin_load_io_at_offset_as_sz (bin, fd, baseaddr, loadaddr, xtr_idx, offset, name, MAX_LOAD_SIZE); if (!res) { res = r_bin_load_io_at_offset_as_sz (bin, fd, baseaddr, loadaddr, xtr_idx, offset, name, UT64_MAX); } return res; } R_API int r_bin_file_deref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_deref (bin, a); } R_API int r_bin_file_deref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); int res = false; if (a && !o) { //r_list_delete_data (bin->binfiles, a); res = true; } else if (a && o->referenced - 1 < 1) { //r_list_delete_data (bin->binfiles, a); res = true; // not thread safe } else if (o) { o->referenced--; } // it is possible for a file not // to be bound to RBin and RBinFiles // XXX - is this an ok assumption? if (bin) bin->cur = NULL; return res; } R_API int r_bin_file_ref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_ref (bin, a); } R_API int r_bin_file_ref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); if (a && o) { o->referenced--; return true; } return false; } static void r_bin_file_free(void /*RBinFile*/ *bf_) { RBinFile *a = bf_; RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (!a) { return; } // Binary format objects are connected to the // RBinObject, so the plugin must destroy the // format data first if (plugin && plugin->destroy) { plugin->destroy (a); } if (a->curxtr && a->curxtr->destroy && a->xtr_obj) { a->curxtr->free_xtr ((void *)(a->xtr_obj)); } r_buf_free (a->buf); // TODO: unset related sdb namespaces if (a && a->sdb_addrinfo) { sdb_free (a->sdb_addrinfo); a->sdb_addrinfo = NULL; } free (a->file); a->o = NULL; r_list_free (a->objs); r_list_free (a->xtr_data); r_id_pool_kick_id (a->rbin->file_ids, a->id); memset (a, 0, sizeof (RBinFile)); free (a); } static RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr) { RBinFile *bf = r_bin_file_new (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, bin->sdb, steal_ptr); if (bf) { r_list_append (bin->binfiles, bf); } return bf; } // This function populate RBinFile->xtr_data, that information is enough to // create RBinObject when needed using r_bin_file_object_new_from_xtr_data static RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr) { if (!bin || !bytes) { return NULL; } RBinFile *bf = r_bin_file_find_by_name (bin, filename); if (!bf) { bf = r_bin_file_create_append (bin, filename, bytes, sz, file_sz, rawstr, fd, xtr->name, false); if (!bf) { return NULL; } if (!bin->cur) { bin->cur = bf; } } if (bf->xtr_data) { r_list_free (bf->xtr_data); } if (xtr && bytes) { RList *xtr_data_list = xtr->extractall_from_bytes (bin, bytes, sz); RListIter *iter; RBinXtrData *xtr; //populate xtr_data with baddr and laddr that will be used later on //r_bin_file_object_new_from_xtr_data r_list_foreach (xtr_data_list, iter, xtr) { xtr->baddr = baseaddr? baseaddr : UT64_MAX; xtr->laddr = loadaddr? loadaddr : UT64_MAX; } bf->loadaddr = loadaddr; bf->xtr_data = xtr_data_list ? xtr_data_list : NULL; } return bf; } static RBinPlugin *r_bin_get_binplugin_by_name(RBin *bin, const char *name) { RBinPlugin *plugin; RListIter *it; if (bin && name) { r_list_foreach (bin->plugins, it, plugin) { if (!strcmp (plugin->name, name)) { return plugin; } } } return NULL; } R_API RBinPlugin *r_bin_get_binplugin_by_bytes(RBin *bin, const ut8 *bytes, ut64 sz) { RBinPlugin *plugin; RListIter *it; if (!bin || !bytes) { return NULL; } r_list_foreach (bin->plugins, it, plugin) { if (plugin->check_bytes && plugin->check_bytes (bytes, sz)) { return plugin; } } return NULL; } static RBinXtrPlugin *r_bin_get_xtrplugin_by_name(RBin *bin, const char *name) { RBinXtrPlugin *xtr; RListIter *it; if (!bin || !name) return NULL; r_list_foreach (bin->binxtrs, it, xtr) { if (!strcmp (xtr->name, name)) { return xtr; } // must be set to null xtr = NULL; } return NULL; } static RBinPlugin *r_bin_get_binplugin_any(RBin *bin) { return r_bin_get_binplugin_by_name (bin, "any"); } static RBinObject *r_bin_object_new(RBinFile *binfile, RBinPlugin *plugin, ut64 baseaddr, ut64 loadaddr, ut64 offset, ut64 sz) { const ut8 *bytes = binfile? r_buf_buffer (binfile->buf): NULL; ut64 bytes_sz = binfile? r_buf_size (binfile->buf): 0; Sdb *sdb = binfile? binfile->sdb: NULL; RBinObject *o = R_NEW0 (RBinObject); if (!o) { return NULL; } o->obj_size = bytes && (bytes_sz >= sz + offset)? sz: 0; o->boffset = offset; o->id = r_num_rand (0xfffff000); o->kv = sdb_new0 (); o->baddr = baseaddr; o->baddr_shift = 0; o->plugin = plugin; o->loadaddr = loadaddr != UT64_MAX ? loadaddr : 0; // XXX more checking will be needed here // only use LoadBytes if buffer offset != 0 // if (offset != 0 && bytes && plugin && plugin->load_bytes && (bytes_sz // >= sz + offset) ) { if (bytes && plugin && plugin->load_bytes && (bytes_sz >= sz + offset)) { ut64 bsz = bytes_sz - offset; if (sz < bsz) { bsz = sz; } o->bin_obj = plugin->load_bytes (binfile, bytes + offset, sz, loadaddr, sdb); if (!o->bin_obj) { bprintf ( "Error in r_bin_object_new: load_bytes failed " "for %s plugin\n", plugin->name); sdb_free (o->kv); free (o); return NULL; } } else if (binfile && plugin && plugin->load) { // XXX - haha, this is a hack. // switching out the current object for the new // one to be processed RBinObject *old_o = binfile->o; binfile->o = o; if (plugin->load (binfile)) { binfile->sdb_info = o->kv; // mark as do not walk sdb_ns_set (binfile->sdb, "info", o->kv); } else { binfile->o = old_o; } o->obj_size = sz; } else { sdb_free (o->kv); free (o); return NULL; } // XXX - binfile could be null here meaning an improper load // XXX - object size cant be set here and needs to be set where // where the object is created from. The reason for this is to prevent // mis-reporting when the file is loaded from impartial bytes or is // extracted // from a set of bytes in the file r_bin_object_set_items (binfile, o); r_bin_file_object_add (binfile, o); // XXX this is a very hacky alternative to rewriting the // RIO stuff, as discussed here: return o; } #define LIMIT_SIZE 0 static int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr) { if (!bytes) { return false; } r_buf_free (binfile->buf); binfile->buf = r_buf_new (); #if LIMIT_SIZE if (sz > 1024 * 1024) { eprintf ("Too big\n"); // TODO: use r_buf_io instead of setbytes all the time to save memory return NULL; } #else if (steal_ptr) { r_buf_set_bytes_steal (binfile->buf, bytes, sz); } else { r_buf_set_bytes (binfile->buf, bytes, sz); } #endif return binfile->buf != NULL; } static RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr) { RBinFile *binfile = R_NEW0 (RBinFile); if (!binfile) { return NULL; } if (!r_id_pool_grab_id (bin->file_ids, &binfile->id)) { if (steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } free (binfile); //no id means no binfile return NULL; } int res = r_bin_file_set_bytes (binfile, bytes, sz, steal_ptr); if (!res && steal_ptr) { // we own the ptr, free on error free((void*) bytes); } binfile->rbin = bin; binfile->file = file? strdup (file): NULL; binfile->rawstr = rawstr; binfile->fd = fd; binfile->curxtr = r_bin_get_xtrplugin_by_name (bin, xtrname); binfile->sdb = sdb; binfile->size = file_sz; binfile->xtr_data = r_list_newf ((RListFree)r_bin_xtrdata_free); binfile->objs = r_list_newf ((RListFree)r_bin_object_free); binfile->xtr_obj = NULL; if (!binfile->buf) { //r_bin_file_free (binfile); binfile->buf = r_buf_new (); // return NULL; } if (sdb) { binfile->sdb = sdb_ns (sdb, sdb_fmt (0, "fd.%d", fd), 1); sdb_set (binfile->sdb, "archs", "0:0:x86:32", 0); // x86?? /* NOTE */ /* Those refs++ are necessary because sdb_ns() doesnt rerefs all * sub-namespaces */ /* And if any namespace is referenced backwards it gets * double-freed */ binfile->sdb_addrinfo = sdb_ns (binfile->sdb, "addrinfo", 1); binfile->sdb_addrinfo->refs++; sdb_ns_set (sdb, "cur", binfile->sdb); binfile->sdb->refs++; } return binfile; } R_API bool r_bin_file_object_new_from_xtr_data(RBin *bin, RBinFile *bf, ut64 baseaddr, ut64 loadaddr, RBinXtrData *data) { RBinObject *o = NULL; RBinPlugin *plugin = NULL; ut8* bytes; ut64 offset = data? data->offset: 0; ut64 sz = data ? data->size : 0; if (!data || !bf) { return false; } // for right now the bytes used will just be the offest into the binfile // buffer // if the extraction requires some sort of transformation then this will // need to be fixed // here. bytes = data->buffer; if (!bytes) { return false; } plugin = r_bin_get_binplugin_by_bytes (bin, (const ut8*)bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } r_buf_free (bf->buf); bf->buf = r_buf_new_with_bytes ((const ut8*)bytes, data->size); //r_bin_object_new append the new object into binfile o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, offset, sz); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (!o) { return false; } if (o && !o->size) { o->size = sz; } bf->narch = data->file_count; if (!o->info) { o->info = R_NEW0 (RBinInfo); } free (o->info->file); free (o->info->arch); free (o->info->machine); free (o->info->type); o->info->file = strdup (bf->file); o->info->arch = strdup (data->metadata->arch); o->info->machine = strdup (data->metadata->machine); o->info->type = strdup (data->metadata->type); o->info->bits = data->metadata->bits; o->info->has_crypto = bf->o->info->has_crypto; data->loaded = true; return true; } static RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr) { ut8 binfile_created = false; RBinPlugin *plugin = NULL; RBinXtrPlugin *xtr = NULL; RBinObject *o = NULL; RBinFile *bf = NULL; if (sz == UT64_MAX) { return NULL; } if (xtrname) { xtr = r_bin_get_xtrplugin_by_name (bin, xtrname); } if (xtr && xtr->check_bytes (bytes, sz)) { return r_bin_file_xtr_load_bytes (bin, xtr, file, bytes, sz, file_sz, baseaddr, loadaddr, 0, fd, rawstr); } if (!bf) { bf = r_bin_file_create_append (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, steal_ptr); if (!bf) { if (!steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } return NULL; } binfile_created = true; } if (bin->force) { plugin = r_bin_get_binplugin_by_name (bin, bin->force); } if (!plugin) { if (pluginname) { plugin = r_bin_get_binplugin_by_name (bin, pluginname); } if (!plugin) { plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } } } o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf)); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (o && !o->size) { o->size = file_sz; } if (!o) { if (bf && binfile_created) { r_list_delete_data (bin->binfiles, bf); } return NULL; } /* WTF */ if (strcmp (plugin->name, "any")) { bf->narch = 1; } /* free unnecessary rbuffer (???) */ return bf; } static void plugin_free(RBinPlugin *p) { if (p && p->fini) { p->fini (NULL); } R_FREE (p); } // rename to r_bin_plugin_add like the rest R_API int r_bin_add(RBin *bin, RBinPlugin *foo) { RListIter *it; RBinPlugin *plugin; if (foo->init) { foo->init (bin->user); } r_list_foreach (bin->plugins, it, plugin) { if (!strcmp (plugin->name, foo->name)) { return false; } } plugin = R_NEW0 (RBinPlugin); memcpy (plugin, foo, sizeof (RBinPlugin)); r_list_append (bin->plugins, plugin); return true; } R_API int r_bin_xtr_add(RBin *bin, RBinXtrPlugin *foo) { RListIter *it; RBinXtrPlugin *xtr; if (foo->init) { foo->init (bin->user); } // avoid duplicates r_list_foreach (bin->binxtrs, it, xtr) { if (!strcmp (xtr->name, foo->name)) { return false; } } r_list_append (bin->binxtrs, foo); return true; } R_API void *r_bin_free(RBin *bin) { if (!bin) { return NULL; } if (bin->io_owned) { r_io_free (bin->iob.io); } bin->file = NULL; free (bin->force); free (bin->srcdir); //r_bin_free_bin_files (bin); r_list_free (bin->binfiles); r_list_free (bin->binxtrs); r_list_free (bin->plugins); sdb_free (bin->sdb); r_id_pool_free (bin->file_ids); memset (bin, 0, sizeof (RBin)); free (bin); return NULL; } static int r_bin_print_plugin_details(RBin *bin, RBinPlugin *bp, int json) { if (json == 'q') { bin->cb_printf ("%s\n", bp->name); } else if (json) { bin->cb_printf ( "{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}\n", bp->name, bp->desc, bp->license? bp->license: "???"); } else { bin->cb_printf ("Name: %s\n", bp->name); bin->cb_printf ("Description: %s\n", bp->desc); if (bp->license) { bin->cb_printf ("License: %s\n", bp->license); } if (bp->version) { bin->cb_printf ("Version: %s\n", bp->version); } if (bp->author) { bin->cb_printf ("Author: %s\n", bp->author); } } return true; } static int r_bin_print_xtrplugin_details(RBin *bin, RBinXtrPlugin *bx, int json) { if (json == 'q') { bin->cb_printf ("%s\n", bx->name); } else if (json) { bin->cb_printf ( "{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}\n", bx->name, bx->desc, bx->license? bx->license: "???"); } else { bin->cb_printf ("Name: %s\n", bx->name); bin->cb_printf ("Description: %s\n", bx->desc); if (bx->license) { bin->cb_printf ("License: %s\n", bx->license); } } return true; } R_API int r_bin_list(RBin *bin, int json) { RListIter *it; RBinPlugin *bp; RBinXtrPlugin *bx; if (json == 'q') { r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ("%s\n", bp->name); } r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ("%s\n", bx->name); } } else if (json) { int i; i = 0; bin->cb_printf ("{\"bin\":["); r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ( "%s{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}", i? ",": "", bp->name, bp->desc, bp->license? bp->license: "???"); i++; } i = 0; bin->cb_printf ("],\"xtr\":["); r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ( "%s{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}", i? ",": "", bx->name, bx->desc, bx->license? bx->license: "???"); i++; } bin->cb_printf ("]}\n"); } else { r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ("bin %-11s %s (%s) %s %s\n", bp->name, bp->desc, bp->license? bp->license: "???", bp->version? bp->version: "", bp->author? bp->author: ""); } r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ("xtr %-11s %s (%s)\n", bx->name, bx->desc, bx->license? bx->license: "???"); } } return false; } R_API int r_bin_list_plugin(RBin *bin, const char* name, int json) { RListIter *it; RBinPlugin *bp; RBinXtrPlugin *bx; r_list_foreach (bin->plugins, it, bp) { if (!r_str_cmp (name, bp->name, strlen (name))) { continue; } return r_bin_print_plugin_details (bin, bp, json); } r_list_foreach (bin->binxtrs, it, bx) { if (!r_str_cmp (name, bx->name, strlen (name))) { continue; } return r_bin_print_xtrplugin_details (bin, bx, json); } eprintf ("cannot find plugin %s\n", name); return false; } static ut64 binobj_get_baddr(RBinObject *o) { return o? o->baddr + o->baddr_shift: UT64_MAX; } R_API ut64 r_binfile_get_baddr(RBinFile *binfile) { return binfile? binobj_get_baddr (binfile->o): UT64_MAX; } /* returns the base address of bin or UT64_MAX in case of errors */ R_API ut64 r_bin_get_baddr(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return binobj_get_baddr (o); } /* returns the load address of bin or UT64_MAX in case of errors */ R_API ut64 r_bin_get_laddr(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->loadaddr: UT64_MAX; } R_API void r_bin_set_baddr(RBin *bin, ut64 baddr) { RBinObject *o = r_bin_cur_object (bin); binobj_set_baddr (o, baddr); // XXX - update all the infos? } R_API ut64 r_bin_get_boffset(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->boffset: UT64_MAX; } R_API RBinAddr *r_bin_get_sym(RBin *bin, int sym) { RBinObject *o = r_bin_cur_object (bin); if (sym < 0 || sym >= R_BIN_SYM_LAST) { return NULL; } return o? o->binsym[sym]: NULL; } // XXX: those accessors are redundant R_API RList *r_bin_get_entries(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->entries: NULL; } R_API RList *r_bin_get_fields(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->fields: NULL; } R_API RList *r_bin_get_imports(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->imports: NULL; } R_API RBinInfo *r_bin_get_info(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->info: NULL; } R_API RList *r_bin_get_libs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->libs: NULL; } R_API RList * r_bin_patch_relocs(RBin *bin) { static bool first = true; RBinObject *o = r_bin_cur_object (bin); if (!o) { return NULL; } // r_bin_object_set_items set o->relocs but there we don't have access // to io // so we need to be run from bin_relocs, free the previous reloc and get // the patched ones if (first && o->plugin && o->plugin->patch_relocs) { RList *tmp = o->plugin->patch_relocs (bin); first = false; if (!tmp) { return o->relocs; } r_list_free (o->relocs); o->relocs = tmp; REBASE_PADDR (o, o->relocs, RBinReloc); first = false; return o->relocs; } return o->relocs; } R_API RList *r_bin_get_relocs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->relocs: NULL; } R_API RList *r_bin_get_sections(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->sections: NULL; } // TODO: Move into section.c and rename it to r_io_section_get_at () R_API RBinSection *r_bin_get_section_at(RBinObject *o, ut64 off, int va) { RBinSection *section; RListIter *iter; ut64 from, to; if (o) { // TODO: must be O(1) .. use sdb here r_list_foreach (o->sections, iter, section) { from = va? binobj_a2b (o, section->vaddr): section->paddr; to = va? (binobj_a2b (o, section->vaddr) + section->vsize) : (section->paddr + section->size); if (off >= from && off < to) { return section; } } } return NULL; } R_API RList *r_bin_reset_strings(RBin *bin) { RBinFile *a = r_bin_cur (bin); RBinObject *o = r_bin_cur_object (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (!a || !o) { return NULL; } if (o->strings) { r_list_free (o->strings); o->strings = NULL; } if (bin->minstrlen <= 0) { return NULL; } a->rawstr = bin->rawstr; if (plugin && plugin->strings) { o->strings = plugin->strings (a); } else { o->strings = get_strings (a, bin->minstrlen, 0); } if (bin->debase64) { filterStrings (bin, o->strings); } return o->strings; } R_API RList *r_bin_get_strings(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->strings: NULL; } R_API int r_bin_is_string(RBin *bin, ut64 va) { RBinString *string; RListIter *iter; RList *list; if (!(list = r_bin_get_strings (bin))) { return false; } r_list_foreach (list, iter, string) { if (string->vaddr == va) { return true; } if (string->vaddr > va) { return false; } } return false; } //callee must not free the symbol R_API RBinSymbol *r_bin_get_symbol_at_vaddr(RBin *bin, ut64 addr) { //use skiplist here RList *symbols = r_bin_get_symbols (bin); RListIter *iter; RBinSymbol *symbol; r_list_foreach (symbols, iter, symbol) { if (symbol->vaddr == addr) { return symbol; } } return NULL; } //callee must not free the symbol R_API RBinSymbol *r_bin_get_symbol_at_paddr(RBin *bin, ut64 addr) { //use skiplist here RList *symbols = r_bin_get_symbols (bin); RListIter *iter; RBinSymbol *symbol; r_list_foreach (symbols, iter, symbol) { if (symbol->paddr == addr) { return symbol; } } return NULL; } R_API RList *r_bin_get_symbols(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->symbols: NULL; } R_API RList *r_bin_get_mem(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->mem: NULL; } R_API int r_bin_is_big_endian(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return (o && o->info)? o->info->big_endian: -1; } R_API int r_bin_is_stripped(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_STRIPPED & o->info->dbg_info): 1; } R_API int r_bin_is_static(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); if (o && r_list_length (o->libs) > 0) return R_BIN_DBG_STATIC & o->info->dbg_info; return true; } // TODO: Integrate with r_bin_dbg */ R_API int r_bin_has_dbg_linenums(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_LINENUMS & o->info->dbg_info): false; } R_API int r_bin_has_dbg_syms(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_SYMS & o->info->dbg_info): false; } R_API int r_bin_has_dbg_relocs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_RELOCS & o->info->dbg_info): false; } R_API RBin *r_bin_new() { int i; RBinXtrPlugin *static_xtr_plugin; RBin *bin = R_NEW0 (RBin); if (!bin) { return NULL; } bin->force = NULL; bin->filter_rules = UT64_MAX; bin->sdb = sdb_new0 (); bin->cb_printf = (PrintfCallback)printf; bin->plugins = r_list_newf ((RListFree)plugin_free); bin->minstrlen = 0; bin->want_dbginfo = true; bin->cur = NULL; bin->io_owned = false; bin->binfiles = r_list_newf ((RListFree)r_bin_file_free); for (i = 0; bin_static_plugins[i]; i++) { r_bin_add (bin, bin_static_plugins[i]); } bin->binxtrs = r_list_new (); bin->binxtrs->free = free; for (i = 0; bin_xtr_static_plugins[i]; i++) { static_xtr_plugin = R_NEW0 (RBinXtrPlugin); if (!static_xtr_plugin) { free (bin); return NULL; } *static_xtr_plugin = *bin_xtr_static_plugins[i]; r_bin_xtr_add (bin, static_xtr_plugin); } bin->file_ids = r_id_pool_new (0, 0xffffffff); return bin; } R_API int r_bin_use_arch(RBin *bin, const char *arch, int bits, const char *name) { RBinFile *binfile = r_bin_file_find_by_arch_bits (bin, arch, bits, name); RBinObject *obj = NULL; if (binfile) { obj = r_bin_object_find_by_arch_bits (binfile, arch, bits, name); if (!obj) { if (binfile->xtr_data) { RBinXtrData *xtr_data = r_list_get_n (binfile->xtr_data, 0); if (!r_bin_file_object_new_from_xtr_data (bin, binfile, UT64_MAX, r_bin_get_laddr (bin), xtr_data)) { return false; } obj = r_list_get_n (binfile->objs, 0); } } } else { void *plugin = r_bin_get_binplugin_by_name (bin, name); if (plugin) { if (bin->cur) { bin->cur->curplugin = plugin; } binfile = r_bin_file_new (bin, "-", NULL, 0, 0, 0, 999, NULL, NULL, false); // create object and set arch/bits obj = r_bin_object_new (binfile, plugin, 0, 0, 0, 1024); binfile->o = obj; obj->info = R_NEW0 (RBinInfo); obj->info->arch = strdup (arch); obj->info->bits = bits; } } return (binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj)); } R_API RBinObject *r_bin_object_find_by_arch_bits(RBinFile *binfile, const char *arch, int bits, const char *name) { RBinObject *obj = NULL; RListIter *iter = NULL; RBinInfo *info = NULL; r_list_foreach (binfile->objs, iter, obj) { info = obj->info; if (info && info->arch && info->file && (bits == info->bits) && !strcmp (info->arch, arch) && !strcmp (info->file, name)) { break; } obj = NULL; } return obj; } R_API RBinFile *r_bin_file_find_by_arch_bits(RBin *bin, const char *arch, int bits, const char *name) { RListIter *iter; RBinFile *binfile = NULL; RBinXtrData *xtr_data; if (!name || !arch) { return NULL; } r_list_foreach (bin->binfiles, iter, binfile) { RListIter *iter_xtr; if (!binfile->xtr_data) { continue; } // look for sub-bins in Xtr Data and Load if we need to r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) { if (xtr_data->metadata && xtr_data->metadata->arch) { char *iter_arch = xtr_data->metadata->arch; int iter_bits = xtr_data->metadata->bits; if (bits == iter_bits && !strcmp (iter_arch, arch)) { if (!xtr_data->loaded) { if (!r_bin_file_object_new_from_xtr_data ( bin, binfile, xtr_data->baddr, xtr_data->laddr, xtr_data)) { return NULL; } return binfile; } } } } } return binfile; } R_API int r_bin_select(RBin *bin, const char *arch, int bits, const char *name) { RBinFile *cur = r_bin_cur (bin), *binfile = NULL; RBinObject *obj = NULL; name = !name && cur? cur->file: name; binfile = r_bin_file_find_by_arch_bits (bin, arch, bits, name); if (binfile && name) { obj = r_bin_object_find_by_arch_bits (binfile, arch, bits, name); } return binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } R_API int r_bin_select_object(RBinFile *binfile, const char *arch, int bits, const char *name) { RBinObject *obj = binfile ? r_bin_object_find_by_arch_bits ( binfile, arch, bits, name) : NULL; return obj && r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, obj); } static RBinObject *r_bin_file_object_find_by_id(RBinFile *binfile, ut32 binobj_id) { RBinObject *obj; RListIter *iter; if (binfile) { r_list_foreach (binfile->objs, iter, obj) { if (obj->id == binobj_id) { return obj; } } } return NULL; } static RBinFile *r_bin_file_find_by_object_id(RBin *bin, ut32 binobj_id) { RListIter *iter; RBinFile *binfile; r_list_foreach (bin->binfiles, iter, binfile) { if (r_bin_file_object_find_by_id (binfile, binobj_id)) { return binfile; } } return NULL; } static RBinFile *r_bin_file_find_by_id(RBin *bin, ut32 binfile_id) { RBinFile *binfile = NULL; RListIter *iter = NULL; r_list_foreach (bin->binfiles, iter, binfile) { if (binfile->id == binfile_id) { break; } binfile = NULL; } return binfile; } R_API int r_bin_object_delete(RBin *bin, ut32 binfile_id, ut32 binobj_id) { RBinFile *binfile = NULL; //, *cbinfile = r_bin_cur (bin); RBinObject *obj = NULL; int res = false; #if 0 if (binfile_id == UT32_MAX && binobj_id == UT32_MAX) { return false; } #endif if (binfile_id == -1) { binfile = r_bin_file_find_by_object_id (bin, binobj_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } else if (binobj_id == -1) { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? binfile->o: NULL; } else { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } // lazy way out, always leaving at least 1 bin object loaded if (binfile && (r_list_length (binfile->objs) > 1)) { binfile->o = NULL; r_list_delete_data (binfile->objs, obj); obj = (RBinObject *)r_list_get_n (binfile->objs, 0); res = obj && binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } return res; } R_API int r_bin_select_by_ids(RBin *bin, ut32 binfile_id, ut32 binobj_id) { RBinFile *binfile = NULL; RBinObject *obj = NULL; if (binfile_id == UT32_MAX && binobj_id == UT32_MAX) { return false; } if (binfile_id == -1) { binfile = r_bin_file_find_by_object_id (bin, binobj_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } else if (binobj_id == -1) { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? binfile->o: NULL; } else { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } if (!binfile || !obj) { return false; } return obj && binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } R_API int r_bin_select_idx(RBin *bin, const char *name, int idx) { RBinFile *nbinfile = NULL, *binfile = r_bin_cur (bin); RBinObject *obj = NULL; const char *tname = !name && binfile? binfile->file: name; int res = false; if (!tname || !bin) { return res; } nbinfile = r_bin_file_find_by_name_n (bin, tname, idx); obj = nbinfile? r_list_get_n (nbinfile->objs, idx): NULL; return obj && nbinfile && r_bin_file_set_cur_binfile_obj (bin, nbinfile, obj); } static void list_xtr_archs(RBin *bin, int mode) { RBinFile *binfile = r_bin_cur (bin); if (binfile->xtr_data) { RListIter *iter_xtr; RBinXtrData *xtr_data; int bits, i = 0; char *arch, *machine; r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) { if (!xtr_data || !xtr_data->metadata || !xtr_data->metadata->arch) { continue; } arch = xtr_data->metadata->arch; machine = xtr_data->metadata->machine; bits = xtr_data->metadata->bits; switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ( "%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":\"%" PFMT64d ",\"machine\":\"%s\"}", i++ ? "," : "", arch, bits, xtr_data->offset, xtr_data->size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %" PFMT64d " %s_%i %s\n", i++, xtr_data->offset, xtr_data->size, arch, bits, machine); break; } } } } R_API void r_bin_list_archs(RBin *bin, int mode) { RListIter *iter; int i = 0; char unk[128]; char archline[128]; RBinFile *binfile = r_bin_cur (bin); RBinObject *obj = NULL; const char *name = binfile? binfile->file: NULL; int narch = binfile? binfile->narch: 0; //are we with xtr format? if (binfile && binfile->curxtr) { list_xtr_archs (bin, mode); return; } Sdb *binfile_sdb = binfile? binfile->sdb: NULL; if (!binfile_sdb) { eprintf ("Cannot find SDB!\n"); return; } else if (!binfile) { eprintf ("Binary format not currently loaded!\n"); return; } sdb_unset (binfile_sdb, ARCHS_KEY, 0); if (mode == 'j') { bin->cb_printf ("\"bins\":["); } RBinFile *nbinfile = r_bin_file_find_by_name_n (bin, name, i); if (!nbinfile) { return; } i = -1; r_list_foreach (nbinfile->objs, iter, obj) { RBinInfo *info = obj->info; char bits = info? info->bits: 0; ut64 boffset = obj->boffset; ut32 obj_size = obj->obj_size; const char *arch = info? info->arch: NULL; const char *machine = info? info->machine: "unknown_machine"; i++; if (!arch) { snprintf (unk, sizeof (unk), "unk_%d", i); arch = unk; } if (info && narch > 1) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", arch, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d %s_%i %s\n", i, boffset, obj_size, arch, bits, machine); } snprintf (archline, sizeof (archline) - 1, "0x%08" PFMT64x ":%d:%s:%d:%s", boffset, obj_size, arch, bits, machine); /// xxx machine not exported? //sdb_array_push (binfile_sdb, ARCHS_KEY, archline, 0); } else { if (info) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", arch, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d %s_%d\n", i, boffset, obj_size, arch, bits); } snprintf (archline, sizeof (archline), "0x%08" PFMT64x ":%d:%s:%d", boffset, obj_size, arch, bits); } else if (nbinfile && mode) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"unk_%d\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", i, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d unk_0\n", i, boffset, obj_size); } snprintf (archline, sizeof (archline), "0x%08" PFMT64x ":%d:%s:%d", boffset, obj_size, "unk", 0); } else { eprintf ("Error: Invalid RBinFile.\n"); } //sdb_array_push (binfile_sdb, ARCHS_KEY, archline, 0); } } if (mode == 'j') { bin->cb_printf ("]"); } } R_API void r_bin_set_user_ptr(RBin *bin, void *user) { bin->user = user; } static RBinSection* _get_vsection_at(RBin *bin, ut64 vaddr) { RBinObject *cur = r_bin_object_get_cur (bin); return r_bin_get_section_at (cur, vaddr, true); } R_API void r_bin_bind(RBin *bin, RBinBind *b) { if (b) { b->bin = bin; b->get_offset = getoffset; b->get_name = getname; b->get_sections = r_bin_get_sections; b->get_vsect_at = _get_vsection_at; } } R_API RBuffer *r_bin_create(RBin *bin, const ut8 *code, int codelen, const ut8 *data, int datalen) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (codelen < 0) { codelen = 0; } if (datalen < 0) { datalen = 0; } if (plugin && plugin->create) { return plugin->create (bin, code, codelen, data, datalen); } return NULL; } R_API RBuffer *r_bin_package(RBin *bin, const char *type, const char *file, RList *files) { if (!strcmp (type, "zip")) { #if 0 int zep = 0; struct zip * z = zip_open (file, 8 | 1, &zep); if (z) { RListIter *iter; const char *f; eprintf ("zip file created\n"); r_list_foreach (files, iter, f) { struct zip_source *zs = NULL; zs = zip_source_file (z, f, 0, 1024); if (zs) { eprintf ("ADD %s\n", f); zip_add (z, f, zs); zip_source_free (zs); } else { eprintf ("Cannot find file %s\n", f); } eprintf ("zS %p\n", zs); } zip_close (z); } else { eprintf ("Cannot create zip file\n"); } #endif } else if (!strcmp (type, "fat")) { const char *f; RListIter *iter; ut32 num; ut8 *num8 = (ut8*)&num; RBuffer *buf = r_buf_new_file (file, true); r_buf_write_at (buf, 0, (const ut8*)"\xca\xfe\xba\xbe", 4); int count = r_list_length (files); num = r_read_be32 (&count); ut64 from = 0x1000; r_buf_write_at (buf, 4, num8, 4); int off = 12; int item = 0; r_list_foreach (files, iter, f) { int f_len = 0; ut8 *f_buf = (ut8 *)r_file_slurp (f, &f_len); if (f_buf && f_len >= 0) { eprintf ("ADD %s %d\n", f, f_len); } else { eprintf ("Cannot open %s\n", f); free (f_buf); continue; } item++; /* CPU */ num8[0] = f_buf[7]; num8[1] = f_buf[6]; num8[2] = f_buf[5]; num8[3] = f_buf[4]; r_buf_write_at (buf, off - 4, num8, 4); /* SUBTYPE */ num8[0] = f_buf[11]; num8[1] = f_buf[10]; num8[2] = f_buf[9]; num8[3] = f_buf[8]; r_buf_write_at (buf, off, num8, 4); ut32 from32 = from; /* FROM */ num = r_read_be32 (&from32); r_buf_write_at (buf, off + 4, num8, 4); r_buf_write_at (buf, from, f_buf, f_len); /* SIZE */ num = r_read_be32 (&f_len); r_buf_write_at (buf, off + 8, num8, 4); off += 20; from += f_len + (f_len % 0x1000); free (f_buf); } r_buf_free (buf); return NULL; } else { eprintf ("Usage: rabin2 -X [fat|zip] [filename] [files ...]\n"); } return NULL; } R_API RBinObject *r_bin_get_object(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); if (o) { o->referenced++; } return o; } R_API RList * /*<RBinClass>*/ r_bin_get_classes(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->classes: NULL; } R_API void r_bin_class_free(RBinClass *c) { free (c->name); free (c->super); r_list_free (c->methods); r_list_free (c->fields); free (c); } R_API RBinClass *r_bin_class_new(RBinFile *binfile, const char *name, const char *super, int view) { RBinObject *o = binfile? binfile->o: NULL; RList *list = NULL; RBinClass *c; if (!o) { return NULL; } list = o->classes; if (!name) { return NULL; } c = r_bin_class_get (binfile, name); if (c) { if (super) { free (c->super); c->super = strdup (super); } return c; } c = R_NEW0 (RBinClass); if (!c) { return NULL; } c->name = strdup (name); c->super = super? strdup (super): NULL; c->index = r_list_length (list); c->methods = r_list_new (); c->fields = r_list_new (); c->visibility = view; if (!list) { list = o->classes = r_list_new (); } r_list_append (list, c); return c; } R_API RBinClass *r_bin_class_get(RBinFile *binfile, const char *name) { if (!binfile || !binfile->o || !name) { return NULL; } RBinClass *c; RListIter *iter; RList *list = binfile->o->classes; r_list_foreach (list, iter, c) { if (!strcmp (c->name, name)) { return c; } } return NULL; } R_API RBinSymbol *r_bin_class_add_method(RBinFile *binfile, const char *classname, const char *name, int nargs) { RBinClass *c = r_bin_class_get (binfile, classname); if (!c) { c = r_bin_class_new (binfile, classname, NULL, 0); if (!c) { eprintf ("Cannot allocate class %s\n", classname); return NULL; } } RBinSymbol *m; RListIter *iter; r_list_foreach (c->methods, iter, m) { if (!strcmp (m->name, name)) { return NULL; } } RBinSymbol *sym = R_NEW0 (RBinSymbol); if (!sym) { return NULL; } sym->name = strdup (name); r_list_append (c->methods, sym); return sym; } R_API void r_bin_class_add_field(RBinFile *binfile, const char *classname, const char *name) { //TODO: add_field into class //eprintf ("TODO add field: %s \n", name); } /* returns vaddr, rebased with the baseaddr of binfile, if va is enabled for * bin, paddr otherwise */ R_API ut64 r_binfile_get_vaddr(RBinFile *binfile, ut64 paddr, ut64 vaddr) { int use_va = 0; if (binfile && binfile->o && binfile->o->info) { use_va = binfile->o->info->has_va; } return use_va? binobj_a2b (binfile->o, vaddr): paddr; } /* returns vaddr, rebased with the baseaddr of bin, if va is enabled for bin, * paddr otherwise */ R_API ut64 r_bin_get_vaddr(RBin *bin, ut64 paddr, ut64 vaddr) { if (!bin || !bin->cur) { return UT64_MAX; } if (paddr == UT64_MAX) { return UT64_MAX; } /* hack to realign thumb symbols */ if (bin->cur->o && bin->cur->o->info && bin->cur->o->info->arch) { if (bin->cur->o->info->bits == 16) { RBinSection *s = r_bin_get_section_at (bin->cur->o, paddr, false); // autodetect thumb if (s && s->srwx & 1 && strstr (s->name, "text")) { if (!strcmp (bin->cur->o->info->arch, "arm") && (vaddr & 1)) { vaddr = (vaddr >> 1) << 1; } } } } return r_binfile_get_vaddr (bin->cur, paddr, vaddr); } R_API ut64 r_bin_a2b(RBin *bin, ut64 addr) { RBinObject *o = r_bin_cur_object (bin); return o? o->baddr_shift + addr: addr; } R_API ut64 r_bin_get_size(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o ? o->size : 0; } R_API int r_bin_file_delete_all(RBin *bin) { int counter = 0; if (bin) { counter = r_list_length (bin->binfiles); r_list_purge (bin->binfiles); bin->cur = NULL; } return counter; } R_API int r_bin_file_delete(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; RBinFile *cur = r_bin_cur (bin); if (bin && cur) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { if (cur->fd == bin_fd) { //avoiding UaF due to dead reference bin->cur = NULL; } r_list_delete (bin->binfiles, iter); return 1; } } } return 0; } R_API RBinFile *r_bin_file_find_by_fd(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; if (bin) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { return bf; } } } return NULL; } R_API RBinFile *r_bin_file_find_by_name(RBin *bin, const char *name) { RListIter *iter; RBinFile *bf = NULL; if (!bin || !name) { return NULL; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { break; } bf = NULL; } return bf; } R_API RBinFile *r_bin_file_find_by_name_n(RBin *bin, const char *name, int idx) { RListIter *iter; RBinFile *bf = NULL; int i = 0; if (!bin) { return bf; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { if (i == idx) { break; } i++; } bf = NULL; } return bf; } R_API int r_bin_file_set_cur_by_fd(RBin *bin, ut32 bin_fd) { RBinFile *bf = r_bin_file_find_by_fd (bin, bin_fd); return r_bin_file_set_cur_binfile (bin, bf); } R_API int r_bin_file_set_cur_binfile_obj(RBin *bin, RBinFile *bf, RBinObject *obj) { RBinPlugin *plugin = NULL; if (!bin || !bf || !obj) { return false; } bin->file = bf->file; bin->cur = bf; bin->narch = bf->narch; bf->o = obj; plugin = r_bin_file_cur_plugin (bf); if (bin->minstrlen < 1) { bin->minstrlen = plugin? plugin->minstrlen: bin->minstrlen; } return true; } R_API int r_bin_file_set_cur_binfile(RBin *bin, RBinFile *bf) { RBinObject *obj = bf? bf->o: NULL; return obj? r_bin_file_set_cur_binfile_obj (bin, bf, obj): false; } R_API int r_bin_file_set_cur_by_name(RBin *bin, const char *name) { RBinFile *bf = r_bin_file_find_by_name (bin, name); return r_bin_file_set_cur_binfile (bin, bf); } R_API RBinFile *r_bin_cur(RBin *bin) { return bin? bin->cur: NULL; } R_API RBinObject *r_bin_cur_object(RBin *bin) { RBinFile *binfile = r_bin_cur (bin); return binfile? binfile->o: NULL; } R_API void r_bin_force_plugin(RBin *bin, const char *name) { free (bin->force); bin->force = (name && *name)? strdup (name): NULL; } R_API int r_bin_read_at(RBin *bin, ut64 addr, ut8 *buf, int size) { RIOBind *iob; if (!bin || !(iob = &(bin->iob))) { return false; } return iob->read_at (iob->io, addr, buf, size); } R_API int r_bin_write_at(RBin *bin, ut64 addr, const ut8 *buf, int size) { RIOBind *iob; if (!bin || !(iob = &(bin->iob))) { return false; } return iob->write_at (iob->io, addr, buf, size); } R_API const char *r_bin_entry_type_string(int etype) { switch (etype) { case R_BIN_ENTRY_TYPE_PROGRAM: return "program"; case R_BIN_ENTRY_TYPE_MAIN: return "main"; case R_BIN_ENTRY_TYPE_INIT: return "init"; case R_BIN_ENTRY_TYPE_FINI: return "fini"; case R_BIN_ENTRY_TYPE_TLS: return "tls"; } return NULL; } R_API void r_bin_load_filter(RBin *bin, ut64 rules) { bin->filter_rules = rules; } /* RBinField */ R_API RBinField *r_bin_field_new(ut64 paddr, ut64 vaddr, int size, const char *name, const char *comment, const char *format) { RBinField *ptr; if (!(ptr = R_NEW0 (RBinField))) { return NULL; } ptr->name = strdup (name); ptr->comment = (comment && *comment)? strdup (comment): NULL; ptr->format = (format && *format)? strdup (format): NULL; ptr->paddr = paddr; ptr->size = size; // ptr->visibility = ??? ptr->vaddr = vaddr; return ptr; } // use void* to honor the RListFree signature R_API void r_bin_field_free(void *_field) { RBinField *field = (RBinField*) _field; free (field->name); free (field->comment); free (field->format); free (field); } R_API const char *r_bin_get_meth_flag_string(ut64 flag, bool compact) { switch (flag) { case R_BIN_METH_CLASS: return compact ? "c" : "class"; case R_BIN_METH_STATIC: return compact ? "s" : "static"; case R_BIN_METH_PUBLIC: return compact ? "p" : "public"; case R_BIN_METH_PRIVATE: return compact ? "P" : "private"; case R_BIN_METH_PROTECTED: return compact ? "r" : "protected"; case R_BIN_METH_INTERNAL: return compact ? "i" : "internal"; case R_BIN_METH_OPEN: return compact ? "o" : "open"; case R_BIN_METH_FILEPRIVATE: return compact ? "e" : "fileprivate"; case R_BIN_METH_FINAL: return compact ? "f" : "final"; case R_BIN_METH_VIRTUAL: return compact ? "v" : "virtual"; case R_BIN_METH_CONST: return compact ? "k" : "const"; case R_BIN_METH_MUTATING: return compact ? "m" : "mutating"; case R_BIN_METH_ABSTRACT: return compact ? "a" : "abstract"; case R_BIN_METH_SYNCHRONIZED: return compact ? "y" : "synchronized"; case R_BIN_METH_NATIVE: return compact ? "n" : "native"; case R_BIN_METH_BRIDGE: return compact ? "b" : "bridge"; case R_BIN_METH_VARARGS: return compact ? "g" : "varargs"; case R_BIN_METH_SYNTHETIC: return compact ? "h" : "synthetic"; case R_BIN_METH_STRICT: return compact ? "t" : "strict"; case R_BIN_METH_MIRANDA: return compact ? "A" : "miranda"; case R_BIN_METH_CONSTRUCTOR: return compact ? "C" : "constructor"; case R_BIN_METH_DECLARED_SYNCHRONIZED: return compact ? "Y" : "declared_synchronized"; default: return NULL; } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2900_0
crossvul-cpp_data_good_290_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IPv6 Internet Control Message Protocol (ICMPv6) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "addrtostr.h" #include "extract.h" #include "ip6.h" #include "ipproto.h" #include "udp.h" #include "ah.h" static const char icmp6_tstr[] = " [|icmp6]"; static const char rpl_tstr[] = " [|rpl]"; static const char mldv2_tstr[] = " [|mldv2]"; /* NetBSD: icmp6.h,v 1.13 2000/08/03 16:30:37 itojun Exp */ /* $KAME: icmp6.h,v 1.22 2000/08/03 15:25:16 jinmei Exp $ */ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ struct icmp6_hdr { uint8_t icmp6_type; /* type field */ uint8_t icmp6_code; /* code field */ uint16_t icmp6_cksum; /* checksum field */ union { uint32_t icmp6_un_data32[1]; /* type-specific field */ uint16_t icmp6_un_data16[2]; /* type-specific field */ uint8_t icmp6_un_data8[4]; /* type-specific field */ } icmp6_dataun; }; #define icmp6_data32 icmp6_dataun.icmp6_un_data32 #define icmp6_data16 icmp6_dataun.icmp6_un_data16 #define icmp6_data8 icmp6_dataun.icmp6_un_data8 #define icmp6_pptr icmp6_data32[0] /* parameter prob */ #define icmp6_mtu icmp6_data32[0] /* packet too big */ #define icmp6_id icmp6_data16[0] /* echo request/reply */ #define icmp6_seq icmp6_data16[1] /* echo request/reply */ #define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */ #define ICMP6_DST_UNREACH 1 /* dest unreachable, codes: */ #define ICMP6_PACKET_TOO_BIG 2 /* packet too big */ #define ICMP6_TIME_EXCEEDED 3 /* time exceeded, code: */ #define ICMP6_PARAM_PROB 4 /* ip6 header bad */ #define ICMP6_ECHO_REQUEST 128 /* echo service */ #define ICMP6_ECHO_REPLY 129 /* echo reply */ #define ICMP6_MEMBERSHIP_QUERY 130 /* group membership query */ #define MLD6_LISTENER_QUERY 130 /* multicast listener query */ #define ICMP6_MEMBERSHIP_REPORT 131 /* group membership report */ #define MLD6_LISTENER_REPORT 131 /* multicast listener report */ #define ICMP6_MEMBERSHIP_REDUCTION 132 /* group membership termination */ #define MLD6_LISTENER_DONE 132 /* multicast listener done */ #define ND_ROUTER_SOLICIT 133 /* router solicitation */ #define ND_ROUTER_ADVERT 134 /* router advertisement */ #define ND_NEIGHBOR_SOLICIT 135 /* neighbor solicitation */ #define ND_NEIGHBOR_ADVERT 136 /* neighbor advertisement */ #define ND_REDIRECT 137 /* redirect */ #define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */ #define ICMP6_WRUREQUEST 139 /* who are you request */ #define ICMP6_WRUREPLY 140 /* who are you reply */ #define ICMP6_FQDN_QUERY 139 /* FQDN query */ #define ICMP6_FQDN_REPLY 140 /* FQDN reply */ #define ICMP6_NI_QUERY 139 /* node information request */ #define ICMP6_NI_REPLY 140 /* node information reply */ #define IND_SOLICIT 141 /* inverse neighbor solicitation */ #define IND_ADVERT 142 /* inverse neighbor advertisement */ #define ICMP6_V2_MEMBERSHIP_REPORT 143 /* v2 membership report */ #define MLDV2_LISTENER_REPORT 143 /* v2 multicast listener report */ #define ICMP6_HADISCOV_REQUEST 144 #define ICMP6_HADISCOV_REPLY 145 #define ICMP6_MOBILEPREFIX_SOLICIT 146 #define ICMP6_MOBILEPREFIX_ADVERT 147 #define MLD6_MTRACE_RESP 200 /* mtrace response(to sender) */ #define MLD6_MTRACE 201 /* mtrace messages */ #define ICMP6_MAXTYPE 201 #define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */ #define ICMP6_DST_UNREACH_ADMIN 1 /* administratively prohibited */ #define ICMP6_DST_UNREACH_NOTNEIGHBOR 2 /* not a neighbor(obsolete) */ #define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */ #define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */ #define ICMP6_DST_UNREACH_NOPORT 4 /* port unreachable */ #define ICMP6_TIME_EXCEED_TRANSIT 0 /* ttl==0 in transit */ #define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* ttl==0 in reass */ #define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */ #define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized next header */ #define ICMP6_PARAMPROB_OPTION 2 /* unrecognized option */ #define ICMP6_INFOMSG_MASK 0x80 /* all informational messages */ #define ICMP6_NI_SUBJ_IPV6 0 /* Query Subject is an IPv6 address */ #define ICMP6_NI_SUBJ_FQDN 1 /* Query Subject is a Domain name */ #define ICMP6_NI_SUBJ_IPV4 2 /* Query Subject is an IPv4 address */ #define ICMP6_NI_SUCCESS 0 /* node information successful reply */ #define ICMP6_NI_REFUSED 1 /* node information request is refused */ #define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */ #define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */ #define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */ #define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */ /* Used in kernel only */ #define ND_REDIRECT_ONLINK 0 /* redirect to an on-link node */ #define ND_REDIRECT_ROUTER 1 /* redirect to a better router */ /* * Multicast Listener Discovery */ struct mld6_hdr { struct icmp6_hdr mld6_hdr; struct in6_addr mld6_addr; /* multicast address */ }; #define mld6_type mld6_hdr.icmp6_type #define mld6_code mld6_hdr.icmp6_code #define mld6_cksum mld6_hdr.icmp6_cksum #define mld6_maxdelay mld6_hdr.icmp6_data16[0] #define mld6_reserved mld6_hdr.icmp6_data16[1] #define MLD_MINLEN 24 #define MLDV2_MINLEN 28 /* * Neighbor Discovery */ struct nd_router_solicit { /* router solicitation */ struct icmp6_hdr nd_rs_hdr; /* could be followed by options */ }; #define nd_rs_type nd_rs_hdr.icmp6_type #define nd_rs_code nd_rs_hdr.icmp6_code #define nd_rs_cksum nd_rs_hdr.icmp6_cksum #define nd_rs_reserved nd_rs_hdr.icmp6_data32[0] struct nd_router_advert { /* router advertisement */ struct icmp6_hdr nd_ra_hdr; uint32_t nd_ra_reachable; /* reachable time */ uint32_t nd_ra_retransmit; /* retransmit timer */ /* could be followed by options */ }; #define nd_ra_type nd_ra_hdr.icmp6_type #define nd_ra_code nd_ra_hdr.icmp6_code #define nd_ra_cksum nd_ra_hdr.icmp6_cksum #define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0] #define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1] #define ND_RA_FLAG_MANAGED 0x80 #define ND_RA_FLAG_OTHER 0x40 #define ND_RA_FLAG_HOME_AGENT 0x20 /* * Router preference values based on draft-draves-ipngwg-router-selection-01. * These are non-standard definitions. */ #define ND_RA_FLAG_RTPREF_MASK 0x18 /* 00011000 */ #define ND_RA_FLAG_RTPREF_HIGH 0x08 /* 00001000 */ #define ND_RA_FLAG_RTPREF_MEDIUM 0x00 /* 00000000 */ #define ND_RA_FLAG_RTPREF_LOW 0x18 /* 00011000 */ #define ND_RA_FLAG_RTPREF_RSV 0x10 /* 00010000 */ #define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1] struct nd_neighbor_solicit { /* neighbor solicitation */ struct icmp6_hdr nd_ns_hdr; struct in6_addr nd_ns_target; /*target address */ /* could be followed by options */ }; #define nd_ns_type nd_ns_hdr.icmp6_type #define nd_ns_code nd_ns_hdr.icmp6_code #define nd_ns_cksum nd_ns_hdr.icmp6_cksum #define nd_ns_reserved nd_ns_hdr.icmp6_data32[0] struct nd_neighbor_advert { /* neighbor advertisement */ struct icmp6_hdr nd_na_hdr; struct in6_addr nd_na_target; /* target address */ /* could be followed by options */ }; #define nd_na_type nd_na_hdr.icmp6_type #define nd_na_code nd_na_hdr.icmp6_code #define nd_na_cksum nd_na_hdr.icmp6_cksum #define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0] #define ND_NA_FLAG_ROUTER 0x80000000 #define ND_NA_FLAG_SOLICITED 0x40000000 #define ND_NA_FLAG_OVERRIDE 0x20000000 struct nd_redirect { /* redirect */ struct icmp6_hdr nd_rd_hdr; struct in6_addr nd_rd_target; /* target address */ struct in6_addr nd_rd_dst; /* destination address */ /* could be followed by options */ }; #define nd_rd_type nd_rd_hdr.icmp6_type #define nd_rd_code nd_rd_hdr.icmp6_code #define nd_rd_cksum nd_rd_hdr.icmp6_cksum #define nd_rd_reserved nd_rd_hdr.icmp6_data32[0] struct nd_opt_hdr { /* Neighbor discovery option header */ uint8_t nd_opt_type; uint8_t nd_opt_len; /* followed by option specific data*/ }; #define ND_OPT_SOURCE_LINKADDR 1 #define ND_OPT_TARGET_LINKADDR 2 #define ND_OPT_PREFIX_INFORMATION 3 #define ND_OPT_REDIRECTED_HEADER 4 #define ND_OPT_MTU 5 #define ND_OPT_ADVINTERVAL 7 #define ND_OPT_HOMEAGENT_INFO 8 #define ND_OPT_ROUTE_INFO 24 /* RFC4191 */ #define ND_OPT_RDNSS 25 #define ND_OPT_DNSSL 31 struct nd_opt_prefix_info { /* prefix information */ nd_uint8_t nd_opt_pi_type; nd_uint8_t nd_opt_pi_len; nd_uint8_t nd_opt_pi_prefix_len; nd_uint8_t nd_opt_pi_flags_reserved; nd_uint32_t nd_opt_pi_valid_time; nd_uint32_t nd_opt_pi_preferred_time; nd_uint32_t nd_opt_pi_reserved2; struct in6_addr nd_opt_pi_prefix; }; #define ND_OPT_PI_FLAG_ONLINK 0x80 #define ND_OPT_PI_FLAG_AUTO 0x40 #define ND_OPT_PI_FLAG_ROUTER 0x20 /*2292bis*/ struct nd_opt_rd_hdr { /* redirected header */ uint8_t nd_opt_rh_type; uint8_t nd_opt_rh_len; uint16_t nd_opt_rh_reserved1; uint32_t nd_opt_rh_reserved2; /* followed by IP header and data */ }; struct nd_opt_mtu { /* MTU option */ uint8_t nd_opt_mtu_type; uint8_t nd_opt_mtu_len; uint16_t nd_opt_mtu_reserved; uint32_t nd_opt_mtu_mtu; }; struct nd_opt_rdnss { /* RDNSS RFC 6106 5.1 */ uint8_t nd_opt_rdnss_type; uint8_t nd_opt_rdnss_len; uint16_t nd_opt_rdnss_reserved; uint32_t nd_opt_rdnss_lifetime; struct in6_addr nd_opt_rdnss_addr[1]; /* variable-length */ }; struct nd_opt_dnssl { /* DNSSL RFC 6106 5.2 */ uint8_t nd_opt_dnssl_type; uint8_t nd_opt_dnssl_len; uint16_t nd_opt_dnssl_reserved; uint32_t nd_opt_dnssl_lifetime; /* followed by list of DNS search domains, variable-length */ }; struct nd_opt_advinterval { /* Advertisement interval option */ uint8_t nd_opt_adv_type; uint8_t nd_opt_adv_len; uint16_t nd_opt_adv_reserved; uint32_t nd_opt_adv_interval; }; struct nd_opt_homeagent_info { /* Home Agent info */ uint8_t nd_opt_hai_type; uint8_t nd_opt_hai_len; uint16_t nd_opt_hai_reserved; int16_t nd_opt_hai_preference; uint16_t nd_opt_hai_lifetime; }; struct nd_opt_route_info { /* route info */ uint8_t nd_opt_rti_type; uint8_t nd_opt_rti_len; uint8_t nd_opt_rti_prefixlen; uint8_t nd_opt_rti_flags; uint32_t nd_opt_rti_lifetime; /* prefix follows */ }; /* * icmp6 namelookup */ struct icmp6_namelookup { struct icmp6_hdr icmp6_nl_hdr; uint8_t icmp6_nl_nonce[8]; int32_t icmp6_nl_ttl; #if 0 uint8_t icmp6_nl_len; uint8_t icmp6_nl_name[3]; #endif /* could be followed by options */ }; /* * icmp6 node information */ struct icmp6_nodeinfo { struct icmp6_hdr icmp6_ni_hdr; uint8_t icmp6_ni_nonce[8]; /* could be followed by reply data */ }; #define ni_type icmp6_ni_hdr.icmp6_type #define ni_code icmp6_ni_hdr.icmp6_code #define ni_cksum icmp6_ni_hdr.icmp6_cksum #define ni_qtype icmp6_ni_hdr.icmp6_data16[0] #define ni_flags icmp6_ni_hdr.icmp6_data16[1] #define NI_QTYPE_NOOP 0 /* NOOP */ #define NI_QTYPE_SUPTYPES 1 /* Supported Qtypes */ #define NI_QTYPE_FQDN 2 /* FQDN (draft 04) */ #define NI_QTYPE_DNSNAME 2 /* DNS Name */ #define NI_QTYPE_NODEADDR 3 /* Node Addresses */ #define NI_QTYPE_IPV4ADDR 4 /* IPv4 Addresses */ /* network endian */ #define NI_SUPTYPE_FLAG_COMPRESS ((uint16_t)htons(0x1)) #define NI_FQDN_FLAG_VALIDTTL ((uint16_t)htons(0x1)) /* network endian */ #define NI_NODEADDR_FLAG_TRUNCATE ((uint16_t)htons(0x1)) #define NI_NODEADDR_FLAG_ALL ((uint16_t)htons(0x2)) #define NI_NODEADDR_FLAG_COMPAT ((uint16_t)htons(0x4)) #define NI_NODEADDR_FLAG_LINKLOCAL ((uint16_t)htons(0x8)) #define NI_NODEADDR_FLAG_SITELOCAL ((uint16_t)htons(0x10)) #define NI_NODEADDR_FLAG_GLOBAL ((uint16_t)htons(0x20)) #define NI_NODEADDR_FLAG_ANYCAST ((uint16_t)htons(0x40)) /* just experimental. not in spec */ struct ni_reply_fqdn { uint32_t ni_fqdn_ttl; /* TTL */ uint8_t ni_fqdn_namelen; /* length in octets of the FQDN */ uint8_t ni_fqdn_name[3]; /* XXX: alignment */ }; /* * Router Renumbering. as router-renum-08.txt */ struct icmp6_router_renum { /* router renumbering header */ struct icmp6_hdr rr_hdr; uint8_t rr_segnum; uint8_t rr_flags; uint16_t rr_maxdelay; uint32_t rr_reserved; }; #define ICMP6_RR_FLAGS_TEST 0x80 #define ICMP6_RR_FLAGS_REQRESULT 0x40 #define ICMP6_RR_FLAGS_FORCEAPPLY 0x20 #define ICMP6_RR_FLAGS_SPECSITE 0x10 #define ICMP6_RR_FLAGS_PREVDONE 0x08 #define rr_type rr_hdr.icmp6_type #define rr_code rr_hdr.icmp6_code #define rr_cksum rr_hdr.icmp6_cksum #define rr_seqnum rr_hdr.icmp6_data32[0] struct rr_pco_match { /* match prefix part */ uint8_t rpm_code; uint8_t rpm_len; uint8_t rpm_ordinal; uint8_t rpm_matchlen; uint8_t rpm_minlen; uint8_t rpm_maxlen; uint16_t rpm_reserved; struct in6_addr rpm_prefix; }; #define RPM_PCO_ADD 1 #define RPM_PCO_CHANGE 2 #define RPM_PCO_SETGLOBAL 3 #define RPM_PCO_MAX 4 struct rr_pco_use { /* use prefix part */ uint8_t rpu_uselen; uint8_t rpu_keeplen; uint8_t rpu_ramask; uint8_t rpu_raflags; uint32_t rpu_vltime; uint32_t rpu_pltime; uint32_t rpu_flags; struct in6_addr rpu_prefix; }; #define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x80 #define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x40 /* network endian */ #define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME ((uint32_t)htonl(0x80000000)) #define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME ((uint32_t)htonl(0x40000000)) struct rr_result { /* router renumbering result message */ uint16_t rrr_flags; uint8_t rrr_ordinal; uint8_t rrr_matchedlen; uint32_t rrr_ifid; struct in6_addr rrr_prefix; }; /* network endian */ #define ICMP6_RR_RESULT_FLAGS_OOB ((uint16_t)htons(0x0002)) #define ICMP6_RR_RESULT_FLAGS_FORBIDDEN ((uint16_t)htons(0x0001)) static const char *get_rtpref(u_int); static const char *get_lifetime(uint32_t); static void print_lladdr(netdissect_options *ndo, const u_char *, size_t); static void icmp6_opt_print(netdissect_options *ndo, const u_char *, int); static void mld6_print(netdissect_options *ndo, const u_char *); static void mldv2_report_print(netdissect_options *ndo, const u_char *, u_int); static void mldv2_query_print(netdissect_options *ndo, const u_char *, u_int); static const struct udphdr *get_upperlayer(netdissect_options *ndo, const u_char *, u_int *); static void dnsname_print(netdissect_options *ndo, const u_char *, const u_char *); static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int, const u_char *, const u_char *); static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *, const u_char *); #ifndef abs #define abs(a) ((0 < (a)) ? (a) : -(a)) #endif #include "rpl.h" static const struct tok icmp6_type_values[] = { { ICMP6_DST_UNREACH, "destination unreachable"}, { ICMP6_PACKET_TOO_BIG, "packet too big"}, { ICMP6_TIME_EXCEEDED, "time exceeded in-transit"}, { ICMP6_PARAM_PROB, "parameter problem"}, { ICMP6_ECHO_REQUEST, "echo request"}, { ICMP6_ECHO_REPLY, "echo reply"}, { MLD6_LISTENER_QUERY, "multicast listener query"}, { MLD6_LISTENER_REPORT, "multicast listener report"}, { MLD6_LISTENER_DONE, "multicast listener done"}, { ND_ROUTER_SOLICIT, "router solicitation"}, { ND_ROUTER_ADVERT, "router advertisement"}, { ND_NEIGHBOR_SOLICIT, "neighbor solicitation"}, { ND_NEIGHBOR_ADVERT, "neighbor advertisement"}, { ND_REDIRECT, "redirect"}, { ICMP6_ROUTER_RENUMBERING, "router renumbering"}, { IND_SOLICIT, "inverse neighbor solicitation"}, { IND_ADVERT, "inverse neighbor advertisement"}, { MLDV2_LISTENER_REPORT, "multicast listener report v2"}, { ICMP6_HADISCOV_REQUEST, "ha discovery request"}, { ICMP6_HADISCOV_REPLY, "ha discovery reply"}, { ICMP6_MOBILEPREFIX_SOLICIT, "mobile router solicitation"}, { ICMP6_MOBILEPREFIX_ADVERT, "mobile router advertisement"}, { ICMP6_WRUREQUEST, "who-are-you request"}, { ICMP6_WRUREPLY, "who-are-you reply"}, { ICMP6_NI_QUERY, "node information query"}, { ICMP6_NI_REPLY, "node information reply"}, { MLD6_MTRACE, "mtrace message"}, { MLD6_MTRACE_RESP, "mtrace response"}, { ND_RPL_MESSAGE, "RPL"}, { 0, NULL } }; static const struct tok icmp6_dst_unreach_code_values[] = { { ICMP6_DST_UNREACH_NOROUTE, "unreachable route" }, { ICMP6_DST_UNREACH_ADMIN, " unreachable prohibited"}, { ICMP6_DST_UNREACH_BEYONDSCOPE, "beyond scope"}, { ICMP6_DST_UNREACH_ADDR, "unreachable address"}, { ICMP6_DST_UNREACH_NOPORT, "unreachable port"}, { 0, NULL } }; static const struct tok icmp6_opt_pi_flag_values[] = { { ND_OPT_PI_FLAG_ONLINK, "onlink" }, { ND_OPT_PI_FLAG_AUTO, "auto" }, { ND_OPT_PI_FLAG_ROUTER, "router" }, { 0, NULL } }; static const struct tok icmp6_opt_ra_flag_values[] = { { ND_RA_FLAG_MANAGED, "managed" }, { ND_RA_FLAG_OTHER, "other stateful"}, { ND_RA_FLAG_HOME_AGENT, "home agent"}, { 0, NULL } }; static const struct tok icmp6_nd_na_flag_values[] = { { ND_NA_FLAG_ROUTER, "router" }, { ND_NA_FLAG_SOLICITED, "solicited" }, { ND_NA_FLAG_OVERRIDE, "override" }, { 0, NULL } }; static const struct tok icmp6_opt_values[] = { { ND_OPT_SOURCE_LINKADDR, "source link-address"}, { ND_OPT_TARGET_LINKADDR, "destination link-address"}, { ND_OPT_PREFIX_INFORMATION, "prefix info"}, { ND_OPT_REDIRECTED_HEADER, "redirected header"}, { ND_OPT_MTU, "mtu"}, { ND_OPT_RDNSS, "rdnss"}, { ND_OPT_DNSSL, "dnssl"}, { ND_OPT_ADVINTERVAL, "advertisement interval"}, { ND_OPT_HOMEAGENT_INFO, "homeagent information"}, { ND_OPT_ROUTE_INFO, "route info"}, { 0, NULL } }; /* mldv2 report types */ static const struct tok mldv2report2str[] = { { 1, "is_in" }, { 2, "is_ex" }, { 3, "to_in" }, { 4, "to_ex" }, { 5, "allow" }, { 6, "block" }, { 0, NULL } }; static const char * get_rtpref(u_int v) { static const char *rtpref_str[] = { "medium", /* 00 */ "high", /* 01 */ "rsv", /* 10 */ "low" /* 11 */ }; return rtpref_str[((v & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff]; } static const char * get_lifetime(uint32_t v) { static char buf[20]; if (v == (uint32_t)~0UL) return "infinity"; else { snprintf(buf, sizeof(buf), "%us", v); return buf; } } static void print_lladdr(netdissect_options *ndo, const uint8_t *p, size_t l) { const uint8_t *ep, *q; q = p; ep = p + l; while (l > 0 && q < ep) { if (q > p) ND_PRINT((ndo,":")); ND_PRINT((ndo,"%02x", *q++)); l--; } } static int icmp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6, const struct icmp6_hdr *icp, u_int len) { return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)icp, len, len, IPPROTO_ICMPV6); } static const struct tok rpl_mop_values[] = { { RPL_DIO_NONSTORING, "nonstoring"}, { RPL_DIO_STORING, "storing"}, { RPL_DIO_NONSTORING_MULTICAST, "nonstoring-multicast"}, { RPL_DIO_STORING_MULTICAST, "storing-multicast"}, { 0, NULL}, }; static const struct tok rpl_subopt_values[] = { { RPL_OPT_PAD0, "pad0"}, { RPL_OPT_PADN, "padN"}, { RPL_DIO_METRICS, "metrics"}, { RPL_DIO_ROUTINGINFO, "routinginfo"}, { RPL_DIO_CONFIG, "config"}, { RPL_DAO_RPLTARGET, "rpltarget"}, { RPL_DAO_TRANSITINFO, "transitinfo"}, { RPL_DIO_DESTPREFIX, "destprefix"}, { RPL_DAO_RPLTARGET_DESC, "rpltargetdesc"}, { 0, NULL}, }; static void rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; ND_TCHECK(opt->rpl_dio_len); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; } static void rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; } static void rpl_dao_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp; const char *dagid_str = "<elided>"; ND_TCHECK(*dao); if (length < ND_RPL_DAO_MIN_LEN) goto tooshort; bp += ND_RPL_DAO_MIN_LEN; length -= ND_RPL_DAO_MIN_LEN; if(RPL_DAO_D(dao->rpl_flags)) { ND_TCHECK2(dao->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, dao->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]", dagid_str, dao->rpl_daoseq, dao->rpl_instanceid, RPL_DAO_K(dao->rpl_flags) ? ",acK":"", RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"", dao->rpl_flags)); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; tooshort: ND_PRINT((ndo," [|length too short]")); return; } static void rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; } static void rpl_print(netdissect_options *ndo, const struct icmp6_hdr *hdr, const u_char *bp, u_int length) { int secured = hdr->icmp6_code & 0x80; int basecode= hdr->icmp6_code & 0x7f; if(secured) { ND_PRINT((ndo, ", (SEC) [worktodo]")); /* XXX * the next header pointer needs to move forward to * skip the secure part. */ return; } else { ND_PRINT((ndo, ", (CLR)")); } switch(basecode) { case ND_RPL_DAG_IS: ND_PRINT((ndo, "DODAG Information Solicitation")); if(ndo->ndo_vflag) { } break; case ND_RPL_DAG_IO: ND_PRINT((ndo, "DODAG Information Object")); if(ndo->ndo_vflag) { rpl_dio_print(ndo, bp, length); } break; case ND_RPL_DAO: ND_PRINT((ndo, "Destination Advertisement Object")); if(ndo->ndo_vflag) { rpl_dao_print(ndo, bp, length); } break; case ND_RPL_DAO_ACK: ND_PRINT((ndo, "Destination Advertisement Object Ack")); if(ndo->ndo_vflag) { rpl_daoack_print(ndo, bp, length); } break; default: ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code)); break; } return; #if 0 trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; #endif } void icmp6_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, int fragmented) { const struct icmp6_hdr *dp; const struct ip6_hdr *ip; const struct ip6_hdr *oip; const struct udphdr *ouh; int dport; const u_char *ep; u_int prot; dp = (const struct icmp6_hdr *)bp; ip = (const struct ip6_hdr *)bp2; oip = (const struct ip6_hdr *)(dp + 1); /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->icmp6_cksum); if (ndo->ndo_vflag && !fragmented) { uint16_t sum, udp_sum; if (ND_TTEST2(bp[0], length)) { udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum); sum = icmp6_cksum(ndo, ip, dp, length); if (sum != 0) ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ", udp_sum, in_cksum_shouldbe(udp_sum, sum))); else ND_PRINT((ndo,"[icmp6 sum ok] ")); } } ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type))); /* display cosmetics: print the packet length for printer that use the vflag now */ if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT || dp->icmp6_type == ND_ROUTER_ADVERT || dp->icmp6_type == ND_NEIGHBOR_ADVERT || dp->icmp6_type == ND_NEIGHBOR_SOLICIT || dp->icmp6_type == ND_REDIRECT || dp->icmp6_type == ICMP6_HADISCOV_REPLY || dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT )) ND_PRINT((ndo,", length %u", length)); switch (dp->icmp6_type) { case ICMP6_DST_UNREACH: ND_TCHECK(oip->ip6_dst); ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code))); switch (dp->icmp6_code) { case ICMP6_DST_UNREACH_NOROUTE: /* fall through */ case ICMP6_DST_UNREACH_ADMIN: case ICMP6_DST_UNREACH_ADDR: ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst))); break; case ICMP6_DST_UNREACH_BEYONDSCOPE: ND_PRINT((ndo," %s, source address %s", ip6addr_string(ndo, &oip->ip6_dst), ip6addr_string(ndo, &oip->ip6_src))); break; case ICMP6_DST_UNREACH_NOPORT: if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot)) == NULL) goto trunc; dport = EXTRACT_16BITS(&ouh->uh_dport); switch (prot) { case IPPROTO_TCP: ND_PRINT((ndo,", %s tcp port %s", ip6addr_string(ndo, &oip->ip6_dst), tcpport_string(ndo, dport))); break; case IPPROTO_UDP: ND_PRINT((ndo,", %s udp port %s", ip6addr_string(ndo, &oip->ip6_dst), udpport_string(ndo, dport))); break; default: ND_PRINT((ndo,", %s protocol %d port %d unreachable", ip6addr_string(ndo, &oip->ip6_dst), oip->ip6_nxt, dport)); break; } break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, bp,"\n\t",length); return; } break; } break; case ICMP6_PACKET_TOO_BIG: ND_TCHECK(dp->icmp6_mtu); ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu))); break; case ICMP6_TIME_EXCEEDED: ND_TCHECK(oip->ip6_dst); switch (dp->icmp6_code) { case ICMP6_TIME_EXCEED_TRANSIT: ND_PRINT((ndo," for %s", ip6addr_string(ndo, &oip->ip6_dst))); break; case ICMP6_TIME_EXCEED_REASSEMBLY: ND_PRINT((ndo," (reassembly)")); break; default: ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code)); break; } break; case ICMP6_PARAM_PROB: ND_TCHECK(oip->ip6_dst); switch (dp->icmp6_code) { case ICMP6_PARAMPROB_HEADER: ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; case ICMP6_PARAMPROB_NEXTHEADER: ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; case ICMP6_PARAMPROB_OPTION: ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr))); break; default: ND_PRINT((ndo,", code-#%d", dp->icmp6_code)); break; } break; case ICMP6_ECHO_REQUEST: case ICMP6_ECHO_REPLY: ND_TCHECK(dp->icmp6_seq); ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq))); break; case ICMP6_MEMBERSHIP_QUERY: if (length == MLD_MINLEN) { mld6_print(ndo, (const u_char *)dp); } else if (length >= MLDV2_MINLEN) { ND_PRINT((ndo," v2")); mldv2_query_print(ndo, (const u_char *)dp, length); } else { ND_PRINT((ndo," unknown-version (len %u) ", length)); } break; case ICMP6_MEMBERSHIP_REPORT: mld6_print(ndo, (const u_char *)dp); break; case ICMP6_MEMBERSHIP_REDUCTION: mld6_print(ndo, (const u_char *)dp); break; case ND_ROUTER_SOLICIT: #define RTSOLLEN 8 if (ndo->ndo_vflag) { icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN, length - RTSOLLEN); } break; case ND_ROUTER_ADVERT: #define RTADVLEN 16 if (ndo->ndo_vflag) { const struct nd_router_advert *p; p = (const struct nd_router_advert *)dp; ND_TCHECK(p->nd_ra_retransmit); ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \ ", pref %s, router lifetime %us, reachable time %ums, retrans timer %ums", (u_int)p->nd_ra_curhoplimit, bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)), get_rtpref(p->nd_ra_flags_reserved), EXTRACT_16BITS(&p->nd_ra_router_lifetime), EXTRACT_32BITS(&p->nd_ra_reachable), EXTRACT_32BITS(&p->nd_ra_retransmit))); icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN, length - RTADVLEN); } break; case ND_NEIGHBOR_SOLICIT: { const struct nd_neighbor_solicit *p; p = (const struct nd_neighbor_solicit *)dp; ND_TCHECK(p->nd_ns_target); ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target))); if (ndo->ndo_vflag) { #define NDSOLLEN 24 icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN, length - NDSOLLEN); } } break; case ND_NEIGHBOR_ADVERT: { const struct nd_neighbor_advert *p; p = (const struct nd_neighbor_advert *)dp; ND_TCHECK(p->nd_na_target); ND_PRINT((ndo,", tgt is %s", ip6addr_string(ndo, &p->nd_na_target))); if (ndo->ndo_vflag) { ND_PRINT((ndo,", Flags [%s]", bittok2str(icmp6_nd_na_flag_values, "none", EXTRACT_32BITS(&p->nd_na_flags_reserved)))); #define NDADVLEN 24 icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN, length - NDADVLEN); #undef NDADVLEN } } break; case ND_REDIRECT: #define RDR(i) ((const struct nd_redirect *)(i)) ND_TCHECK(RDR(dp)->nd_rd_dst); ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst))); ND_TCHECK(RDR(dp)->nd_rd_target); ND_PRINT((ndo," to %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_target))); #define REDIRECTLEN 40 if (ndo->ndo_vflag) { icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN, length - REDIRECTLEN); } break; #undef REDIRECTLEN #undef RDR case ICMP6_ROUTER_RENUMBERING: icmp6_rrenum_print(ndo, bp, ep); break; case ICMP6_NI_QUERY: case ICMP6_NI_REPLY: icmp6_nodeinfo_print(ndo, length, bp, ep); break; case IND_SOLICIT: case IND_ADVERT: break; case ICMP6_V2_MEMBERSHIP_REPORT: mldv2_report_print(ndo, (const u_char *) dp, length); break; case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */ case ICMP6_HADISCOV_REQUEST: ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); break; case ICMP6_HADISCOV_REPLY: if (ndo->ndo_vflag) { const struct in6_addr *in6; const u_char *cp; ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); cp = (const u_char *)dp + length; in6 = (const struct in6_addr *)(dp + 1); for (; (const u_char *)in6 < cp; in6++) { ND_TCHECK(*in6); ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6))); } } break; case ICMP6_MOBILEPREFIX_ADVERT: if (ndo->ndo_vflag) { ND_TCHECK(dp->icmp6_data16[0]); ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0]))); ND_TCHECK(dp->icmp6_data16[1]); if (dp->icmp6_data16[1] & 0xc0) ND_PRINT((ndo," ")); if (dp->icmp6_data16[1] & 0x80) ND_PRINT((ndo,"M")); if (dp->icmp6_data16[1] & 0x40) ND_PRINT((ndo,"O")); #define MPADVLEN 8 icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN, length - MPADVLEN); } break; case ND_RPL_MESSAGE: /* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */ rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4); break; default: ND_PRINT((ndo,", length %u", length)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp,"\n\t", length); return; } if (!ndo->ndo_vflag) ND_PRINT((ndo,", length %u", length)); return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); } static const struct udphdr * get_upperlayer(netdissect_options *ndo, const u_char *bp, u_int *prot) { const u_char *ep; const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp; const struct udphdr *uh; const struct ip6_hbh *hbh; const struct ip6_frag *fragh; const struct ah *ah; u_int nh; int hlen; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(ip6->ip6_nxt)) return NULL; nh = ip6->ip6_nxt; hlen = sizeof(struct ip6_hdr); while (bp < ep) { bp += hlen; switch(nh) { case IPPROTO_UDP: case IPPROTO_TCP: uh = (const struct udphdr *)bp; if (ND_TTEST(uh->uh_dport)) { *prot = nh; return(uh); } else return(NULL); /* NOTREACHED */ case IPPROTO_HOPOPTS: case IPPROTO_DSTOPTS: case IPPROTO_ROUTING: hbh = (const struct ip6_hbh *)bp; if (!ND_TTEST(hbh->ip6h_len)) return(NULL); nh = hbh->ip6h_nxt; hlen = (hbh->ip6h_len + 1) << 3; break; case IPPROTO_FRAGMENT: /* this should be odd, but try anyway */ fragh = (const struct ip6_frag *)bp; if (!ND_TTEST(fragh->ip6f_offlg)) return(NULL); /* fragments with non-zero offset are meaningless */ if ((EXTRACT_16BITS(&fragh->ip6f_offlg) & IP6F_OFF_MASK) != 0) return(NULL); nh = fragh->ip6f_nxt; hlen = sizeof(struct ip6_frag); break; case IPPROTO_AH: ah = (const struct ah *)bp; if (!ND_TTEST(ah->ah_len)) return(NULL); nh = ah->ah_nxt; hlen = (ah->ah_len + 2) << 2; break; default: /* unknown or undecodable header */ *prot = nh; /* meaningless, but set here anyway */ return(NULL); } } return(NULL); /* should be notreached, though */ } static void icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid) { const struct nd_opt_hdr *op; const struct nd_opt_prefix_info *opp; const struct nd_opt_mtu *opm; const struct nd_opt_rdnss *oprd; const struct nd_opt_dnssl *opds; const struct nd_opt_advinterval *opa; const struct nd_opt_homeagent_info *oph; const struct nd_opt_route_info *opri; const u_char *cp, *ep, *domp; struct in6_addr in6; const struct in6_addr *in6p; size_t l; u_int i; #define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return cp = bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; while (cp < ep) { op = (const struct nd_opt_hdr *)cp; ECHECK(op->nd_opt_len); if (resid <= 0) return; if (op->nd_opt_len == 0) goto trunc; if (cp + (op->nd_opt_len << 3) > ep) goto trunc; ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ", tok2str(icmp6_opt_values, "unknown", op->nd_opt_type), op->nd_opt_type, op->nd_opt_len << 3, op->nd_opt_len)); switch (op->nd_opt_type) { case ND_OPT_SOURCE_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_TARGET_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_PREFIX_INFORMATION: opp = (const struct nd_opt_prefix_info *)op; ND_TCHECK(opp->nd_opt_pi_prefix); ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s", ip6addr_string(ndo, &opp->nd_opt_pi_prefix), opp->nd_opt_pi_prefix_len, (op->nd_opt_len != 4) ? "badlen" : "", bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved), get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time)))); ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time)))); break; case ND_OPT_REDIRECTED_HEADER: print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3); /* xxx */ break; case ND_OPT_MTU: opm = (const struct nd_opt_mtu *)op; ND_TCHECK(opm->nd_opt_mtu_mtu); ND_PRINT((ndo," %u%s", EXTRACT_32BITS(&opm->nd_opt_mtu_mtu), (op->nd_opt_len != 1) ? "bad option length" : "" )); break; case ND_OPT_RDNSS: oprd = (const struct nd_opt_rdnss *)op; l = (op->nd_opt_len - 1) / 2; ND_PRINT((ndo," lifetime %us,", EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime))); for (i = 0; i < l; i++) { ND_TCHECK(oprd->nd_opt_rdnss_addr[i]); ND_PRINT((ndo," addr: %s", ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i]))); } break; case ND_OPT_DNSSL: opds = (const struct nd_opt_dnssl *)op; ND_PRINT((ndo," lifetime %us, domain(s):", EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime))); domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */ while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0') { ND_PRINT((ndo, " ")); if ((domp = ns_nprint (ndo, domp, bp)) == NULL) goto trunc; } break; case ND_OPT_ADVINTERVAL: opa = (const struct nd_opt_advinterval *)op; ND_TCHECK(opa->nd_opt_adv_interval); ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval))); break; case ND_OPT_HOMEAGENT_INFO: oph = (const struct nd_opt_homeagent_info *)op; ND_TCHECK(oph->nd_opt_hai_lifetime); ND_PRINT((ndo," preference %u, lifetime %u", EXTRACT_16BITS(&oph->nd_opt_hai_preference), EXTRACT_16BITS(&oph->nd_opt_hai_lifetime))); break; case ND_OPT_ROUTE_INFO: opri = (const struct nd_opt_route_info *)op; ND_TCHECK(opri->nd_opt_rti_lifetime); memset(&in6, 0, sizeof(in6)); in6p = (const struct in6_addr *)(opri + 1); switch (op->nd_opt_len) { case 1: break; case 2: ND_TCHECK2(*in6p, 8); memcpy(&in6, opri + 1, 8); break; case 3: ND_TCHECK(*in6p); memcpy(&in6, opri + 1, sizeof(in6)); break; default: goto trunc; } ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6), opri->nd_opt_rti_prefixlen)); ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags))); ND_PRINT((ndo,", lifetime=%s", get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime)))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ return; } break; } /* do we want to see an additional hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ cp += op->nd_opt_len << 3; resid -= op->nd_opt_len << 3; } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); return; #undef ECHECK } static void mld6_print(netdissect_options *ndo, const u_char *bp) { const struct mld6_hdr *mp = (const struct mld6_hdr *)bp; const u_char *ep; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if ((const u_char *)mp + sizeof(*mp) > ep) return; ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay))); ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr))); } static void mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int group, nsrcs, ngroups; u_int i, j; /* Minimum len is 8 */ if (len < 8) { ND_PRINT((ndo," [invalid len %d]", len)); return; } ND_TCHECK(icp->icmp6_data16[1]); ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]); ND_PRINT((ndo,", %d group record(s)", ngroups)); if (ndo->ndo_vflag > 0) { /* Print the group records */ group = 8; for (i = 0; i < ngroups; i++) { /* type(1) + auxlen(1) + numsrc(2) + grp(16) */ if (len < group + 20) { ND_PRINT((ndo," [invalid number of groups]")); return; } ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr)); ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4]))); ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]", bp[group]))); nsrcs = (bp[group + 2] << 8) + bp[group + 3]; /* Check the number of sources and print them */ if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) { ND_PRINT((ndo," [invalid number of sources %d]", nsrcs)); return; } if (ndo->ndo_vflag == 1) ND_PRINT((ndo,", %d source(s)", nsrcs)); else { /* Print the sources */ ND_PRINT((ndo," {")); for (j = 0; j < nsrcs; j++) { ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)]))); } ND_PRINT((ndo," }")); } /* Next group record */ group += 20 + nsrcs * sizeof(struct in6_addr); ND_PRINT((ndo,"]")); } } return; trunc: ND_PRINT((ndo, "%s", mldv2_tstr)); return; } static void mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int mrc; int mrt, qqi; u_int nsrcs; register u_int i; /* Minimum len is 28 */ if (len < 28) { ND_PRINT((ndo," [invalid len %d]", len)); return; } ND_TCHECK(icp->icmp6_data16[0]); mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]); if (mrc < 32768) { mrt = mrc; } else { mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3); } if (ndo->ndo_vflag) { ND_PRINT((ndo," [max resp delay=%d]", mrt)); } ND_TCHECK2(bp[8], sizeof(struct in6_addr)); ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8]))); if (ndo->ndo_vflag) { ND_TCHECK(bp[25]); if (bp[24] & 0x08) { ND_PRINT((ndo," sflag")); } if (bp[24] & 0x07) { ND_PRINT((ndo," robustness=%d", bp[24] & 0x07)); } if (bp[25] < 128) { qqi = bp[25]; } else { qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3); } ND_PRINT((ndo," qqi=%d", qqi)); } ND_TCHECK2(bp[26], 2); nsrcs = EXTRACT_16BITS(&bp[26]); if (nsrcs > 0) { if (len < 28 + nsrcs * sizeof(struct in6_addr)) ND_PRINT((ndo," [invalid number of sources]")); else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo," {")); for (i = 0; i < nsrcs; i++) { ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)]))); } ND_PRINT((ndo," }")); } else ND_PRINT((ndo,", %d source(s)", nsrcs)); } ND_PRINT((ndo,"]")); return; trunc: ND_PRINT((ndo, "%s", mldv2_tstr)); return; } static void dnsname_print(netdissect_options *ndo, const u_char *cp, const u_char *ep) { int i; /* DNS name decoding - no decompression */ ND_PRINT((ndo,", \"")); while (cp < ep) { i = *cp++; if (i) { if (i > ep - cp) { ND_PRINT((ndo,"???")); break; } while (i-- && cp < ep) { safeputchar(ndo, *cp); cp++; } if (cp + 1 < ep && *cp) ND_PRINT((ndo,".")); } else { if (cp == ep) { /* FQDN */ ND_PRINT((ndo,".")); } else if (cp + 1 == ep && *cp == '\0') { /* truncated */ } else { /* invalid */ ND_PRINT((ndo,"???")); } break; } } ND_PRINT((ndo,"\"")); } static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep) { const struct icmp6_nodeinfo *ni6; const struct icmp6_hdr *dp; const u_char *cp; size_t siz, i; int needcomma; if (ep < bp) return; dp = (const struct icmp6_hdr *)bp; ni6 = (const struct icmp6_nodeinfo *)bp; siz = ep - bp; switch (ni6->ni_type) { case ICMP6_NI_QUERY: if (siz == sizeof(*dp) + 4) { /* KAME who-are-you */ ND_PRINT((ndo," who-are-you request")); break; } ND_PRINT((ndo," node information query")); ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," (")); /*)*/ switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: ND_PRINT((ndo,"noop")); break; case NI_QTYPE_SUPTYPES: ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: ND_PRINT((ndo,"DNS name")); break; case NI_QTYPE_NODEADDR: ND_PRINT((ndo,"node addresses")); i = ni6->ni_flags; if (!i) break; /* NI_NODEADDR_FLAG_TRUNCATE undefined for query */ ND_PRINT((ndo," [%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "")); break; default: ND_PRINT((ndo,"unknown")); break; } if (ni6->ni_qtype == NI_QTYPE_NOOP || ni6->ni_qtype == NI_QTYPE_SUPTYPES) { if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid len")); /*(*/ ND_PRINT((ndo,")")); break; } /* XXX backward compat, icmp-name-lookup-03 */ if (siz == sizeof(*ni6)) { ND_PRINT((ndo,", 03 draft")); /*(*/ ND_PRINT((ndo,")")); break; } switch (ni6->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in6_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ip6addr_string(ndo, ni6 + 1))); break; case ICMP6_NI_SUBJ_FQDN: ND_PRINT((ndo,", subject=DNS name")); cp = (const u_char *)(ni6 + 1); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); break; case ICMP6_NI_SUBJ_IPV4: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ipaddr_string(ndo, ni6 + 1))); break; default: ND_PRINT((ndo,", unknown subject")); break; } /*(*/ ND_PRINT((ndo,")")); break; case ICMP6_NI_REPLY: if (icmp6len > siz) { ND_PRINT((ndo,"[|icmp6: node information reply]")); break; } needcomma = 0; ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," node information reply")); ND_PRINT((ndo," (")); /*)*/ switch (ni6->ni_code) { case ICMP6_NI_SUCCESS: if (ndo->ndo_vflag) { ND_PRINT((ndo,"success")); needcomma++; } break; case ICMP6_NI_REFUSED: ND_PRINT((ndo,"refused")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case ICMP6_NI_UNKNOWN: ND_PRINT((ndo,"unknown")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; } if (ni6->ni_code != ICMP6_NI_SUCCESS) { /*(*/ ND_PRINT((ndo,")")); break; } switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"noop")); if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case NI_QTYPE_SUPTYPES: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"DNS name")); cp = (const u_char *)(ni6 + 1) + 4; ND_TCHECK(cp[0]); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0) ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1))); break; case NI_QTYPE_NODEADDR: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"node addresses")); i = sizeof(*ni6); while (i < siz) { if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz) break; ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i))); i += sizeof(struct in6_addr); ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i))); i += sizeof(int32_t); } i = ni6->ni_flags; if (!i) break; ND_PRINT((ndo," [%s%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "", (i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : "")); break; default: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"unknown")); break; } /*(*/ ND_PRINT((ndo,")")); break; } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); } static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep) { const struct icmp6_router_renum *rr6; const char *cp; const struct rr_pco_match *match; const struct rr_pco_use *use; char hbuf[NI_MAXHOST]; int n; if (ep < bp) return; rr6 = (const struct icmp6_router_renum *)bp; cp = (const char *)(rr6 + 1); ND_TCHECK(rr6->rr_reserved); switch (rr6->rr_code) { case ICMP6_ROUTER_RENUMBERING_COMMAND: ND_PRINT((ndo,"router renum: command")); break; case ICMP6_ROUTER_RENUMBERING_RESULT: ND_PRINT((ndo,"router renum: result")); break; case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET: ND_PRINT((ndo,"router renum: sequence number reset")); break; default: ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code)); break; } ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum))); if (ndo->ndo_vflag) { #define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "") ND_PRINT((ndo,"[")); /*]*/ if (rr6->rr_flags) { ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"), F(ICMP6_RR_FLAGS_REQRESULT, "R"), F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"), F(ICMP6_RR_FLAGS_SPECSITE, "S"), F(ICMP6_RR_FLAGS_PREVDONE, "P"))); } ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum)); ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay))); if (rr6->rr_reserved) ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved))); /*[*/ ND_PRINT((ndo,"]")); #undef F } if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) { match = (const struct rr_pco_match *)cp; cp = (const char *)(match + 1); ND_TCHECK(match->rpm_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"match(")); /*)*/ switch (match->rpm_code) { case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break; case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break; case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break; default: ND_PRINT((ndo,"#%u", match->rpm_code)); break; } if (ndo->ndo_vflag) { ND_PRINT((ndo,",ord=%u", match->rpm_ordinal)); ND_PRINT((ndo,",min=%u", match->rpm_minlen)); ND_PRINT((ndo,",max=%u", match->rpm_maxlen)); } if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen)); else ND_PRINT((ndo,",?/%u", match->rpm_matchlen)); /*(*/ ND_PRINT((ndo,")")); n = match->rpm_len - 3; if (n % 4) goto trunc; n /= 4; while (n-- > 0) { use = (const struct rr_pco_use *)cp; cp = (const char *)(use + 1); ND_TCHECK(use->rpu_prefix); if (ndo->ndo_vflag > 1) ND_PRINT((ndo,"\n\t")); else ND_PRINT((ndo," ")); ND_PRINT((ndo,"use(")); /*)*/ if (use->rpu_flags) { #define F(x, y) ((use->rpu_flags) & (x) ? (y) : "") ND_PRINT((ndo,"%s%s,", F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"), F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P"))); #undef F } if (ndo->ndo_vflag) { ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask)); ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags)); if (~use->rpu_vltime == 0) ND_PRINT((ndo,"vltime=infty,")); else ND_PRINT((ndo,"vltime=%u,", EXTRACT_32BITS(&use->rpu_vltime))); if (~use->rpu_pltime == 0) ND_PRINT((ndo,"pltime=infty,")); else ND_PRINT((ndo,"pltime=%u,", EXTRACT_32BITS(&use->rpu_pltime))); } if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf))) ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen, use->rpu_keeplen)); else ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen, use->rpu_keeplen)); /*(*/ ND_PRINT((ndo,")")); } } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_290_0
crossvul-cpp_data_good_3910_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.rdp") const char* DATA_PDU_TYPE_STRINGS[80] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout", /* 0x37 */ "FrameAcknowledge", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; static BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type); static void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id); static void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id); /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(wStream* s, UINT16* flags, UINT16* length) { /* Basic Security Header */ if ((Stream_GetRemainingLength(s) < 4) || (length && (*length < 4))) return FALSE; Stream_Read_UINT16(s, *flags); /* flags */ Stream_Seek(s, 2); /* flagsHi (unused) */ if (length) *length -= 4; return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(wStream* s, UINT16 flags) { /* Basic Security Header */ Stream_Write_UINT16(s, flags); /* flags */ Stream_Write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { UINT16 len; if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, len); /* totalLength */ *length = len; /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (len == 0x8000) { if (!rdp_read_flow_control_pdu(s, type)) return FALSE; *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s))) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (len > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ Stream_Write_UINT16(s, length); /* totalLength */ Stream_Write_UINT16(s, type | 0x10); /* pduType */ Stream_Write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(wStream* s, UINT16* length, BYTE* type, UINT32* shareId, BYTE* compressedType, UINT16* compressedLength) { if (Stream_GetRemainingLength(s) < 12) return FALSE; /* Share Data Header */ Stream_Read_UINT32(s, *shareId); /* shareId (4 bytes) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT8(s); /* streamId (1 byte) */ Stream_Read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ Stream_Read_UINT8(s, *type); /* pduType2, Data PDU Type (1 byte) */ Stream_Read_UINT8(s, *compressedType); /* compressedType (1 byte) */ Stream_Read_UINT16(s, *compressedLength); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ Stream_Write_UINT32(s, share_id); /* shareId (4 bytes) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT8(s, STREAM_LOW); /* streamId (1 byte) */ Stream_Write_UINT16(s, length); /* uncompressedLength (2 bytes) */ Stream_Write_UINT8(s, type); /* pduType2, Data PDU Type (1 byte) */ Stream_Write_UINT8(s, 0); /* compressedType (1 byte) */ Stream_Write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static BOOL rdp_security_stream_init(rdpRdp* rdp, wStream* s, BOOL sec_header) { if (!rdp || !s) return FALSE; if (rdp->do_crypt) { if (!Stream_SafeSeek(s, 12)) return FALSE; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { if (!Stream_SafeSeek(s, 4)) return FALSE; } rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0 || sec_header) { if (!Stream_SafeSeek(s, 4)) return FALSE; } return TRUE; } wStream* rdp_send_stream_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, FALSE)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_send_stream_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_CONTROL_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_data_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_DATA_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } BOOL rdp_set_error_info(rdpRdp* rdp, UINT32 errorInfo) { rdp->errorInfo = errorInfo; if (rdp->errorInfo != ERRINFO_SUCCESS) { rdpContext* context = rdp->context; rdp_print_errinfo(rdp->errorInfo); if (context) { freerdp_set_last_error_log(context, MAKE_FREERDP_ERROR(ERRINFO, errorInfo)); if (context->pubSub) { ErrorInfoEventArgs e; EventArgsInit(&e, "freerdp"); e.code = rdp->errorInfo; PubSub_OnErrorInfo(context->pubSub, context, &e); } } else WLog_ERR(TAG, "%s missing context=%p", __FUNCTION__, context); } else { freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SUCCESS); } return TRUE; } wStream* rdp_message_channel_pdu_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, TRUE)) goto fail; return s; fail: Stream_Release(s); return NULL; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, wStream* s, UINT16* length, UINT16* channelId) { BYTE li; BYTE byte; BYTE code; BYTE choice; UINT16 initiator; enum DomainMCSPDU MCSPDU; enum DomainMCSPDU domainMCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!tpkt_read_header(s, length)) return FALSE; if (!tpdu_read_header(s, &code, &li, *length)) return FALSE; if (code != X224_TPDU_DATA) { if (code == X224_TPDU_DISCONNECT_REQUEST) { freerdp_abort_connect(rdp->instance); return TRUE; } return FALSE; } if (!per_read_choice(s, &choice)) return FALSE; domainMCSPDU = (enum DomainMCSPDU)(choice >> 2); if (domainMCSPDU != MCSPDU) { if (domainMCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } MCSPDU = domainMCSPDU; if (*length < 8U) return FALSE; if ((*length - 8U) > Stream_GetRemainingLength(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { int reason = 0; TerminateEventArgs e; rdpContext* context; if (!mcs_recv_disconnect_provider_ultimatum(rdp->mcs, s, &reason)) return FALSE; if (!rdp->instance) return FALSE; context = rdp->instance->context; context->disconnectUltimatum = reason; if (rdp->errorInfo == ERRINFO_SUCCESS) { /** * Some servers like Windows Server 2008 R2 do not send the error info pdu * when the user logs off like they should. Map DisconnectProviderUltimatum * to a ERRINFO_LOGOFF_BY_USER when the errinfo code is ERRINFO_SUCCESS. */ if (reason == Disconnect_Ultimatum_provider_initiated) rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); else if (reason == Disconnect_Ultimatum_user_requested) rdp_set_error_info(rdp, ERRINFO_LOGOFF_BY_USER); else rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); } WLog_DBG(TAG, "DisconnectProviderUltimatum: reason: %d", reason); freerdp_abort_connect(rdp->instance); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); return TRUE; } if (Stream_GetRemainingLength(s) < 5) return FALSE; if (!per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID)) /* initiator (UserId) */ return FALSE; if (!per_read_integer16(s, channelId, 0)) /* channelId */ return FALSE; Stream_Read_UINT8(s, byte); /* dataPriority + Segmentation (0x70) */ if (!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > Stream_GetRemainingLength(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, wStream* s, UINT16 length, UINT16 channelId) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->userId, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channelId, 0); /* channelId */ Stream_Write_UINT8(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, even though we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; Stream_Write_UINT16_BE(s, length); /* userData (OCTET_STRING) */ } static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, int length, UINT32 sec_flags, UINT32* pad) { BYTE* data; BOOL status; sec_flags |= rdp->sec_flags; *pad = 0; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = Stream_Pointer(s) + 12; length = length - (data - Stream_Buffer(s)); Stream_Write_UINT16(s, 0x10); /* length */ Stream_Write_UINT8(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ *pad = 8 - (length % 8); if (*pad == 8) *pad = 0; if (*pad) memset(data + length, 0, *pad); Stream_Write_UINT8(s, *pad); if (!security_hmac_signature(data, length, Stream_Pointer(s), rdp)) return FALSE; Stream_Seek(s, 8); security_fips_encrypt(data, length + *pad, rdp); } else { data = Stream_Pointer(s) + 8; length = length - (data - Stream_Buffer(s)); if (sec_flags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, data, length, TRUE, Stream_Pointer(s)); else status = security_mac_signature(rdp, data, length, Stream_Pointer(s)); if (!status) return FALSE; Stream_Seek(s, 8); if (!security_encrypt(Stream_Pointer(s), length, rdp)) return FALSE; } } rdp->sec_flags = 0; } return TRUE; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp, UINT16 sec_flags) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0 || sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet. * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, wStream* s, UINT16 channel_id) { BOOL rc = FALSE; UINT32 pad; UINT16 length; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, channel_id); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_pdu(rdpRdp* rdp, wStream* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!rdp || !s) return FALSE; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) return FALSE; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, wStream* s, BYTE type, UINT16 channel_id) { BOOL rc = FALSE; size_t length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); WLog_DBG(TAG, "%s: sending data (type=0x%x size=%" PRIuz " channelId=%" PRIu16 ")", __FUNCTION__, type, Stream_Length(s), channel_id); rdp->outPackets++; if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags) { BOOL rc = FALSE; UINT16 length; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId); if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } static BOOL rdp_recv_server_shutdown_denied_pdu(rdpRdp* rdp, wStream* s) { return TRUE; } static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT16 ledFlags; rdpContext* context = rdp->instance->context; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */ IFCALL(context->update->SetKeyboardIndicators, context, ledFlags); return TRUE; } static BOOL rdp_recv_server_set_keyboard_ime_status_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT32 imeState; UINT32 imeConvMode; if (!rdp || !rdp->input) return FALSE; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT32(s, imeState); /* imeState (4 bytes) */ Stream_Read_UINT32(s, imeConvMode); /* imeConvMode (4 bytes) */ IFCALL(rdp->update->SetKeyboardImeStatus, rdp->context, unitId, imeState, imeConvMode); return TRUE; } static BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, wStream* s) { UINT32 errorInfo; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, errorInfo); /* errorInfo (4 bytes) */ return rdp_set_error_info(rdp, errorInfo); } static BOOL rdp_recv_server_auto_reconnect_status_pdu(rdpRdp* rdp, wStream* s) { UINT32 arcStatus; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, arcStatus); /* arcStatus (4 bytes) */ WLog_WARN(TAG, "AutoReconnectStatus: 0x%08" PRIX32 "", arcStatus); return TRUE; } static BOOL rdp_recv_server_status_info_pdu(rdpRdp* rdp, wStream* s) { UINT32 statusCode; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, statusCode); /* statusCode (4 bytes) */ if (rdp->update->ServerStatusInfo) return rdp->update->ServerStatusInfo(rdp->context, statusCode); return TRUE; } static BOOL rdp_recv_monitor_layout_pdu(rdpRdp* rdp, wStream* s) { UINT32 index; UINT32 monitorCount; MONITOR_DEF* monitor; MONITOR_DEF* monitorDefArray; BOOL ret = TRUE; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, monitorCount); /* monitorCount (4 bytes) */ if ((Stream_GetRemainingLength(s) / 20) < monitorCount) return FALSE; monitorDefArray = (MONITOR_DEF*)calloc(monitorCount, sizeof(MONITOR_DEF)); if (!monitorDefArray) return FALSE; for (monitor = monitorDefArray, index = 0; index < monitorCount; index++, monitor++) { Stream_Read_UINT32(s, monitor->left); /* left (4 bytes) */ Stream_Read_UINT32(s, monitor->top); /* top (4 bytes) */ Stream_Read_UINT32(s, monitor->right); /* right (4 bytes) */ Stream_Read_UINT32(s, monitor->bottom); /* bottom (4 bytes) */ Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */ } IFCALLRET(rdp->update->RemoteMonitors, ret, rdp->context, monitorCount, monitorDefArray); free(monitorDefArray); return ret; } int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { BYTE type; wStream* cs; UINT16 length; UINT32 shareId; BYTE compressedType; UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) { WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; } cs = s; if (compressedType & PACKET_COMPRESSED) { UINT32 DstSize = 0; BYTE* pDstData = NULL; UINT16 SrcSize = compressedLength - 18; if ((compressedLength < 18) || (Stream_GetRemainingLength(s) < SrcSize)) { WLog_ERR(TAG, "bulk_decompress: not enough bytes for compressedLength %" PRIu16 "", compressedLength); return -1; } if (bulk_decompress(rdp->bulk, Stream_Pointer(s), SrcSize, &pDstData, &DstSize, compressedType)) { if (!(cs = StreamPool_Take(rdp->transport->ReceivePool, DstSize))) { WLog_ERR(TAG, "Couldn't take stream from pool"); return -1; } Stream_SetPosition(cs, 0); Stream_Write(cs, pDstData, DstSize); Stream_SealLength(cs); Stream_SetPosition(cs, 0); } else { WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } Stream_Seek(s, SrcSize); } WLog_DBG(TAG, "recv %s Data PDU (0x%02" PRIX8 "), length: %" PRIu16 "", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - " "rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - " "rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - " "rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; } break; default: break; } if (cs != s) Stream_Release(cs); return 0; out_fail: if (cs != s) Stream_Release(cs); return -1; } int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ return rdp_recv_autodetect_request_packet(rdp, s); } if (securityFlags & SEC_AUTODETECT_RSP) { /* Client Auto-Detect Response PDU */ return rdp_recv_autodetect_response_packet(rdp, s); } if (securityFlags & SEC_HEARTBEAT) { /* Heartbeat PDU */ return rdp_recv_heartbeat_packet(rdp, s); } if (securityFlags & SEC_TRANSPORT_REQ) { /* Initiate Multitransport Request PDU */ return rdp_recv_multitransport_packet(rdp, s); } return -1; } int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return -1; if (type == PDU_TYPE_DATA) { return rdp_recv_data_pdu(rdp, s); } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else if (type == PDU_TYPE_FLOW_RESPONSE || type == PDU_TYPE_FLOW_STOP || type == PDU_TYPE_FLOW_TEST) { return 0; } else { return -1; } } BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; if (!type) return FALSE; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ return TRUE; } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, wStream* s, UINT16* pLength, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; BOOL status; INT32 length; if (!rdp || !s || !pLength) return FALSE; length = *pLength; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; INT64 padLength; if (Stream_GetRemainingLength(s) < 12) return FALSE; Stream_Read_UINT16(s, len); /* 0x10 */ Stream_Read_UINT8(s, version); /* 0x1 */ Stream_Read_UINT8(s, pad); sig = Stream_Pointer(s); Stream_Seek(s, 8); /* signature */ length -= 12; padLength = length - pad; if ((length <= 0) || (padLength <= 0)) return FALSE; if (!security_fips_decrypt(Stream_Pointer(s), length, rdp)) { WLog_ERR(TAG, "FATAL: cannot decrypt"); return FALSE; /* TODO */ } if (!security_fips_check_signature(Stream_Pointer(s), length - pad, sig, rdp)) { WLog_ERR(TAG, "FATAL: invalid packet signature"); return FALSE; /* TODO */ } Stream_SetLength(s, Stream_Length(s) - pad); *pLength = padLength; return TRUE; } if (Stream_GetRemainingLength(s) < sizeof(wmac)) return FALSE; Stream_Read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (length <= 0) return FALSE; if (!security_decrypt(Stream_Pointer(s), length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, Stream_Pointer(s), length, FALSE, cmac); else status = security_mac_signature(rdp, Stream_Pointer(s), length, cmac); if (!status) return FALSE; if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { WLog_ERR(TAG, "WARNING: invalid packet signature"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ // return FALSE; } *pLength = length; return TRUE; } static const char* pdu_type_to_str(UINT16 pduType) { static char buffer[1024] = { 0 }; switch (pduType) { case PDU_TYPE_DEMAND_ACTIVE: return "PDU_TYPE_DEMAND_ACTIVE"; case PDU_TYPE_CONFIRM_ACTIVE: return "PDU_TYPE_CONFIRM_ACTIVE"; case PDU_TYPE_DEACTIVATE_ALL: return "PDU_TYPE_DEACTIVATE_ALL"; case PDU_TYPE_DATA: return "PDU_TYPE_DATA"; case PDU_TYPE_SERVER_REDIRECTION: return "PDU_TYPE_SERVER_REDIRECTION"; case PDU_TYPE_FLOW_TEST: return "PDU_TYPE_FLOW_TEST"; case PDU_TYPE_FLOW_RESPONSE: return "PDU_TYPE_FLOW_RESPONSE"; case PDU_TYPE_FLOW_STOP: return "PDU_TYPE_FLOW_STOP"; default: _snprintf(buffer, sizeof(buffer), "UNKNOWN %04" PRIx16, pduType); return buffer; } } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) { int rc = 0; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId = 0; UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, &length, &channelId)) { WLog_ERR(TAG, "Incorrect RDP header."); return -1; } if (freerdp_shall_disconnect(rdp->instance)) return 0; if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, &length)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, &length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ Stream_Rewind(s, 2); rdp->inPackets++; rc = rdp_recv_enhanced_security_redirection_packet(rdp, s); goto out; } } if (channelId == MCS_GLOBAL_CHANNEL_ID) { while (Stream_GetRemainingLength(s) > 3) { size_t startheader, endheader, start, end, diff, headerdiff; startheader = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; } start = endheader = Stream_GetPosition(s); headerdiff = endheader - startheader; if (pduLength < headerdiff) { WLog_ERR( TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() invalid pduLength %" PRIu16, pduLength); return -1; } pduLength -= headerdiff; rdp->settings->PduSource = pduSource; rdp->inPackets++; switch (pduType) { case PDU_TYPE_DATA: rc = rdp_recv_data_pdu(rdp, s); if (rc < 0) return rc; break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; } break; case PDU_TYPE_SERVER_REDIRECTION: return rdp_recv_enhanced_security_redirection_packet(rdp, s); case PDU_TYPE_FLOW_RESPONSE: case PDU_TYPE_FLOW_STOP: case PDU_TYPE_FLOW_TEST: WLog_DBG(TAG, "flow message 0x%04" PRIX16 "", pduType); /* http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (!Stream_SafeSeek(s, pduLength)) return -1; break; default: WLog_ERR(TAG, "incorrect PDU type: 0x%04" PRIX16 "", pduType); break; } end = Stream_GetPosition(s); diff = end - start; if (diff != pduLength) { WLog_WARN(TAG, "pduType %s not properly parsed, %" PRIdz " bytes remaining unhandled. Skipping.", pdu_type_to_str(pduType), diff); if (!Stream_SafeSeek(s, pduLength)) return -1; } } } else if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId)) { if (!rdp->settings->UseRdpSecurityLayer) if (!rdp_read_security_header(s, &securityFlags, NULL)) return -1; rdp->inPackets++; rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { rdp->inPackets++; if (!freerdp_channel_process(rdp->instance, s, channelId, length)) return -1; } out: if (!tpkt_ensure_stream_consumed(s, length)) return -1; return rc; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { WLog_ERR(TAG, "incorrect FastPath PDU header length %" PRIu16 "", length); return -1; } if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, &length, flags)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; } } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, wStream* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*)extra; /* * At any point in the connection sequence between when all * MCS channels have been joined and when the RDP connection * enters the active state, an auto-detect PDU can be received * on the MCS message channel. */ if ((rdp->state > CONNECTION_STATE_MCS_CHANNEL_JOIN) && (rdp->state < CONNECTION_STATE_ACTIVE)) { if (rdp_client_connect_auto_detect(rdp, s)) return 0; } switch (rdp->state) { case CONNECTION_STATE_NLA: if (nla_get_state(rdp->nla) < NLA_STATE_AUTH_INFO) { if (nla_recv_pdu(rdp->nla, s) < 1) { WLog_ERR(TAG, "%s: %s - nla_recv_pdu() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } else if (nla_get_state(rdp->nla) == NLA_STATE_POST_NEGO) { nego_recv(rdp->transport, s, (void*)rdp->nego); if (nego_get_state(rdp->nego) != NEGO_STATE_FINAL) { WLog_ERR(TAG, "%s: %s - nego_recv() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } if (nla_get_state(rdp->nla) == NLA_STATE_AUTH_INFO) { transport_set_nla_mode(rdp->transport, FALSE); if (rdp->settings->VmConnectMode) { if (!nego_set_state(rdp->nego, NEGO_STATE_NLA)) return -1; if (!nego_set_requested_protocols(rdp->nego, PROTOCOL_HYBRID | PROTOCOL_SSL)) return -1; nego_send_negotiation_request(rdp->nego); if (!nla_set_state(rdp->nla, NLA_STATE_POST_NEGO)) return -1; } else { if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } } if (nla_get_state(rdp->nla) == NLA_STATE_FINAL) { nla_free(rdp->nla); rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) { WLog_ERR(TAG, "%s: %s - mcs_client_begin() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } break; case CONNECTION_STATE_MCS_CONNECT: if (!mcs_recv_connect_response(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_connect_response failure"); return -1; } if (!mcs_send_erect_domain_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_erect_domain_request failure"); return -1; } if (!mcs_send_attach_user_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_attach_user_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER); break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!mcs_recv_attach_user_confirm(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_attach_user_confirm failure"); return -1; } if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->userId)) { WLog_ERR(TAG, "mcs_send_channel_join_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN); break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) { WLog_ERR(TAG, "%s: %s - " "rdp_client_connect_mcs_channel_join_confirm() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); status = -1; } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_client_connect_license() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - " "rdp_client_connect_demand_active() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) { ActivatedEventArgs activatedEvent; rdpContext* context = rdp->context; rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); EventArgsInit(&activatedEvent, "libfreerdp"); activatedEvent.firstActivation = !rdp->deactivation_reactivation; PubSub_OnActivated(context->pubSub, context, &activatedEvent); return 2; } if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; default: WLog_ERR(TAG, "%s: %s state %d", __FUNCTION__, rdp_server_connection_state_string(rdp->state), rdp->state); status = -1; break; } return status; } BOOL rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, const BYTE* data, size_t size) { return freerdp_channel_send(rdp, channelId, data, size); } BOOL rdp_send_error_info(rdpRdp* rdp) { wStream* s; BOOL status; if (rdp->errorInfo == ERRINFO_SUCCESS) return TRUE; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, rdp->errorInfo); /* error id (4 bytes) */ status = rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_ERROR_INFO, 0); return status; } int rdp_check_fds(rdpRdp* rdp) { int status; rdpTransport* transport = rdp->transport; if (transport->tsg) { rdpTsg* tsg = transport->tsg; if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles()"); return -1; } if (tsg_get_state(tsg) != TSG_STATE_PIPE_CREATED) return 1; } status = transport_check_fds(transport); if (status == 1) { if (!rdp_client_redirect(rdp)) /* session redirection */ return -1; } if (status < 0) WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } BOOL freerdp_get_stats(rdpRdp* rdp, UINT64* inBytes, UINT64* outBytes, UINT64* inPackets, UINT64* outPackets) { if (!rdp) return FALSE; if (inBytes) *inBytes = rdp->inBytes; if (outBytes) *outBytes = rdp->outBytes; if (inPackets) *inPackets = rdp->inPackets; if (outPackets) *outPackets = rdp->outPackets; return TRUE; } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(rdpContext* context) { rdpRdp* rdp; DWORD flags; BOOL newSettings = FALSE; rdp = (rdpRdp*)calloc(1, sizeof(rdpRdp)); if (!rdp) return NULL; rdp->context = context; rdp->instance = context->instance; flags = 0; if (context->ServerMode) flags |= FREERDP_SETTINGS_SERVER_MODE; if (!context->settings) { context->settings = freerdp_settings_new(flags); if (!context->settings) goto out_free; newSettings = TRUE; } rdp->settings = context->settings; if (context->instance) { rdp->settings->instance = context->instance; context->instance->settings = rdp->settings; } else if (context->peer) { rdp->settings->instance = context->peer; context->peer->settings = rdp->settings; } rdp->transport = transport_new(context); if (!rdp->transport) goto out_free_settings; rdp->license = license_new(rdp); if (!rdp->license) goto out_free_transport; rdp->input = input_new(rdp); if (!rdp->input) goto out_free_license; rdp->update = update_new(rdp); if (!rdp->update) goto out_free_input; rdp->fastpath = fastpath_new(rdp); if (!rdp->fastpath) goto out_free_update; rdp->nego = nego_new(rdp->transport); if (!rdp->nego) goto out_free_fastpath; rdp->mcs = mcs_new(rdp->transport); if (!rdp->mcs) goto out_free_nego; rdp->redirection = redirection_new(); if (!rdp->redirection) goto out_free_mcs; rdp->autodetect = autodetect_new(); if (!rdp->autodetect) goto out_free_redirection; rdp->heartbeat = heartbeat_new(); if (!rdp->heartbeat) goto out_free_autodetect; rdp->multitransport = multitransport_new(); if (!rdp->multitransport) goto out_free_heartbeat; rdp->bulk = bulk_new(context); if (!rdp->bulk) goto out_free_multitransport; return rdp; out_free_multitransport: multitransport_free(rdp->multitransport); out_free_heartbeat: heartbeat_free(rdp->heartbeat); out_free_autodetect: autodetect_free(rdp->autodetect); out_free_redirection: redirection_free(rdp->redirection); out_free_mcs: mcs_free(rdp->mcs); out_free_nego: nego_free(rdp->nego); out_free_fastpath: fastpath_free(rdp->fastpath); out_free_update: update_free(rdp->update); out_free_input: input_free(rdp->input); out_free_license: license_free(rdp->license); out_free_transport: transport_free(rdp->transport); out_free_settings: if (newSettings) freerdp_settings_free(rdp->settings); out_free: free(rdp); return NULL; } void rdp_reset(rdpRdp* rdp) { rdpContext* context; rdpSettings* settings; context = rdp->context; settings = rdp->settings; bulk_reset(rdp->bulk); if (rdp->rc4_decrypt_key) { winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = NULL; } if (rdp->rc4_encrypt_key) { winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = NULL; } if (rdp->fips_encrypt) { winpr_Cipher_Free(rdp->fips_encrypt); rdp->fips_encrypt = NULL; } if (rdp->fips_decrypt) { winpr_Cipher_Free(rdp->fips_decrypt); rdp->fips_decrypt = NULL; } if (settings->ServerRandom) { free(settings->ServerRandom); settings->ServerRandom = NULL; settings->ServerRandomLength = 0; } if (settings->ServerCertificate) { free(settings->ServerCertificate); settings->ServerCertificate = NULL; } if (settings->ClientAddress) { free(settings->ClientAddress); settings->ClientAddress = NULL; } mcs_free(rdp->mcs); nego_free(rdp->nego); license_free(rdp->license); transport_free(rdp->transport); fastpath_free(rdp->fastpath); rdp->transport = transport_new(context); rdp->license = license_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->fastpath = fastpath_new(rdp); rdp->transport->layer = TRANSPORT_LAYER_TCP; rdp->errorInfo = 0; rdp->deactivation_reactivation = 0; rdp->finalize_sc_pdus = 0; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp) { winpr_RC4_Free(rdp->rc4_decrypt_key); winpr_RC4_Free(rdp->rc4_encrypt_key); winpr_Cipher_Free(rdp->fips_encrypt); winpr_Cipher_Free(rdp->fips_decrypt); freerdp_settings_free(rdp->settings); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); nla_free(rdp->nla); redirection_free(rdp->redirection); autodetect_free(rdp->autodetect); heartbeat_free(rdp->heartbeat); multitransport_free(rdp->multitransport); bulk_free(rdp->bulk); free(rdp); } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3910_0
crossvul-cpp_data_bad_1178_0
/** @file mat4.c * Matlab MAT version 4 file functions * @ingroup MAT */ /* * Copyright (c) 2005-2019, Christopher C. Hulbert * 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 HOLDER 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 <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include <limits.h> #if defined(__GLIBC__) #include <endian.h> #endif #include "matio_private.h" #include "mat4.h" /** @if mat_devman * @brief Creates a new Matlab MAT version 4 file * * Tries to create a new Matlab MAT file with the given name. * @ingroup MAT * @param matname Name of MAT file to create * @return A pointer to the MAT file or NULL if it failed. This is not a * simple FILE * and should not be used as one. * @endif */ mat_t * Mat_Create4(const char* matname) { FILE *fp = NULL; mat_t *mat = NULL; #if defined(_WIN32) && defined(_MSC_VER) wchar_t* wname = utf82u(matname); if ( NULL != wname ) { fp = _wfopen(wname, L"w+b"); free(wname); } #else fp = fopen(matname, "w+b"); #endif if ( !fp ) return NULL; mat = (mat_t*)malloc(sizeof(*mat)); if ( NULL == mat ) { fclose(fp); Mat_Critical("Couldn't allocate memory for the MAT file"); return NULL; } mat->fp = fp; mat->header = NULL; mat->subsys_offset = NULL; mat->filename = strdup_printf("%s",matname); mat->version = MAT_FT_MAT4; mat->byteswap = 0; mat->mode = 0; mat->bof = 0; mat->next_index = 0; mat->num_datasets = 0; #if defined(MAT73) && MAT73 mat->refs_id = -1; #endif mat->dir = NULL; Mat_Rewind(mat); return mat; } /** @if mat_devman * @brief Writes a matlab variable to a version 4 matlab file * * @ingroup mat_internal * @param mat MAT file pointer * @param matvar pointer to the mat variable * @retval 0 on success * @endif */ int Mat_VarWrite4(mat_t *mat,matvar_t *matvar) { typedef struct { mat_int32_t type; mat_int32_t mrows; mat_int32_t ncols; mat_int32_t imagf; mat_int32_t namelen; } Fmatrix; mat_int32_t nelems = 1, i; Fmatrix x; if ( NULL == mat || NULL == matvar || NULL == matvar->name || matvar->rank != 2 ) return -1; switch ( matvar->data_type ) { case MAT_T_DOUBLE: x.type = 0; break; case MAT_T_SINGLE: x.type = 10; break; case MAT_T_INT32: x.type = 20; break; case MAT_T_INT16: x.type = 30; break; case MAT_T_UINT16: x.type = 40; break; case MAT_T_UINT8: x.type = 50; break; default: return 2; } #if defined(__GLIBC__) #if (__BYTE_ORDER == __LITTLE_ENDIAN) #elif (__BYTE_ORDER == __BIG_ENDIAN) x.type += 1000; #else return -1; #endif #elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) x.type += 1000; #elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) #elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || \ defined(__ppc__) || defined(__hpux) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__) x.type += 1000; #elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || \ defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || \ defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || \ defined(_M_X64) || defined(__bfin__) #else return -1; #endif x.namelen = (mat_int32_t)strlen(matvar->name) + 1; /* FIXME: SEEK_END is not Guaranteed by the C standard */ (void)fseek((FILE*)mat->fp,0,SEEK_END); /* Always write at end of file */ switch ( matvar->class_type ) { case MAT_C_CHAR: x.type++; /* Fall through */ case MAT_C_DOUBLE: case MAT_C_SINGLE: case MAT_C_INT32: case MAT_C_INT16: case MAT_C_UINT16: case MAT_C_UINT8: for ( i = 0; i < matvar->rank; i++ ) { mat_int32_t dim; dim = (mat_int32_t)matvar->dims[i]; nelems *= dim; } x.mrows = (mat_int32_t)matvar->dims[0]; x.ncols = (mat_int32_t)matvar->dims[1]; x.imagf = matvar->isComplex ? 1 : 0; fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp); fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp); if ( matvar->isComplex ) { mat_complex_split_t *complex_data; complex_data = (mat_complex_split_t*)matvar->data; fwrite(complex_data->Re, matvar->data_size, nelems, (FILE*)mat->fp); fwrite(complex_data->Im, matvar->data_size, nelems, (FILE*)mat->fp); } else { fwrite(matvar->data, matvar->data_size, nelems, (FILE*)mat->fp); } break; case MAT_C_SPARSE: { mat_sparse_t* sparse; double tmp; int j; size_t stride = Mat_SizeOf(matvar->data_type); #if !defined(EXTENDED_SPARSE) if ( MAT_T_DOUBLE != matvar->data_type ) break; #endif sparse = (mat_sparse_t*)matvar->data; x.type += 2; x.mrows = sparse->njc > 0 ? sparse->jc[sparse->njc - 1] + 1 : 1; x.ncols = matvar->isComplex ? 4 : 3; x.imagf = 0; fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp); fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp); for ( i = 0; i < sparse->njc - 1; i++ ) { for ( j = sparse->jc[i]; j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) { tmp = sparse->ir[j] + 1; fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp); } } tmp = (double)matvar->dims[0]; fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp); for ( i = 0; i < sparse->njc - 1; i++ ) { for ( j = sparse->jc[i]; j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) { tmp = i + 1; fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp); } } tmp = (double)matvar->dims[1]; fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp); tmp = 0.; if ( matvar->isComplex ) { mat_complex_split_t *complex_data; char* re, *im; complex_data = (mat_complex_split_t*)sparse->data; re = (char*)complex_data->Re; im = (char*)complex_data->Im; for ( i = 0; i < sparse->njc - 1; i++ ) { for ( j = sparse->jc[i]; j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) { fwrite(re + j*stride, stride, 1, (FILE*)mat->fp); } } fwrite(&tmp, stride, 1, (FILE*)mat->fp); for ( i = 0; i < sparse->njc - 1; i++ ) { for ( j = sparse->jc[i]; j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) { fwrite(im + j*stride, stride, 1, (FILE*)mat->fp); } } } else { char *data = (char*)sparse->data; for ( i = 0; i < sparse->njc - 1; i++ ) { for ( j = sparse->jc[i]; j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) { fwrite(data + j*stride, stride, 1, (FILE*)mat->fp); } } } fwrite(&tmp, stride, 1, (FILE*)mat->fp); break; } default: break; } return 0; } /** @if mat_devman * @brief Reads the data of a version 4 MAT file variable * * @ingroup mat_internal * @param mat MAT file pointer * @param matvar MAT variable pointer to read the data * @endif */ void Mat_VarRead4(mat_t *mat,matvar_t *matvar) { int err; size_t nelems = 1; err = SafeMulDims(matvar, &nelems); if ( err ) { Mat_Critical("Integer multiplication overflow"); return; } (void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET); switch ( matvar->class_type ) { case MAT_C_DOUBLE: matvar->data_size = sizeof(double); err = SafeMul(&matvar->nbytes, nelems, matvar->data_size); if ( err ) { Mat_Critical("Integer multiplication overflow"); return; } if ( matvar->isComplex ) { mat_complex_split_t *complex_data = ComplexMalloc(matvar->nbytes); if ( NULL != complex_data ) { matvar->data = complex_data; ReadDoubleData(mat, (double*)complex_data->Re, matvar->data_type, nelems); ReadDoubleData(mat, (double*)complex_data->Im, matvar->data_type, nelems); } else { Mat_Critical("Couldn't allocate memory for the complex data"); } } else { matvar->data = malloc(matvar->nbytes); if ( NULL != matvar->data ) { ReadDoubleData(mat, (double*)matvar->data, matvar->data_type, nelems); } else { Mat_Critical("Couldn't allocate memory for the data"); } } /* Update data type to match format of matvar->data */ matvar->data_type = MAT_T_DOUBLE; break; case MAT_C_CHAR: matvar->data_size = 1; matvar->nbytes = nelems; matvar->data = malloc(matvar->nbytes); if ( NULL != matvar->data ) { ReadUInt8Data(mat, (mat_uint8_t*)matvar->data, matvar->data_type, nelems); } else { Mat_Critical("Couldn't allocate memory for the data"); } matvar->data_type = MAT_T_UINT8; break; case MAT_C_SPARSE: matvar->data_size = sizeof(mat_sparse_t); matvar->data = malloc(matvar->data_size); if ( NULL != matvar->data ) { double tmp; int i; mat_sparse_t* sparse; long fpos; enum matio_types data_type = MAT_T_DOUBLE; /* matvar->dims[1] either is 3 for real or 4 for complex sparse */ matvar->isComplex = matvar->dims[1] == 4 ? 1 : 0; sparse = (mat_sparse_t*)matvar->data; sparse->nir = matvar->dims[0] - 1; sparse->nzmax = sparse->nir; sparse->ir = (mat_int32_t*)malloc(sparse->nir*sizeof(mat_int32_t)); if ( sparse->ir != NULL ) { ReadInt32Data(mat, sparse->ir, data_type, sparse->nir); for ( i = 0; i < sparse->nir; i++ ) sparse->ir[i] = sparse->ir[i] - 1; } else { free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't allocate memory for the sparse row array"); return; } ReadDoubleData(mat, &tmp, data_type, 1); matvar->dims[0] = (size_t)tmp; fpos = ftell((FILE*)mat->fp); if ( fpos == -1L ) { free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't determine file position"); return; } (void)fseek((FILE*)mat->fp,sparse->nir*Mat_SizeOf(data_type), SEEK_CUR); ReadDoubleData(mat, &tmp, data_type, 1); if ( tmp > INT_MAX-1 || tmp < 0 ) { free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Invalid column dimension for sparse matrix"); return; } matvar->dims[1] = (size_t)tmp; (void)fseek((FILE*)mat->fp,fpos,SEEK_SET); if ( matvar->dims[1] > INT_MAX-1 ) { free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Invalid column dimension for sparse matrix"); return; } sparse->njc = (int)matvar->dims[1] + 1; sparse->jc = (mat_int32_t*)malloc(sparse->njc*sizeof(mat_int32_t)); if ( sparse->jc != NULL ) { mat_int32_t *jc; jc = (mat_int32_t*)malloc(sparse->nir*sizeof(mat_int32_t)); if ( jc != NULL ) { int j = 0; sparse->jc[0] = 0; ReadInt32Data(mat, jc, data_type, sparse->nir); for ( i = 1; i < sparse->njc-1; i++ ) { while ( j < sparse->nir && jc[j] <= i ) j++; sparse->jc[i] = j; } free(jc); /* terminating nnz */ sparse->jc[sparse->njc-1] = sparse->nir; } else { free(sparse->jc); free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't allocate memory for the sparse index array"); return; } } else { free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't allocate memory for the sparse index array"); return; } ReadDoubleData(mat, &tmp, data_type, 1); sparse->ndata = sparse->nir; data_type = matvar->data_type; if ( matvar->isComplex ) { mat_complex_split_t *complex_data = ComplexMalloc(sparse->ndata*Mat_SizeOf(data_type)); if ( NULL != complex_data ) { sparse->data = complex_data; #if defined(EXTENDED_SPARSE) switch ( data_type ) { case MAT_T_DOUBLE: ReadDoubleData(mat, (double*)complex_data->Re, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); ReadDoubleData(mat, (double*)complex_data->Im, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); break; case MAT_T_SINGLE: { float tmp2; ReadSingleData(mat, (float*)complex_data->Re, data_type, sparse->ndata); ReadSingleData(mat, &tmp2, data_type, 1); ReadSingleData(mat, (float*)complex_data->Im, data_type, sparse->ndata); ReadSingleData(mat, &tmp2, data_type, 1); break; } case MAT_T_INT32: { mat_int32_t tmp2; ReadInt32Data(mat, (mat_int32_t*)complex_data->Re, data_type, sparse->ndata); ReadInt32Data(mat, &tmp2, data_type, 1); ReadInt32Data(mat, (mat_int32_t*)complex_data->Im, data_type, sparse->ndata); ReadInt32Data(mat, &tmp2, data_type, 1); break; } case MAT_T_INT16: { mat_int16_t tmp2; ReadInt16Data(mat, (mat_int16_t*)complex_data->Re, data_type, sparse->ndata); ReadInt16Data(mat, &tmp2, data_type, 1); ReadInt16Data(mat, (mat_int16_t*)complex_data->Im, data_type, sparse->ndata); ReadInt16Data(mat, &tmp2, data_type, 1); break; } case MAT_T_UINT16: { mat_uint16_t tmp2; ReadUInt16Data(mat, (mat_uint16_t*)complex_data->Re, data_type, sparse->ndata); ReadUInt16Data(mat, &tmp2, data_type, 1); ReadUInt16Data(mat, (mat_uint16_t*)complex_data->Im, data_type, sparse->ndata); ReadUInt16Data(mat, &tmp2, data_type, 1); break; } case MAT_T_UINT8: { mat_uint8_t tmp2; ReadUInt8Data(mat, (mat_uint8_t*)complex_data->Re, data_type, sparse->ndata); ReadUInt8Data(mat, &tmp2, data_type, 1); ReadUInt8Data(mat, (mat_uint8_t*)complex_data->Im, data_type, sparse->ndata); ReadUInt8Data(mat, &tmp2, data_type, 1); break; } default: free(complex_data->Re); free(complex_data->Im); free(complex_data); free(sparse->jc); free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Mat_VarRead4: %d is not a supported data type for " "extended sparse", data_type); return; } #else ReadDoubleData(mat, (double*)complex_data->Re, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); ReadDoubleData(mat, (double*)complex_data->Im, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); #endif } else { free(sparse->jc); free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't allocate memory for the complex sparse data"); return; } } else { sparse->data = malloc(sparse->ndata*Mat_SizeOf(data_type)); if ( sparse->data != NULL ) { #if defined(EXTENDED_SPARSE) switch ( data_type ) { case MAT_T_DOUBLE: ReadDoubleData(mat, (double*)sparse->data, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); break; case MAT_T_SINGLE: { float tmp2; ReadSingleData(mat, (float*)sparse->data, data_type, sparse->ndata); ReadSingleData(mat, &tmp2, data_type, 1); break; } case MAT_T_INT32: { mat_int32_t tmp2; ReadInt32Data(mat, (mat_int32_t*)sparse->data, data_type, sparse->ndata); ReadInt32Data(mat, &tmp2, data_type, 1); break; } case MAT_T_INT16: { mat_int16_t tmp2; ReadInt16Data(mat, (mat_int16_t*)sparse->data, data_type, sparse->ndata); ReadInt16Data(mat, &tmp2, data_type, 1); break; } case MAT_T_UINT16: { mat_uint16_t tmp2; ReadUInt16Data(mat, (mat_uint16_t*)sparse->data, data_type, sparse->ndata); ReadUInt16Data(mat, &tmp2, data_type, 1); break; } case MAT_T_UINT8: { mat_uint8_t tmp2; ReadUInt8Data(mat, (mat_uint8_t*)sparse->data, data_type, sparse->ndata); ReadUInt8Data(mat, &tmp2, data_type, 1); break; } default: free(sparse->data); free(sparse->jc); free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Mat_VarRead4: %d is not a supported data type for " "extended sparse", data_type); return; } #else ReadDoubleData(mat, (double*)sparse->data, data_type, sparse->ndata); ReadDoubleData(mat, &tmp, data_type, 1); #endif } else { free(sparse->jc); free(sparse->ir); free(matvar->data); matvar->data = NULL; Mat_Critical("Couldn't allocate memory for the sparse data"); return; } } break; } else { Mat_Critical("Couldn't allocate memory for the data"); return; } default: Mat_Critical("MAT V4 data type error"); return; } return; } /** @if mat_devman * @brief Reads a slab of data from a version 4 MAT file for the @c matvar variable * * @ingroup mat_internal * @param mat Version 4 MAT file pointer * @param matvar pointer to the mat variable * @param data pointer to store the read data in (must be of size * edge[0]*...edge[rank-1]*Mat_SizeOfClass(matvar->class_type)) * @param start index to start reading data in each dimension * @param stride write data every @c stride elements in each dimension * @param edge number of elements to read in each dimension * @retval 0 on success * @endif */ int Mat_VarReadData4(mat_t *mat,matvar_t *matvar,void *data, int *start,int *stride,int *edge) { int err = 0; (void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET); switch( matvar->data_type ) { case MAT_T_DOUBLE: case MAT_T_SINGLE: case MAT_T_INT32: case MAT_T_INT16: case MAT_T_UINT16: case MAT_T_UINT8: break; default: return 1; } if ( matvar->rank == 2 ) { if ( (size_t)stride[0]*(edge[0]-1)+start[0]+1 > matvar->dims[0] ) err = 1; else if ( (size_t)stride[1]*(edge[1]-1)+start[1]+1 > matvar->dims[1] ) err = 1; if ( matvar->isComplex ) { mat_complex_split_t *cdata = (mat_complex_split_t*)data; size_t nbytes = Mat_SizeOf(matvar->data_type); err = SafeMulDims(matvar, &nbytes); if ( err ) { Mat_Critical("Integer multiplication overflow"); return err; } ReadDataSlab2(mat,cdata->Re,matvar->class_type,matvar->data_type, matvar->dims,start,stride,edge); (void)fseek((FILE*)mat->fp,matvar->internal->datapos+nbytes,SEEK_SET); ReadDataSlab2(mat,cdata->Im,matvar->class_type, matvar->data_type,matvar->dims,start,stride,edge); } else { ReadDataSlab2(mat,data,matvar->class_type,matvar->data_type, matvar->dims,start,stride,edge); } } else if ( matvar->isComplex ) { mat_complex_split_t *cdata = (mat_complex_split_t*)data; size_t nbytes = Mat_SizeOf(matvar->data_type); err = SafeMulDims(matvar, &nbytes); if ( err ) { Mat_Critical("Integer multiplication overflow"); return err; } ReadDataSlabN(mat,cdata->Re,matvar->class_type,matvar->data_type, matvar->rank,matvar->dims,start,stride,edge); (void)fseek((FILE*)mat->fp,matvar->internal->datapos+nbytes,SEEK_SET); ReadDataSlabN(mat,cdata->Im,matvar->class_type,matvar->data_type, matvar->rank,matvar->dims,start,stride,edge); } else { ReadDataSlabN(mat,data,matvar->class_type,matvar->data_type, matvar->rank,matvar->dims,start,stride,edge); } return err; } /** @brief Reads a subset of a MAT variable using a 1-D indexing * * Reads data from a MAT variable using a linear (1-D) indexing mode. The * variable must have been read by Mat_VarReadInfo. * @ingroup MAT * @param mat MAT file to read data from * @param matvar MAT variable information * @param data pointer to store data in (must be pre-allocated) * @param start starting index * @param stride stride of data * @param edge number of elements to read * @retval 0 on success */ int Mat_VarReadDataLinear4(mat_t *mat,matvar_t *matvar,void *data,int start, int stride,int edge) { int err; size_t nelems = 1; err = SafeMulDims(matvar, &nelems); if ( err ) { Mat_Critical("Integer multiplication overflow"); return err; } (void)fseek((FILE*)mat->fp,matvar->internal->datapos,SEEK_SET); matvar->data_size = Mat_SizeOf(matvar->data_type); if ( (size_t)stride*(edge-1)+start+1 > nelems ) { return 1; } if ( matvar->isComplex ) { mat_complex_split_t *complex_data = (mat_complex_split_t*)data; err = SafeMul(&nelems, nelems, matvar->data_size); if ( err ) { Mat_Critical("Integer multiplication overflow"); return err; } ReadDataSlab1(mat,complex_data->Re,matvar->class_type, matvar->data_type,start,stride,edge); (void)fseek((FILE*)mat->fp,matvar->internal->datapos+nelems,SEEK_SET); ReadDataSlab1(mat,complex_data->Im,matvar->class_type, matvar->data_type,start,stride,edge); } else { ReadDataSlab1(mat,data,matvar->class_type,matvar->data_type,start, stride,edge); } return err; } /** @if mat_devman * @brief Reads the header information for the next MAT variable in a version 4 MAT file * * @ingroup mat_internal * @param mat MAT file pointer * @return pointer to the MAT variable or NULL * @endif */ matvar_t * Mat_VarReadNextInfo4(mat_t *mat) { int M,O,data_type,class_type; mat_int32_t tmp; long nBytes; size_t readresult; matvar_t *matvar = NULL; union { mat_uint32_t u; mat_uint8_t c[4]; } endian; if ( mat == NULL || mat->fp == NULL ) return NULL; else if ( NULL == (matvar = Mat_VarCalloc()) ) return NULL; readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp); if ( 1 != readresult ) { Mat_VarFree(matvar); return NULL; } endian.u = 0x01020304; /* See if MOPT may need byteswapping */ if ( tmp < 0 || tmp > 4052 ) { if ( Mat_int32Swap(&tmp) > 4052 ) { Mat_VarFree(matvar); return NULL; } } M = (int)floor(tmp / 1000.0); switch ( M ) { case 0: /* IEEE little endian */ mat->byteswap = endian.c[0] != 4; break; case 1: /* IEEE big endian */ mat->byteswap = endian.c[0] != 1; break; default: /* VAX, Cray, or bogus */ Mat_VarFree(matvar); return NULL; } tmp -= M*1000; O = (int)floor(tmp / 100.0); /* O must be zero */ if ( 0 != O ) { Mat_VarFree(matvar); return NULL; } tmp -= O*100; data_type = (int)floor(tmp / 10.0); /* Convert the V4 data type */ switch ( data_type ) { case 0: matvar->data_type = MAT_T_DOUBLE; break; case 1: matvar->data_type = MAT_T_SINGLE; break; case 2: matvar->data_type = MAT_T_INT32; break; case 3: matvar->data_type = MAT_T_INT16; break; case 4: matvar->data_type = MAT_T_UINT16; break; case 5: matvar->data_type = MAT_T_UINT8; break; default: Mat_VarFree(matvar); return NULL; } tmp -= data_type*10; class_type = (int)floor(tmp / 1.0); switch ( class_type ) { case 0: matvar->class_type = MAT_C_DOUBLE; break; case 1: matvar->class_type = MAT_C_CHAR; break; case 2: matvar->class_type = MAT_C_SPARSE; break; default: Mat_VarFree(matvar); return NULL; } matvar->rank = 2; matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims)); if ( NULL == matvar->dims ) { Mat_VarFree(matvar); return NULL; } readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp); if ( mat->byteswap ) Mat_int32Swap(&tmp); matvar->dims[0] = tmp; if ( 1 != readresult ) { Mat_VarFree(matvar); return NULL; } readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp); if ( mat->byteswap ) Mat_int32Swap(&tmp); matvar->dims[1] = tmp; if ( 1 != readresult ) { Mat_VarFree(matvar); return NULL; } readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp); if ( 1 != readresult ) { Mat_VarFree(matvar); return NULL; } if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) { Mat_VarFree(matvar); return NULL; } readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp); if ( 1 != readresult ) { Mat_VarFree(matvar); return NULL; } if ( mat->byteswap ) Mat_int32Swap(&tmp); /* Check that the length of the variable name is at least 1 */ if ( tmp < 1 ) { Mat_VarFree(matvar); return NULL; } matvar->name = (char*)malloc(tmp); if ( NULL == matvar->name ) { Mat_VarFree(matvar); return NULL; } readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp); if ( tmp != readresult ) { Mat_VarFree(matvar); return NULL; } matvar->internal->datapos = ftell((FILE*)mat->fp); if ( matvar->internal->datapos == -1L ) { Mat_VarFree(matvar); Mat_Critical("Couldn't determine file position"); return NULL; } { int err; size_t tmp2 = Mat_SizeOf(matvar->data_type); if ( matvar->isComplex ) tmp2 *= 2; err = SafeMulDims(matvar, &tmp2); if ( err ) { Mat_VarFree(matvar); Mat_Critical("Integer multiplication overflow"); return NULL; } nBytes = (long)tmp2; } (void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR); return matvar; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1178_0
crossvul-cpp_data_bad_3946_5
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Protocol Security Negotiation * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 Norbert Federa <norbert.federa@thincast.com> * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <freerdp/log.h> #include "tpkt.h" #include "nego.h" #include "transport.h" #define TAG FREERDP_TAG("core.nego") struct rdp_nego { UINT16 port; UINT32 flags; const char* hostname; char* cookie; BYTE* RoutingToken; DWORD RoutingTokenLength; BOOL SendPreconnectionPdu; UINT32 PreconnectionId; char* PreconnectionBlob; NEGO_STATE state; BOOL TcpConnected; BOOL SecurityConnected; UINT32 CookieMaxLength; BOOL sendNegoData; UINT32 SelectedProtocol; UINT32 RequestedProtocols; BOOL NegotiateSecurityLayer; BOOL EnabledProtocols[16]; BOOL RestrictedAdminModeRequired; BOOL GatewayEnabled; BOOL GatewayBypassLocal; rdpTransport* transport; }; static const char* nego_state_string(NEGO_STATE state) { static const char* const NEGO_STATE_STRINGS[] = { "NEGO_STATE_INITIAL", "NEGO_STATE_EXT", "NEGO_STATE_NLA", "NEGO_STATE_TLS", "NEGO_STATE_RDP", "NEGO_STATE_FAIL", "NEGO_STATE_FINAL", "NEGO_STATE_INVALID" }; if (state >= ARRAYSIZE(NEGO_STATE_STRINGS)) return NEGO_STATE_STRINGS[ARRAYSIZE(NEGO_STATE_STRINGS) - 1]; return NEGO_STATE_STRINGS[state]; } static const char* protocol_security_string(UINT32 security) { static const char* PROTOCOL_SECURITY_STRINGS[] = { "RDP", "TLS", "NLA", "UNK", "UNK", "UNK", "UNK", "UNK", "EXT", "UNK" }; if (security >= ARRAYSIZE(PROTOCOL_SECURITY_STRINGS)) return PROTOCOL_SECURITY_STRINGS[ARRAYSIZE(PROTOCOL_SECURITY_STRINGS) - 1]; return PROTOCOL_SECURITY_STRINGS[security]; } static BOOL nego_transport_connect(rdpNego* nego); static BOOL nego_transport_disconnect(rdpNego* nego); static BOOL nego_security_connect(rdpNego* nego); static BOOL nego_send_preconnection_pdu(rdpNego* nego); static BOOL nego_recv_response(rdpNego* nego); static void nego_send(rdpNego* nego); static void nego_process_negotiation_request(rdpNego* nego, wStream* s); static void nego_process_negotiation_response(rdpNego* nego, wStream* s); static void nego_process_negotiation_failure(rdpNego* nego, wStream* s); /** * Negotiate protocol security and connect. * @param nego * @return */ BOOL nego_connect(rdpNego* nego) { rdpSettings* settings = nego->transport->settings; if (nego->state == NEGO_STATE_INITIAL) { if (nego->EnabledProtocols[PROTOCOL_HYBRID_EX]) { nego->state = NEGO_STATE_EXT; } else if (nego->EnabledProtocols[PROTOCOL_HYBRID]) { nego->state = NEGO_STATE_NLA; } else if (nego->EnabledProtocols[PROTOCOL_SSL]) { nego->state = NEGO_STATE_TLS; } else if (nego->EnabledProtocols[PROTOCOL_RDP]) { nego->state = NEGO_STATE_RDP; } else { WLog_ERR(TAG, "No security protocol is enabled"); nego->state = NEGO_STATE_FAIL; return FALSE; } if (!nego->NegotiateSecurityLayer) { WLog_DBG(TAG, "Security Layer Negotiation is disabled"); /* attempt only the highest enabled protocol (see nego_attempt_*) */ nego->EnabledProtocols[PROTOCOL_HYBRID] = FALSE; nego->EnabledProtocols[PROTOCOL_SSL] = FALSE; nego->EnabledProtocols[PROTOCOL_RDP] = FALSE; nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = FALSE; if (nego->state == NEGO_STATE_EXT) { nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = TRUE; nego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE; nego->SelectedProtocol = PROTOCOL_HYBRID_EX; } else if (nego->state == NEGO_STATE_NLA) { nego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE; nego->SelectedProtocol = PROTOCOL_HYBRID; } else if (nego->state == NEGO_STATE_TLS) { nego->EnabledProtocols[PROTOCOL_SSL] = TRUE; nego->SelectedProtocol = PROTOCOL_SSL; } else if (nego->state == NEGO_STATE_RDP) { nego->EnabledProtocols[PROTOCOL_RDP] = TRUE; nego->SelectedProtocol = PROTOCOL_RDP; } } if (nego->SendPreconnectionPdu) { if (!nego_send_preconnection_pdu(nego)) { WLog_ERR(TAG, "Failed to send preconnection pdu"); nego->state = NEGO_STATE_FINAL; return FALSE; } } } if (!nego->NegotiateSecurityLayer) { nego->state = NEGO_STATE_FINAL; } else { do { WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); nego_send(nego); if (nego->state == NEGO_STATE_FAIL) { if (freerdp_get_last_error(nego->transport->context) == FREERDP_ERROR_SUCCESS) WLog_ERR(TAG, "Protocol Security Negotiation Failure"); nego->state = NEGO_STATE_FINAL; return FALSE; } } while (nego->state != NEGO_STATE_FINAL); } WLog_DBG(TAG, "Negotiated %s security", protocol_security_string(nego->SelectedProtocol)); /* update settings with negotiated protocol security */ settings->RequestedProtocols = nego->RequestedProtocols; settings->SelectedProtocol = nego->SelectedProtocol; settings->NegotiationFlags = nego->flags; if (nego->SelectedProtocol == PROTOCOL_RDP) { settings->UseRdpSecurityLayer = TRUE; if (!settings->EncryptionMethods) { /** * Advertise all supported encryption methods if the client * implementation did not set any security methods */ settings->EncryptionMethods = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_56BIT | ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS; } } /* finally connect security layer (if not already done) */ if (!nego_security_connect(nego)) { WLog_DBG(TAG, "Failed to connect with %s security", protocol_security_string(nego->SelectedProtocol)); return FALSE; } return TRUE; } BOOL nego_disconnect(rdpNego* nego) { nego->state = NEGO_STATE_INITIAL; return nego_transport_disconnect(nego); } /* connect to selected security layer */ BOOL nego_security_connect(rdpNego* nego) { if (!nego->TcpConnected) { nego->SecurityConnected = FALSE; } else if (!nego->SecurityConnected) { if (nego->SelectedProtocol == PROTOCOL_HYBRID) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_HYBRID"); nego->SecurityConnected = transport_connect_nla(nego->transport); } else if (nego->SelectedProtocol == PROTOCOL_SSL) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_SSL"); nego->SecurityConnected = transport_connect_tls(nego->transport); } else if (nego->SelectedProtocol == PROTOCOL_RDP) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_RDP"); nego->SecurityConnected = transport_connect_rdp(nego->transport); } else { WLog_ERR(TAG, "cannot connect security layer because no protocol has been selected yet."); } } return nego->SecurityConnected; } /** * Connect TCP layer. * @param nego * @return */ static BOOL nego_tcp_connect(rdpNego* nego) { if (!nego->TcpConnected) { if (nego->GatewayEnabled) { if (nego->GatewayBypassLocal) { /* Attempt a direct connection first, and then fallback to using the gateway */ WLog_INFO(TAG, "Detecting if host can be reached locally. - This might take some time."); WLog_INFO(TAG, "To disable auto detection use /gateway-usage-method:direct"); transport_set_gateway_enabled(nego->transport, FALSE); nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 1); } if (!nego->TcpConnected) { transport_set_gateway_enabled(nego->transport, TRUE); nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15); } } else { nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15); } } return nego->TcpConnected; } /** * Connect TCP layer. For direct approach, connect security layer as well. * @param nego * @return */ BOOL nego_transport_connect(rdpNego* nego) { if (!nego_tcp_connect(nego)) return FALSE; if (nego->TcpConnected && !nego->NegotiateSecurityLayer) return nego_security_connect(nego); return nego->TcpConnected; } /** * Disconnect TCP layer. * @param nego * @return */ BOOL nego_transport_disconnect(rdpNego* nego) { if (nego->TcpConnected) transport_disconnect(nego->transport); nego->TcpConnected = FALSE; nego->SecurityConnected = FALSE; return TRUE; } /** * Send preconnection information if enabled. * @param nego * @return */ BOOL nego_send_preconnection_pdu(rdpNego* nego) { wStream* s; UINT32 cbSize; UINT16 cchPCB = 0; WCHAR* wszPCB = NULL; WLog_DBG(TAG, "Sending preconnection PDU"); if (!nego_tcp_connect(nego)) return FALSE; /* it's easier to always send the version 2 PDU, and it's just 2 bytes overhead */ cbSize = PRECONNECTION_PDU_V2_MIN_SIZE; if (nego->PreconnectionBlob) { cchPCB = (UINT16)ConvertToUnicode(CP_UTF8, 0, nego->PreconnectionBlob, -1, &wszPCB, 0); cchPCB += 1; /* zero-termination */ cbSize += cchPCB * 2; } s = Stream_New(NULL, cbSize); if (!s) { free(wszPCB); WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } Stream_Write_UINT32(s, cbSize); /* cbSize */ Stream_Write_UINT32(s, 0); /* Flags */ Stream_Write_UINT32(s, PRECONNECTION_PDU_V2); /* Version */ Stream_Write_UINT32(s, nego->PreconnectionId); /* Id */ Stream_Write_UINT16(s, cchPCB); /* cchPCB */ if (wszPCB) { Stream_Write(s, wszPCB, cchPCB * 2); /* wszPCB */ free(wszPCB); } Stream_SealLength(s); if (transport_write(nego->transport, s) < 0) { Stream_Free(s, TRUE); return FALSE; } Stream_Free(s, TRUE); return TRUE; } /** * Attempt negotiating NLA + TLS extended security. * @param nego */ static void nego_attempt_ext(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL | PROTOCOL_HYBRID_EX; WLog_DBG(TAG, "Attempting NLA extended security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_HYBRID]) nego->state = NEGO_STATE_NLA; else if (nego->EnabledProtocols[PROTOCOL_SSL]) nego->state = NEGO_STATE_TLS; else if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating NLA + TLS security. * @param nego */ static void nego_attempt_nla(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL; WLog_DBG(TAG, "Attempting NLA security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_SSL]) nego->state = NEGO_STATE_TLS; else if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating TLS security. * @param nego */ static void nego_attempt_tls(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_SSL; WLog_DBG(TAG, "Attempting TLS security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating standard RDP security. * @param nego */ static void nego_attempt_rdp(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_RDP; WLog_DBG(TAG, "Attempting RDP security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } } /** * Wait to receive a negotiation response * @param nego */ BOOL nego_recv_response(rdpNego* nego) { int status; wStream* s; s = Stream_New(NULL, 1024); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } status = transport_read_pdu(nego->transport, s); if (status < 0) { Stream_Free(s, TRUE); return FALSE; } status = nego_recv(nego->transport, s, nego); Stream_Free(s, TRUE); if (status < 0) return FALSE; return TRUE; } /** * Receive protocol security negotiation message.\n * @msdn{cc240501} * @param transport transport * @param s stream * @param extra nego pointer */ int nego_recv(rdpTransport* transport, wStream* s, void* extra) { BYTE li; BYTE type; UINT16 length; rdpNego* nego = (rdpNego*)extra; if (!tpkt_read_header(s, &length)) return -1; if (!tpdu_read_connection_confirm(s, &li, length)) return -1; if (li > 6) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ switch (type) { case TYPE_RDP_NEG_RSP: nego_process_negotiation_response(nego, s); WLog_DBG(TAG, "selected_protocol: %" PRIu32 "", nego->SelectedProtocol); /* enhanced security selected ? */ if (nego->SelectedProtocol) { if ((nego->SelectedProtocol == PROTOCOL_HYBRID) && (!nego->EnabledProtocols[PROTOCOL_HYBRID])) { nego->state = NEGO_STATE_FAIL; } if ((nego->SelectedProtocol == PROTOCOL_SSL) && (!nego->EnabledProtocols[PROTOCOL_SSL])) { nego->state = NEGO_STATE_FAIL; } } else if (!nego->EnabledProtocols[PROTOCOL_RDP]) { nego->state = NEGO_STATE_FAIL; } break; case TYPE_RDP_NEG_FAILURE: nego_process_negotiation_failure(nego, s); break; } } else if (li == 6) { WLog_DBG(TAG, "no rdpNegData"); if (!nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_FAIL; else nego->state = NEGO_STATE_FINAL; } else { WLog_ERR(TAG, "invalid negotiation response"); nego->state = NEGO_STATE_FAIL; } if (!tpkt_ensure_stream_consumed(s, length)) return -1; return 0; } /** * Read optional routing token or cookie of X.224 Connection Request PDU. * @msdn{cc240470} * @param nego * @param s stream */ static BOOL nego_read_request_token_or_cookie(rdpNego* nego, wStream* s) { /* routingToken and cookie are optional and mutually exclusive! * * routingToken (variable): An optional and variable-length routing * token (used for load balancing) terminated by a 0x0D0A two-byte * sequence: (check [MSFT-SDLBTS] for details!) * Cookie:[space]msts=[ip address].[port].[reserved][\x0D\x0A] * * cookie (variable): An optional and variable-length ANSI character * string terminated by a 0x0D0A two-byte sequence: * Cookie:[space]mstshash=[ANSISTRING][\x0D\x0A] */ BYTE* str = NULL; UINT16 crlf = 0; size_t pos, len; BOOL result = FALSE; BOOL isToken = FALSE; size_t remain = Stream_GetRemainingLength(s); str = Stream_Pointer(s); pos = Stream_GetPosition(s); /* minimum length for token is 15 */ if (remain < 15) return TRUE; if (memcmp(Stream_Pointer(s), "Cookie: mstshash=", 17) != 0) { isToken = TRUE; } else { /* not a token, minimum length for cookie is 19 */ if (remain < 19) return TRUE; Stream_Seek(s, 17); } while ((remain = Stream_GetRemainingLength(s)) >= 2) { Stream_Read_UINT16(s, crlf); if (crlf == 0x0A0D) break; Stream_Rewind(s, 1); } if (crlf == 0x0A0D) { Stream_Rewind(s, 2); len = Stream_GetPosition(s) - pos; remain = Stream_GetRemainingLength(s); Stream_Write_UINT16(s, 0); if (strnlen((char*)str, len) == len) { if (isToken) result = nego_set_routing_token(nego, str, len); else result = nego_set_cookie(nego, (char*)str); } } if (!result) { Stream_SetPosition(s, pos); WLog_ERR(TAG, "invalid %s received", isToken ? "routing token" : "cookie"); } else { WLog_DBG(TAG, "received %s [%s]", isToken ? "routing token" : "cookie", str); } return result; } /** * Read protocol security negotiation request message.\n * @param nego * @param s stream */ BOOL nego_read_request(rdpNego* nego, wStream* s) { BYTE li; BYTE type; UINT16 length; if (!tpkt_read_header(s, &length)) return FALSE; if (!tpdu_read_connection_request(s, &li, length)) return FALSE; if (li != Stream_GetRemainingLength(s) + 6) { WLog_ERR(TAG, "Incorrect TPDU length indicator."); return FALSE; } if (!nego_read_request_token_or_cookie(nego, s)) { WLog_ERR(TAG, "Failed to parse routing token or cookie."); return FALSE; } if (Stream_GetRemainingLength(s) >= 8) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ if (type != TYPE_RDP_NEG_REQ) { WLog_ERR(TAG, "Incorrect negotiation request type %" PRIu8 "", type); return FALSE; } nego_process_negotiation_request(nego, s); } return tpkt_ensure_stream_consumed(s, length); } /** * Send protocol security negotiation message. * @param nego */ void nego_send(rdpNego* nego) { if (nego->state == NEGO_STATE_EXT) nego_attempt_ext(nego); else if (nego->state == NEGO_STATE_NLA) nego_attempt_nla(nego); else if (nego->state == NEGO_STATE_TLS) nego_attempt_tls(nego); else if (nego->state == NEGO_STATE_RDP) nego_attempt_rdp(nego); else WLog_ERR(TAG, "invalid negotiation state for sending"); } /** * Send RDP Negotiation Request (RDP_NEG_REQ).\n * @msdn{cc240500}\n * @msdn{cc240470} * @param nego */ BOOL nego_send_negotiation_request(rdpNego* nego) { BOOL rc = FALSE; wStream* s; size_t length; size_t bm, em; BYTE flags = 0; size_t cookie_length; s = Stream_New(NULL, 512); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } length = TPDU_CONNECTION_REQUEST_LENGTH; bm = Stream_GetPosition(s); Stream_Seek(s, length); if (nego->RoutingToken) { Stream_Write(s, nego->RoutingToken, nego->RoutingTokenLength); /* Ensure Routing Token is correctly terminated - may already be present in string */ if ((nego->RoutingTokenLength > 2) && (nego->RoutingToken[nego->RoutingTokenLength - 2] == 0x0D) && (nego->RoutingToken[nego->RoutingTokenLength - 1] == 0x0A)) { WLog_DBG(TAG, "Routing token looks correctly terminated - use verbatim"); length += nego->RoutingTokenLength; } else { WLog_DBG(TAG, "Adding terminating CRLF to routing token"); Stream_Write_UINT8(s, 0x0D); /* CR */ Stream_Write_UINT8(s, 0x0A); /* LF */ length += nego->RoutingTokenLength + 2; } } else if (nego->cookie) { cookie_length = strlen(nego->cookie); if (cookie_length > nego->CookieMaxLength) cookie_length = nego->CookieMaxLength; Stream_Write(s, "Cookie: mstshash=", 17); Stream_Write(s, (BYTE*)nego->cookie, cookie_length); Stream_Write_UINT8(s, 0x0D); /* CR */ Stream_Write_UINT8(s, 0x0A); /* LF */ length += cookie_length + 19; } WLog_DBG(TAG, "RequestedProtocols: %" PRIu32 "", nego->RequestedProtocols); if ((nego->RequestedProtocols > PROTOCOL_RDP) || (nego->sendNegoData)) { /* RDP_NEG_DATA must be present for TLS and NLA */ if (nego->RestrictedAdminModeRequired) flags |= RESTRICTED_ADMIN_MODE_REQUIRED; Stream_Write_UINT8(s, TYPE_RDP_NEG_REQ); Stream_Write_UINT8(s, flags); Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, nego->RequestedProtocols); /* requestedProtocols */ length += 8; } if (length > UINT16_MAX) goto fail; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); tpkt_write_header(s, (UINT16)length); tpdu_write_connection_request(s, (UINT16)length - 5); Stream_SetPosition(s, em); Stream_SealLength(s); rc = (transport_write(nego->transport, s) >= 0); fail: Stream_Free(s, TRUE); return rc; } /** * Process Negotiation Request from Connection Request message. * @param nego * @param s */ void nego_process_negotiation_request(rdpNego* nego, wStream* s) { BYTE flags; UINT16 length; Stream_Read_UINT8(s, flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->RequestedProtocols); WLog_DBG(TAG, "RDP_NEG_REQ: RequestedProtocol: 0x%08" PRIX32 "", nego->RequestedProtocols); nego->state = NEGO_STATE_FINAL; } /** * Process Negotiation Response from Connection Confirm message. * @param nego * @param s */ void nego_process_negotiation_response(rdpNego* nego, wStream* s) { UINT16 length; WLog_DBG(TAG, "RDP_NEG_RSP"); if (Stream_GetRemainingLength(s) < 7) { WLog_ERR(TAG, "Invalid RDP_NEG_RSP"); nego->state = NEGO_STATE_FAIL; return; } Stream_Read_UINT8(s, nego->flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->SelectedProtocol); nego->state = NEGO_STATE_FINAL; } /** * Process Negotiation Failure from Connection Confirm message. * @param nego * @param s */ void nego_process_negotiation_failure(rdpNego* nego, wStream* s) { BYTE flags; UINT16 length; UINT32 failureCode; WLog_DBG(TAG, "RDP_NEG_FAILURE"); Stream_Read_UINT8(s, flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, failureCode); switch (failureCode) { case SSL_REQUIRED_BY_SERVER: WLog_WARN(TAG, "Error: SSL_REQUIRED_BY_SERVER"); break; case SSL_NOT_ALLOWED_BY_SERVER: WLog_WARN(TAG, "Error: SSL_NOT_ALLOWED_BY_SERVER"); nego->sendNegoData = TRUE; break; case SSL_CERT_NOT_ON_SERVER: WLog_ERR(TAG, "Error: SSL_CERT_NOT_ON_SERVER"); nego->sendNegoData = TRUE; break; case INCONSISTENT_FLAGS: WLog_ERR(TAG, "Error: INCONSISTENT_FLAGS"); break; case HYBRID_REQUIRED_BY_SERVER: WLog_WARN(TAG, "Error: HYBRID_REQUIRED_BY_SERVER"); break; default: WLog_ERR(TAG, "Error: Unknown protocol security error %" PRIu32 "", failureCode); break; } nego->state = NEGO_STATE_FAIL; } /** * Send RDP Negotiation Response (RDP_NEG_RSP).\n * @param nego */ BOOL nego_send_negotiation_response(rdpNego* nego) { UINT16 length; size_t bm, em; BOOL status; wStream* s; BYTE flags; rdpSettings* settings; status = TRUE; settings = nego->transport->settings; s = Stream_New(NULL, 512); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } length = TPDU_CONNECTION_CONFIRM_LENGTH; bm = Stream_GetPosition(s); Stream_Seek(s, length); if (nego->SelectedProtocol & PROTOCOL_FAILED_NEGO) { UINT32 errorCode = (nego->SelectedProtocol & ~PROTOCOL_FAILED_NEGO); flags = 0; Stream_Write_UINT8(s, TYPE_RDP_NEG_FAILURE); Stream_Write_UINT8(s, flags); /* flags */ Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, errorCode); length += 8; status = FALSE; } else { flags = EXTENDED_CLIENT_DATA_SUPPORTED; if (settings->SupportGraphicsPipeline) flags |= DYNVC_GFX_PROTOCOL_SUPPORTED; /* RDP_NEG_DATA must be present for TLS, NLA, and RDP */ Stream_Write_UINT8(s, TYPE_RDP_NEG_RSP); Stream_Write_UINT8(s, flags); /* flags */ Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, nego->SelectedProtocol); /* selectedProtocol */ length += 8; } em = Stream_GetPosition(s); Stream_SetPosition(s, bm); tpkt_write_header(s, length); tpdu_write_connection_confirm(s, length - 5); Stream_SetPosition(s, em); Stream_SealLength(s); if (transport_write(nego->transport, s) < 0) { Stream_Free(s, TRUE); return FALSE; } Stream_Free(s, TRUE); if (status) { /* update settings with negotiated protocol security */ settings->RequestedProtocols = nego->RequestedProtocols; settings->SelectedProtocol = nego->SelectedProtocol; if (settings->SelectedProtocol == PROTOCOL_RDP) { settings->TlsSecurity = FALSE; settings->NlaSecurity = FALSE; settings->RdpSecurity = TRUE; settings->UseRdpSecurityLayer = TRUE; if (settings->EncryptionLevel == ENCRYPTION_LEVEL_NONE) { /** * If the server implementation did not explicitely set a * encryption level we default to client compatible */ settings->EncryptionLevel = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE; } if (settings->LocalConnection) { /** * Note: This hack was firstly introduced in commit 95f5e115 to * disable the unnecessary encryption with peers connecting to * 127.0.0.1 or local unix sockets. * This also affects connections via port tunnels! (e.g. ssh -L) */ WLog_INFO(TAG, "Turning off encryption for local peer with standard rdp security"); settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } if (!settings->RdpServerRsaKey && !settings->RdpKeyFile && !settings->RdpKeyContent) { WLog_ERR(TAG, "Missing server certificate"); return FALSE; } } else if (settings->SelectedProtocol == PROTOCOL_SSL) { settings->TlsSecurity = TRUE; settings->NlaSecurity = FALSE; settings->RdpSecurity = FALSE; settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } else if (settings->SelectedProtocol == PROTOCOL_HYBRID) { settings->TlsSecurity = TRUE; settings->NlaSecurity = TRUE; settings->RdpSecurity = FALSE; settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } } return status; } /** * Initialize NEGO state machine. * @param nego */ void nego_init(rdpNego* nego) { nego->state = NEGO_STATE_INITIAL; nego->RequestedProtocols = PROTOCOL_RDP; nego->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH; nego->sendNegoData = FALSE; nego->flags = 0; } /** * Create a new NEGO state machine instance. * @param transport * @return */ rdpNego* nego_new(rdpTransport* transport) { rdpNego* nego = (rdpNego*)calloc(1, sizeof(rdpNego)); if (!nego) return NULL; nego->transport = transport; nego_init(nego); return nego; } /** * Free NEGO state machine. * @param nego */ void nego_free(rdpNego* nego) { if (nego) { free(nego->RoutingToken); free(nego->cookie); free(nego); } } /** * Set target hostname and port. * @param nego * @param hostname * @param port */ BOOL nego_set_target(rdpNego* nego, const char* hostname, UINT16 port) { if (!nego || !hostname) return FALSE; nego->hostname = hostname; nego->port = port; return TRUE; } /** * Enable security layer negotiation. * @param nego pointer to the negotiation structure * @param enable_rdp whether to enable security layer negotiation (TRUE for enabled, FALSE for * disabled) */ void nego_set_negotiation_enabled(rdpNego* nego, BOOL NegotiateSecurityLayer) { WLog_DBG(TAG, "Enabling security layer negotiation: %s", NegotiateSecurityLayer ? "TRUE" : "FALSE"); nego->NegotiateSecurityLayer = NegotiateSecurityLayer; } /** * Enable restricted admin mode. * @param nego pointer to the negotiation structure * @param enable_restricted whether to enable security layer negotiation (TRUE for enabled, FALSE * for disabled) */ void nego_set_restricted_admin_mode_required(rdpNego* nego, BOOL RestrictedAdminModeRequired) { WLog_DBG(TAG, "Enabling restricted admin mode: %s", RestrictedAdminModeRequired ? "TRUE" : "FALSE"); nego->RestrictedAdminModeRequired = RestrictedAdminModeRequired; } void nego_set_gateway_enabled(rdpNego* nego, BOOL GatewayEnabled) { nego->GatewayEnabled = GatewayEnabled; } void nego_set_gateway_bypass_local(rdpNego* nego, BOOL GatewayBypassLocal) { nego->GatewayBypassLocal = GatewayBypassLocal; } /** * Enable RDP security protocol. * @param nego pointer to the negotiation structure * @param enable_rdp whether to enable normal RDP protocol (TRUE for enabled, FALSE for disabled) */ void nego_enable_rdp(rdpNego* nego, BOOL enable_rdp) { WLog_DBG(TAG, "Enabling RDP security: %s", enable_rdp ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_RDP] = enable_rdp; } /** * Enable TLS security protocol. * @param nego pointer to the negotiation structure * @param enable_tls whether to enable TLS + RDP protocol (TRUE for enabled, FALSE for disabled) */ void nego_enable_tls(rdpNego* nego, BOOL enable_tls) { WLog_DBG(TAG, "Enabling TLS security: %s", enable_tls ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_SSL] = enable_tls; } /** * Enable NLA security protocol. * @param nego pointer to the negotiation structure * @param enable_nla whether to enable network level authentication protocol (TRUE for enabled, * FALSE for disabled) */ void nego_enable_nla(rdpNego* nego, BOOL enable_nla) { WLog_DBG(TAG, "Enabling NLA security: %s", enable_nla ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_HYBRID] = enable_nla; } /** * Enable NLA extended security protocol. * @param nego pointer to the negotiation structure * @param enable_ext whether to enable network level authentication extended protocol (TRUE for * enabled, FALSE for disabled) */ void nego_enable_ext(rdpNego* nego, BOOL enable_ext) { WLog_DBG(TAG, "Enabling NLA extended security: %s", enable_ext ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = enable_ext; } /** * Set routing token. * @param nego * @param RoutingToken * @param RoutingTokenLength */ BOOL nego_set_routing_token(rdpNego* nego, BYTE* RoutingToken, DWORD RoutingTokenLength) { if (RoutingTokenLength == 0) return FALSE; free(nego->RoutingToken); nego->RoutingTokenLength = RoutingTokenLength; nego->RoutingToken = (BYTE*)malloc(nego->RoutingTokenLength); if (!nego->RoutingToken) return FALSE; CopyMemory(nego->RoutingToken, RoutingToken, nego->RoutingTokenLength); return TRUE; } /** * Set cookie. * @param nego * @param cookie */ BOOL nego_set_cookie(rdpNego* nego, char* cookie) { if (nego->cookie) { free(nego->cookie); nego->cookie = NULL; } if (!cookie) return TRUE; nego->cookie = _strdup(cookie); if (!nego->cookie) return FALSE; return TRUE; } /** * Set cookie maximum length * @param nego * @param CookieMaxLength */ void nego_set_cookie_max_length(rdpNego* nego, UINT32 CookieMaxLength) { nego->CookieMaxLength = CookieMaxLength; } /** * Enable / disable preconnection PDU. * @param nego * @param send_pcpdu */ void nego_set_send_preconnection_pdu(rdpNego* nego, BOOL SendPreconnectionPdu) { nego->SendPreconnectionPdu = SendPreconnectionPdu; } /** * Set preconnection id. * @param nego * @param id */ void nego_set_preconnection_id(rdpNego* nego, UINT32 PreconnectionId) { nego->PreconnectionId = PreconnectionId; } /** * Set preconnection blob. * @param nego * @param blob */ void nego_set_preconnection_blob(rdpNego* nego, char* PreconnectionBlob) { nego->PreconnectionBlob = PreconnectionBlob; } UINT32 nego_get_selected_protocol(rdpNego* nego) { if (!nego) return 0; return nego->SelectedProtocol; } BOOL nego_set_selected_protocol(rdpNego* nego, UINT32 SelectedProtocol) { if (!nego) return FALSE; nego->SelectedProtocol = SelectedProtocol; return TRUE; } UINT32 nego_get_requested_protocols(rdpNego* nego) { if (!nego) return 0; return nego->RequestedProtocols; } BOOL nego_set_requested_protocols(rdpNego* nego, UINT32 RequestedProtocols) { if (!nego) return FALSE; nego->RequestedProtocols = RequestedProtocols; return TRUE; } NEGO_STATE nego_get_state(rdpNego* nego) { if (!nego) return NEGO_STATE_FAIL; return nego->state; } BOOL nego_set_state(rdpNego* nego, NEGO_STATE state) { if (!nego) return FALSE; nego->state = state; return TRUE; } SEC_WINNT_AUTH_IDENTITY* nego_get_identity(rdpNego* nego) { if (!nego) return NULL; return nla_get_identity(nego->transport->nla); } void nego_free_nla(rdpNego* nego) { if (!nego || !nego->transport) return; nla_free(nego->transport->nla); nego->transport->nla = NULL; } const BYTE* nego_get_routing_token(rdpNego* nego, DWORD* RoutingTokenLength) { if (!nego) return NULL; if (RoutingTokenLength) *RoutingTokenLength = nego->RoutingTokenLength; return nego->RoutingToken; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_5
crossvul-cpp_data_bad_2644_5
/* $OpenBSD: print-gre.c,v 1.6 2002/10/30 03:04:04 fgsch Exp $ */ /* * Copyright (c) 2002 Jason L. Wright (jason@thought.net) * 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. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Jason L. Wright * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* \summary: Generic Routing Encapsulation (GRE) printer */ /* * netdissect printer for GRE - Generic Routing Encapsulation * RFC1701 (GRE), RFC1702 (GRE IPv4), and RFC2637 (Enhanced GRE) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtostr.h" #include "extract.h" #include "ethertype.h" static const char tstr[] = "[|gre]"; #define GRE_CP 0x8000 /* checksum present */ #define GRE_RP 0x4000 /* routing present */ #define GRE_KP 0x2000 /* key present */ #define GRE_SP 0x1000 /* sequence# present */ #define GRE_sP 0x0800 /* source routing */ #define GRE_RECRS 0x0700 /* recursion count */ #define GRE_AP 0x0080 /* acknowledgment# present */ static const struct tok gre_flag_values[] = { { GRE_CP, "checksum present"}, { GRE_RP, "routing present"}, { GRE_KP, "key present"}, { GRE_SP, "sequence# present"}, { GRE_sP, "source routing present"}, { GRE_RECRS, "recursion count"}, { GRE_AP, "ack present"}, { 0, NULL } }; #define GRE_VERS_MASK 0x0007 /* protocol version */ /* source route entry types */ #define GRESRE_IP 0x0800 /* IP */ #define GRESRE_ASN 0xfffe /* ASN */ static void gre_print_0(netdissect_options *, const u_char *, u_int); static void gre_print_1(netdissect_options *, const u_char *, u_int); static int gre_sre_print(netdissect_options *, uint16_t, uint8_t, uint8_t, const u_char *, u_int); static int gre_sre_ip_print(netdissect_options *, uint8_t, uint8_t, const u_char *, u_int); static int gre_sre_asn_print(netdissect_options *, uint8_t, uint8_t, const u_char *, u_int); void gre_print(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length, vers; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; vers = EXTRACT_16BITS(bp) & GRE_VERS_MASK; ND_PRINT((ndo, "GREv%u",vers)); switch(vers) { case 0: gre_print_0(ndo, bp, len); break; case 1: gre_print_1(ndo, bp, len); break; default: ND_PRINT((ndo, " ERROR: unknown-version")); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } static void gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length; uint16_t flags, prot; /* 16 bits ND_TCHECKed in gre_print() */ flags = EXTRACT_16BITS(bp); if (ndo->ndo_vflag) ND_PRINT((ndo, ", Flags [%s]", bittok2str(gre_flag_values,"none",flags))); len -= 2; bp += 2; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; prot = EXTRACT_16BITS(bp); len -= 2; bp += 2; if ((flags & GRE_CP) | (flags & GRE_RP)) { ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; if (ndo->ndo_vflag) ND_PRINT((ndo, ", sum 0x%x", EXTRACT_16BITS(bp))); bp += 2; len -= 2; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; ND_PRINT((ndo, ", off 0x%x", EXTRACT_16BITS(bp))); bp += 2; len -= 2; } if (flags & GRE_KP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", key=0x%x", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_SP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_RP) { for (;;) { uint16_t af; uint8_t sreoff; uint8_t srelen; ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; af = EXTRACT_16BITS(bp); sreoff = *(bp + 2); srelen = *(bp + 3); bp += 4; len -= 4; if (af == 0 && srelen == 0) break; if (!gre_sre_print(ndo, af, sreoff, srelen, bp, len)) goto trunc; if (len < srelen) goto trunc; bp += srelen; len -= srelen; } } if (ndo->ndo_eflag) ND_PRINT((ndo, ", proto %s (0x%04x)", tok2str(ethertype_values,"unknown",prot), prot)); ND_PRINT((ndo, ", length %u",length)); if (ndo->ndo_vflag < 1) ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */ else ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */ switch (prot) { case ETHERTYPE_IP: ip_print(ndo, bp, len); break; case ETHERTYPE_IPV6: ip6_print(ndo, bp, len); break; case ETHERTYPE_MPLS: mpls_print(ndo, bp, len); break; case ETHERTYPE_IPX: ipx_print(ndo, bp, len); break; case ETHERTYPE_ATALK: atalk_print(ndo, bp, len); break; case ETHERTYPE_GRE_ISO: isoclns_print(ndo, bp, len, ndo->ndo_snapend - bp); break; case ETHERTYPE_TEB: ether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL); break; default: ND_PRINT((ndo, "gre-proto-0x%x", prot)); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void gre_print_1(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length; uint16_t flags, prot; /* 16 bits ND_TCHECKed in gre_print() */ flags = EXTRACT_16BITS(bp); len -= 2; bp += 2; if (ndo->ndo_vflag) ND_PRINT((ndo, ", Flags [%s]", bittok2str(gre_flag_values,"none",flags))); ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; prot = EXTRACT_16BITS(bp); len -= 2; bp += 2; if (flags & GRE_KP) { uint32_t k; ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; k = EXTRACT_32BITS(bp); ND_PRINT((ndo, ", call %d", k & 0xffff)); len -= 4; bp += 4; } if (flags & GRE_SP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_AP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", ack %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if ((flags & GRE_SP) == 0) ND_PRINT((ndo, ", no-payload")); if (ndo->ndo_eflag) ND_PRINT((ndo, ", proto %s (0x%04x)", tok2str(ethertype_values,"unknown",prot), prot)); ND_PRINT((ndo, ", length %u",length)); if ((flags & GRE_SP) == 0) return; if (ndo->ndo_vflag < 1) ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */ else ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */ switch (prot) { case ETHERTYPE_PPP: ppp_print(ndo, bp, len); break; default: ND_PRINT((ndo, "gre-proto-0x%x", prot)); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static int gre_sre_print(netdissect_options *ndo, uint16_t af, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { int ret; switch (af) { case GRESRE_IP: ND_PRINT((ndo, ", (rtaf=ip")); ret = gre_sre_ip_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; case GRESRE_ASN: ND_PRINT((ndo, ", (rtaf=asn")); ret = gre_sre_asn_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; default: ND_PRINT((ndo, ", (rtaf=0x%x)", af)); ret = 1; } return (ret); } static int gre_sre_ip_print(netdissect_options *ndo, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { const u_char *up = bp; char buf[INET_ADDRSTRLEN]; if (sreoff & 3) { ND_PRINT((ndo, ", badoffset=%u", sreoff)); return (1); } if (srelen & 3) { ND_PRINT((ndo, ", badlength=%u", srelen)); return (1); } if (sreoff >= srelen) { ND_PRINT((ndo, ", badoff/len=%u/%u", sreoff, srelen)); return (1); } while (srelen != 0) { if (!ND_TTEST2(*bp, 4)) return (0); if (len < 4) return (0); addrtostr(bp, buf, sizeof(buf)); ND_PRINT((ndo, " %s%s", ((bp - up) == sreoff) ? "*" : "", buf)); bp += 4; len -= 4; srelen -= 4; } return (1); } static int gre_sre_asn_print(netdissect_options *ndo, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { const u_char *up = bp; if (sreoff & 1) { ND_PRINT((ndo, ", badoffset=%u", sreoff)); return (1); } if (srelen & 1) { ND_PRINT((ndo, ", badlength=%u", srelen)); return (1); } if (sreoff >= srelen) { ND_PRINT((ndo, ", badoff/len=%u/%u", sreoff, srelen)); return (1); } while (srelen != 0) { if (!ND_TTEST2(*bp, 2)) return (0); if (len < 2) return (0); ND_PRINT((ndo, " %s%x", ((bp - up) == sreoff) ? "*" : "", EXTRACT_16BITS(bp))); bp += 2; len -= 2; srelen -= 2; } return (1); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_5
crossvul-cpp_data_bad_235_0
/* radare2 - LGPL - Copyright 2016-2017 - Davis, Alex Kornitzer */ #include <r_util.h> #include "mdmp.h" ut64 r_bin_mdmp_get_paddr(struct r_bin_mdmp_obj *obj, ut64 vaddr) { /* FIXME: Will only resolve exact matches, probably no need to fix as ** this function will become redundant on the optimisation stage */ struct minidump_memory_descriptor64 *memory; ut64 index, paddr = 0; RListIter *it; /* Loop through the memories sections looking for a match */ index = obj->streams.memories64.base_rva; r_list_foreach (obj->streams.memories64.memories, it, memory) { if (vaddr == memory->start_of_memory_range) { paddr = index; break; } index += memory->data_size; } return paddr; } struct minidump_memory_info *r_bin_mdmp_get_mem_info(struct r_bin_mdmp_obj *obj, ut64 vaddr) { struct minidump_memory_info *mem_info; RListIter *it; if (!obj) return NULL; r_list_foreach (obj->streams.memory_infos, it, mem_info) { if (mem_info->allocation_base && vaddr == mem_info->base_address) { return mem_info; } } return NULL; } ut32 r_bin_mdmp_get_srwx(struct r_bin_mdmp_obj *obj, ut64 vaddr) { struct minidump_memory_info *mem_info; if (!(mem_info = r_bin_mdmp_get_mem_info(obj, vaddr))) { return 0; } /* FIXME: Have I got these mappings right, I am not sure I have!!! */ switch (mem_info->protect) { case MINIDUMP_PAGE_READONLY: return R_BIN_SCN_READABLE; case MINIDUMP_PAGE_READWRITE: return R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE; case MINIDUMP_PAGE_EXECUTE: return R_BIN_SCN_EXECUTABLE; case MINIDUMP_PAGE_EXECUTE_READ: return R_BIN_SCN_EXECUTABLE | R_BIN_SCN_READABLE; case MINIDUMP_PAGE_EXECUTE_READWRITE: return R_BIN_SCN_EXECUTABLE | R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE; case MINIDUMP_PAGE_NOACCESS: case MINIDUMP_PAGE_WRITECOPY: case MINIDUMP_PAGE_EXECUTE_WRITECOPY: case MINIDUMP_PAGE_GUARD: case MINIDUMP_PAGE_NOCACHE: case MINIDUMP_PAGE_WRITECOMBINE: default: return 0; } } static void r_bin_mdmp_free_pe32_bin(void *pe_bin_) { struct Pe32_r_bin_mdmp_pe_bin *pe_bin = pe_bin_; if (pe_bin) { sdb_free (pe_bin->bin->kv); Pe32_r_bin_pe_free (pe_bin->bin); R_FREE (pe_bin); } } static void r_bin_mdmp_free_pe64_bin(void *pe_bin_) { struct Pe64_r_bin_mdmp_pe_bin *pe_bin = pe_bin_; if (pe_bin) { sdb_free (pe_bin->bin->kv); Pe64_r_bin_pe_free (pe_bin->bin); R_FREE (pe_bin); } } void r_bin_mdmp_free(struct r_bin_mdmp_obj *obj) { if (!obj) return; r_list_free (obj->streams.ex_threads); r_list_free (obj->streams.memories); r_list_free (obj->streams.memories64.memories); r_list_free (obj->streams.memory_infos); r_list_free (obj->streams.modules); r_list_free (obj->streams.operations); r_list_free (obj->streams.thread_infos); r_list_free (obj->streams.threads); r_list_free (obj->streams.unloaded_modules); r_list_free (obj->pe32_bins); r_list_free (obj->pe64_bins); r_buf_free (obj->b); obj->b = NULL; free (obj); return; } static void r_bin_mdmp_init_parsing(struct r_bin_mdmp_obj *obj) { /* TODO: Handle unions, can we? */ /* FIXME: Why are we getting struct missing errors when it finds them */ sdb_set (obj->kv, "mdmp_mem_state.cparse", "enum mdmp_mem_state { MEM_COMMIT=0x1000, " "MEM_FREE=0x10000, MEM_RESERVE=0x02000 };", 0); sdb_set (obj->kv, "mdmp_mem_type.cparse", "enum mdmp_mem_type { MEM_IMAGE=0x1000000, " "MEM_MAPPED=0x40000, MEM_PRIVATE=0x20000 };", 0); sdb_set (obj->kv, "mdmp_page_protect.cparse", "enum mdmp_page_protect { PAGE_NOACCESS=1, " "PAGE_READONLY=2, PAGE_READWRITE=4, PAGE_WRITECOPY=8, " "PAGE_EXECUTE=0x10, PAGE_EXECUTE_READ=0x20, " "PAGE_EXECUTE_READWRITE=0x40, PAGE_EXECUTE_WRITECOPY=0x80, " "PAGE_GUARD=0x100, PAGE_NOCACHE=0x200, " "PAGE_WRITECOMBINE=0x400, PAGE_TARGETS_INVALID=0x40000000 };", 0); sdb_set (obj->kv, "mdmp_misc1_flags.cparse", "enum mdmp_misc1_flags { MINIDUMP_MISC1_PROCESS_ID=1, " "MINIDUMP_MISC1_PROCESS_TIMES=2, " "MINIDUMP_MISC1_PROCESSOR_POWER_INFO=4 };", 0); sdb_set (obj->kv, "mdmp_processor_architecture.cparse", "enum mdmp_processor_architecture { " "PROCESSOR_ARCHITECTURE_INTEL=0, " "PROCESSOR_ARCHITECTURE_ARM=5, " "PROCESSOR_ARCHITECTURE_IA64=6, " "PROCESSOR_ARCHITECTURE_AMD64=9, " "PROCESSOR_ARCHITECTURE_UNKNOWN=0xffff };", 0); sdb_set (obj->kv, "mdmp_product_type.cparse", "enum mdmp_product_type { " "VER_NT_WORKSTATION=1, VER_NT_DOMAIN_CONTROLLER=2, " "VER_NT_SERVER=3 };", 0); sdb_set (obj->kv, "mdmp_platform_id.cparse", "enum mdmp_platform_id { " "VER_PLATFORM_WIN32s=0, " "VER_PLATFORM_WIN32_WINDOWS=1, " "VER_PLATFORM_WIN32_NT=2 };", 0); sdb_set (obj->kv, "mdmp_suite_mask.cparse", "enum mdmp_suite_mask { " "VER_SUITE_SMALLBUSINESS=1, VER_SUITE_ENTERPRISE=2, " "VER_SUITE_BACKOFFICE=4, VER_SUITE_TERMINAL=0x10, " "VER_SUITE_SMALLBUSINESS_RESTRICTED=0x20, " "VER_SUITE_EMBEDDEDNT=0x40, VER_SUITE_DATACENTER=0x80, " "VER_SUITE_SINGLEUSERTS=0x100, VER_SUITE_PERSONAL=0x200, " "VER_SUITE_BLADE=0x400, VER_SUITE_STORAGE_SERVER=0x2000, " "VER_SUITE_COMPUTE_SERVER=0x4000 };", 0); sdb_set (obj->kv, "mdmp_callback_type.cparse", "enum mdmp_type { ModuleCallback=0," "ThreadCallback=1, ThreadExCallback=2, " "IncludeThreadCallback=3, IncludeModuleCallback=4, " "MemoryCallback=5, CancelCallback=6, " "WriteKernelMinidumpCallback=7, " "KernelMinidumpStatusCallback=8, " "RemoveMemoryCallback=9, " "IncludeVmRegionCallback=10, " "IoStartCallback=11, IoWriteAllCallback=12, " "IoFinishCallback=13, ReadMemoryFailureCallback=14, " "SecondaryFlagsCallback=15 };", 0); sdb_set (obj->kv, "mdmp_exception_code.cparse", "enum mdmp_exception_code { " "DBG_CONTROL_C=0x40010005, " "EXCEPTION_GUARD_PAGE_VIOLATION=0x80000001, " "EXCEPTION_DATATYPE_MISALIGNMENT=0x80000002, " "EXCEPTION_BREAKPOINT=0x80000003, " "EXCEPTION_SINGLE_STEP=0x80000004, " "EXCEPTION_ACCESS_VIOLATION=0xc0000005, " "EXCEPTION_IN_PAGE_ERROR=0xc0000006, " "EXCEPTION_INVALID_HANDLE=0xc0000008, " "EXCEPTION_ILLEGAL_INSTRUCTION=0xc000001d, " "EXCEPTION_NONCONTINUABLE_EXCEPTION=0xc0000025, " "EXCEPTION_INVALID_DISPOSITION=0xc0000026, " "EXCEPTION_ARRAY_BOUNDS_EXCEEDED=0xc000008c, " "EXCEPTION_FLOAT_DENORMAL_OPERAND=0xc000008d, " "EXCEPTION_FLOAT_DIVIDE_BY_ZERO=0xc000008e, " "EXCEPTION_FLOAT_INEXACT_RESULT=0xc000008f, " "EXCEPTION_FLOAT_INVALID_OPERATION=0xc0000090, " "EXCEPTION_FLOAT_OVERFLOW=0xc0000091, " "EXCEPTION_FLOAT_STACK_CHECK=0xc0000092, " "EXCEPTION_FLOAT_UNDERFLOW=0xc0000093, " "EXCEPTION_INTEGER_DIVIDE_BY_ZERO=0xc0000094, " "EXCEPTION_INTEGER_OVERFLOW=0xc0000095, " "EXCEPTION_PRIVILEGED_INSTRUCTION=0xc0000096, " "EXCEPTION_STACK_OVERFLOW=0xc00000fd, " "EXCEPTION_POSSIBLE_DEADLOCK=0xc0000194 };", 0); sdb_set (obj->kv, "mdmp_exception_flags.cparse", "enum mdmp_exception_flags { " "EXCEPTION_CONTINUABLE=0, " "EXCEPTION_NONCONTINUABLE=1 };", 0); sdb_set (obj->kv, "mdmp_handle_object_information_type.cparse", "enum mdmp_handle_object_information_type { " "MiniHandleObjectInformationNone=0, " "MiniThreadInformation1=1, MiniMutantInformation1=2, " "MiniMutantInformation2=3, MiniMutantProcessInformation1=4, " "MiniProcessInformation2=5 };", 0); sdb_set (obj->kv, "mdmp_secondary_flags.cparse", "enum mdmp_secondary_flags { " "MiniSecondaryWithoutPowerInfo=0 };", 0); sdb_set (obj->kv, "mdmp_stream_type.cparse", "enum mdmp_stream_type { UnusedStream=0, " "ReservedStream0=1, ReservedStream1=2, " "ThreadListStream=3, ModuleListStream=4, " "MemoryListStream=5, ExceptionStream=6, " "SystemInfoStream=7, ThreadExListStream=8, " "Memory64ListStream=9, CommentStreamA=10, " "CommentStreamW=11, HandleDataStream=12, " "FunctionTableStream=13, UnloadedModuleListStream=14, " "MiscInfoStream=15, MemoryInfoListStream=16, " "ThreadInfoListStream=17, " "HandleOperationListStream=18, " "LastReservedStream=0xffff };", 0); sdb_set (obj->kv, "mdmp_type.cparse", "enum mdmp_type { " "MiniDumpNormal=0x0, " "MiniDumpWithDataSegs=0x1, " "MiniDumpWithFullMemory=0x2, " "MiniDumpWithHandleData=0x4, " "MiniDumpFilterMemory=0x8, " "MiniDumpScanMemory=0x10, " "MiniDumpWithUnloadedModule=0x20, " "MiniDumpWihinDirectlyReferencedMemory=0x40, " "MiniDumpFilterWithModulePaths=0x80," "MiniDumpWithProcessThreadData=0x100, " "MiniDumpWithPrivateReadWriteMemory=0x200, " "MiniDumpWithoutOptionalDate=0x400, " "MiniDumpWithFullMemoryInfo=0x800, " "MiniDumpWithThreadInfo=0x1000, " "MiniDumpWithCodeSegs=0x2000, " "MiniDumpWithoutAuxiliaryState=0x4000, " "MiniDumpWithFullAuxiliaryState=0x8000, " "MiniDumpWithPrivateWriteCopyMemory=0x10000, " "MiniDumpIgnoreInaccessibleMemory=0x20000, " "MiniDumpWithTokenInformation=0x40000, " "MiniDumpWithModuleHeaders=0x80000, " "MiniDumpFilterTriage=0x100000, " "MiniDumpValidTypeFlags=0x1fffff };", 0); sdb_set (obj->kv, "mdmp_module_write_flags.cparse", "enum mdmp_module_write_flags { " "ModuleWriteModule=0, ModuleWriteDataSeg=2, " "ModuleWriteMiscRecord=4, ModuleWriteCvRecord=8, " "ModuleReferencedByMemory=0x10, ModuleWriteTlsData=0x20, " "ModuleWriteCodeSegs=0x40 };", 0); sdb_set (obj->kv, "mdmp_thread_write_flags.cparse", "enum mdmp_thread_write_flags { " "ThreadWriteThread=0, ThreadWriteStack=2, " "ThreadWriteContext=4, ThreadWriteBackingStore=8, " "ThreadWriteInstructionWindow=0x10, " "ThreadWriteThreadData=0x20, " "ThreadWriteThreadInfo=0x40 };", 0); sdb_set (obj->kv, "mdmp_context_flags.cparse", "enum mdmp_context_flags { CONTEXT_i386=0x10000, " "CONTEXT_CONTROL=0x10001, CONTEXT_INTEGER=0x10002, " "CONTEXT_SEGMENTS=0x10004, CONTEXT_FLOATING_POINT=0x10008, " "CONTEXT_DEBUG_REGISTERS=0x10010, " "CONTEXT_EXTENDED_REGISTERS=0x10020 };", 0); sdb_set (obj->kv, "mdmp_location_descriptor.format", "dd DataSize RVA", 0); sdb_set (obj->kv, "mdmp_location_descriptor64.format", "qq DataSize RVA", 0); sdb_set (obj->kv, "mdmp_memory_descriptor.format", "q? " "StartOfMemoryRange " "(mdmp_location_descriptor)Memory", 0); sdb_set (obj->kv, "mdmp_memory_descriptor64.format", "qq " "StartOfMemoryRange DataSize", 0); #if 0 /* TODO: Flag dependent thus not fully implemented */ sdb_set (obj->kv, "mdmp_context.format", "[4]B " "(mdmp_context_flags)ContextFlags", 0); #endif sdb_set (obj->kv, "mdmp_vs_fixedfileinfo.format", "ddddddddddddd " "dwSignature dwStrucVersion dwFileVersionMs " "dwFileVersionLs dwProductVersionMs " "dwProductVersionLs dwFileFlagsMask dwFileFlags " "dwFileOs dwFileType dwFileSubtype dwFileDateMs " "dwFileDateLs", 0); sdb_set (obj->kv, "mdmp_string.format", "dZ Length Buffer", 0); } static bool r_bin_mdmp_init_hdr(struct r_bin_mdmp_obj *obj) { obj->hdr = (struct minidump_header *)obj->b->buf; if (obj->hdr->number_of_streams == 0) { eprintf ("[WARN] No streams present!\n"); return false; } if (obj->hdr->stream_directory_rva < sizeof (struct minidump_header)) { eprintf ("[ERROR] RVA for directory resides in the header!\n"); return false; } if (obj->hdr->check_sum) { eprintf ("[INFO] Checksum present but needs validating!\n"); return false; } sdb_num_set (obj->kv, "mdmp.hdr.time_date_stamp", obj->hdr->time_date_stamp, 0); sdb_num_set (obj->kv, "mdmp.hdr.flags", obj->hdr->flags, 0); sdb_num_set (obj->kv, "mdmp_header.offset", 0, 0); sdb_set (obj->kv, "mdmp_header.format", "[4]zddddt[8]B Signature " "Version NumberOfStreams StreamDirectoryRVA CheckSum " "TimeDateStamp (mdmp_type)Flags", 0); return true; } static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) { int i; struct minidump_handle_operation_list *handle_operation_list; struct minidump_memory_list *memory_list; struct minidump_memory64_list *memory64_list; struct minidump_memory_info_list *memory_info_list; struct minidump_module_list *module_list; struct minidump_thread_list *thread_list; struct minidump_thread_ex_list *thread_ex_list; struct minidump_thread_info_list *thread_info_list; struct minidump_unloaded_module_list *unloaded_module_list; struct avrf_handle_operation *handle_operations; struct minidump_memory_descriptor *memories; struct minidump_memory_descriptor64 *memories64; struct minidump_memory_info *memory_infos; struct minidump_module *modules; struct minidump_thread *threads; struct minidump_thread_ex *ex_threads; struct minidump_thread_info *thread_infos; struct minidump_unloaded_module *unloaded_modules; /* We could confirm data sizes but a malcious MDMP will always get around ** this! But we can ensure that the data is not outside of the file */ if (entry->location.rva + entry->location.data_size > obj->b->length) { eprintf("[ERROR] Size Mismatch - Stream data is larger than file size!\n"); return false; } switch (entry->stream_type) { case THREAD_LIST_STREAM: thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread.format", "ddddq?? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext", 0); sdb_num_set (obj->kv, "mdmp_thread_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_list.format", sdb_fmt ("d[%i]? " "NumberOfThreads (mdmp_thread)Threads", thread_list->number_of_threads), 0); /* TODO: Not yet fully parsed or utilised */ for (i = 0; i < thread_list->number_of_threads; i++) { threads = (struct minidump_thread *)(&(thread_list->threads)); r_list_append (obj->streams.threads, &(threads[i])); } break; case MODULE_LIST_STREAM: module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_module.format", "qddtd???qq " "BaseOfImage SizeOfImage CheckSum " "TimeDateStamp ModuleNameRVA " "(mdmp_vs_fixedfileinfo)VersionInfo " "(mdmp_location_descriptor)CvRecord " "(mdmp_location_descriptor)MiscRecord " "Reserved0 Reserved1", 0); sdb_num_set (obj->kv, "mdmp_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_module_list.format", sdb_fmt ("d[%i]? " "NumberOfModule (mdmp_module)Modules", module_list->number_of_modules, 0), 0); for (i = 0; i < module_list->number_of_modules; i++) { modules = (struct minidump_module *)(&(module_list->modules)); r_list_append(obj->streams.modules, &(modules[i])); } break; case MEMORY_LIST_STREAM: memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_list.format", sdb_fmt ("d[%i]? " "NumberOfMemoryRanges " "(mdmp_memory_descriptor)MemoryRanges ", memory_list->number_of_memory_ranges, 0), 0); for (i = 0; i < memory_list->number_of_memory_ranges; i++) { memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges)); r_list_append (obj->streams.memories, &(memories[i])); } break; case EXCEPTION_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_exception.format", "[4]E[4]Eqqdd[15]q " "(mdmp_exception_code)ExceptionCode " "(mdmp_exception_flags)ExceptionFlags " "ExceptionRecord ExceptionAddress " "NumberParameters __UnusedAlignment " "ExceptionInformation", 0); sdb_num_set (obj->kv, "mdmp_exception_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_exception_stream.format", "dd?? " "ThreadId __Alignment " "(mdmp_exception)ExceptionRecord " "(mdmp_location_descriptor)ThreadContext", 0); break; case SYSTEM_INFO_STREAM: obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_system_info.offset", entry->location.rva, 0); /* TODO: We need E as a byte! */ sdb_set (obj->kv, "mdmp_system_info.format", "[2]EwwbBddd[4]Ed[2]Ew[2]q " "(mdmp_processor_architecture)ProcessorArchitecture " "ProcessorLevel ProcessorRevision NumberOfProcessors " "(mdmp_product_type)ProductType " "MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId " "CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures", 0); break; case THREAD_EX_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_ex.format", "ddddq??? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext " "(mdmp_memory_descriptor)BackingStore", 0); sdb_num_set (obj->kv, "mdmp_thread_ex_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_ex_list.format", sdb_fmt ("d[%i]? NumberOfThreads " "(mdmp_thread_ex)Threads", thread_ex_list->number_of_threads, 0), 0); for (i = 0; i < thread_ex_list->number_of_threads; i++) { ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads)); r_list_append (obj->streams.ex_threads, &(ex_threads[i])); } break; case MEMORY_64_LIST_STREAM: memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory64_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory64_list.format", sdb_fmt ("qq[%i]? NumberOfMemoryRanges " "BaseRva " "(mdmp_memory_descriptor64)MemoryRanges", memory64_list->number_of_memory_ranges), 0); obj->streams.memories64.base_rva = memory64_list->base_rva; for (i = 0; i < memory64_list->number_of_memory_ranges; i++) { memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges)); r_list_append (obj->streams.memories64.memories, &(memories64[i])); } break; case COMMENT_STREAM_A: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_a = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_a.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_a.format", "s CommentA", 0); break; case COMMENT_STREAM_W: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_w = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_w.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_w.format", "s CommentW", 0); break; case HANDLE_DATA_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_data_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_data_stream.format", "dddd " "SizeOfHeader SizeOfDescriptor " "NumberOfDescriptors Reserved", 0); break; case FUNCTION_TABLE_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_function_table_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_function_table_stream.format", "dddddd " "SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor " "SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad", 0); break; case UNLOADED_MODULE_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_unloaded_module.format", "qddtd " "BaseOfImage SizeOfImage CheckSum TimeDateStamp " "ModuleNameRva", 0); sdb_num_set (obj->kv, "mdmp_unloaded_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_unloaded_module_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < unloaded_module_list->number_of_entries; i++) { unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list)); r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i])); } break; case MISC_INFO_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva); /* TODO: Handle different sizes */ sdb_num_set (obj->kv, "mdmp_misc_info.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_misc_info.format", "d[4]Bdtttddddd " "SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId " "ProcessCreateTime ProcessUserTime ProcessKernelTime " "ProcessorMaxMhz ProcessorCurrentMhz " "ProcessorMhzLimit ProcessorMaxIdleState " "ProcessorCurrentIdleState", 0); break; case MEMORY_INFO_LIST_STREAM: memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_memory_info.format", "qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase " "(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize " "(mdmp_mem_state)State (mdmp_page_protect)Protect " "(mdmp_mem_type)Type __Alignment2", 0); sdb_num_set (obj->kv, "mdmp_memory_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_info_list.format", sdb_fmt ("ddq[%i]? SizeOfHeader SizeOfEntry " "NumberOfEntries (mdmp_memory_info)MemoryInfo", memory_info_list->number_of_entries), 0); for (i = 0; i < memory_info_list->number_of_entries; i++) { memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list)); r_list_append (obj->streams.memory_infos, &(memory_infos[i])); } break; case THREAD_INFO_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_info.format", "ddddttttqq " "ThreadId DumpFlags DumpError ExitStatus CreateTime " "ExitTime KernelTime UserTime StartAddress Affinity", 0); sdb_num_set (obj->kv, "mdmp_thread_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_info_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < thread_info_list->number_of_entries; i++) { thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list)); r_list_append (obj->streams.thread_infos, &(thread_infos[i])); } break; case HANDLE_OPERATION_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_operation_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_operation_list.format", "dddd " "SizeOfHeader SizeOfEntry NumberOfEntries Reserved", 0); for (i = 0; i < handle_operation_list->number_of_entries; i++) { handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list)); r_list_append (obj->streams.operations, &(handle_operations[i])); } break; case LAST_RESERVED_STREAM: /* TODO: Not yet fully parsed or utilised */ break; case UNUSED_STREAM: case RESERVED_STREAM_0: case RESERVED_STREAM_1: /* Silently ignore reserved streams */ break; default: eprintf ("[WARN] Invalid or unsupported enumeration encountered %i\n", entry->stream_type); return false; } return true; } static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { int i; ut8 *directory_base; struct minidump_directory *entry; directory_base = obj->b->buf + obj->hdr->stream_directory_rva; sdb_num_set (obj->kv, "mdmp_directory.offset", obj->hdr->stream_directory_rva, 0); sdb_set (obj->kv, "mdmp_directory.format", "[4]E? " "(mdmp_stream_type)StreamType " "(mdmp_location_descriptor)Location", 0); /* Parse each entry in the directory */ for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory))); r_bin_mdmp_init_directory_entry (obj, entry); } return true; } static bool r_bin_mdmp_patch_pe_headers(RBuffer *pe_buf) { int i; Pe64_image_dos_header dos_hdr; Pe64_image_nt_headers nt_hdr; Pe64_image_section_header *section_hdrs; r_buf_read_at (pe_buf, 0, (ut8 *)&dos_hdr, sizeof (Pe64_image_dos_header)); r_buf_read_at (pe_buf, dos_hdr.e_lfanew, (ut8 *)&nt_hdr, sizeof (Pe64_image_nt_headers)); /* Patch RawData in headers */ section_hdrs = (Pe64_image_section_header *)(pe_buf->buf + dos_hdr.e_lfanew + 4 + sizeof (Pe64_image_file_header) + nt_hdr.file_header.SizeOfOptionalHeader); for (i = 0; i < nt_hdr.file_header.NumberOfSections; i++) { section_hdrs[i].PointerToRawData = section_hdrs[i].VirtualAddress; } return true; } static int check_pe32_bytes(const ut8 *buf, ut64 length) { unsigned int idx; if (!buf || length <= 0x3d) { return false; } idx = (buf[0x3c] | (buf[0x3d]<<8)); if (length > idx + 0x18 + 2) { if (!memcmp (buf, "MZ", 2) && !memcmp (buf+idx, "PE", 2) && !memcmp (buf+idx+0x18, "\x0b\x01", 2)) { return true; } } return false; } static int check_pe64_bytes(const ut8 *buf, ut64 length) { int idx, ret = false; if (!buf || length <= 0x3d) { return false; } idx = buf[0x3c] | (buf[0x3d]<<8); if (length >= idx + 0x20) { if (!memcmp (buf, "MZ", 2) && !memcmp (buf+idx, "PE", 2) && !memcmp (buf+idx+0x18, "\x0b\x02", 2)) { ret = true; } } return ret; } static bool r_bin_mdmp_init_pe_bins(struct r_bin_mdmp_obj *obj) { bool dup; ut64 paddr; struct minidump_module *module; struct Pe32_r_bin_mdmp_pe_bin *pe32_bin, *pe32_dup; struct Pe64_r_bin_mdmp_pe_bin *pe64_bin, *pe64_dup; RBuffer *buf; RListIter *it, *it_dup; r_list_foreach (obj->streams.modules, it, module) { /* Duplicate modules can appear in the MDMP module list, ** filtering them out seems to be the correct behaviour */ if (!(paddr = r_bin_mdmp_get_paddr (obj, module->base_of_image))) { continue; } int left = 0; const ut8 *b = r_buf_get_at (obj->b, paddr, &left); buf = r_buf_new_with_bytes (b, R_MIN (left, module->size_of_image)); dup = false; if (check_pe32_bytes (buf->buf, module->size_of_image)) { r_list_foreach(obj->pe32_bins, it_dup, pe32_dup) { if (pe32_dup->vaddr == module->base_of_image) { dup = true; continue; } } if (dup) { continue; } if (!(pe32_bin = R_NEW0 (struct Pe32_r_bin_mdmp_pe_bin))) { continue; } r_bin_mdmp_patch_pe_headers (buf); pe32_bin->vaddr = module->base_of_image; pe32_bin->paddr = paddr; pe32_bin->bin = Pe32_r_bin_pe_new_buf (buf, 0); r_list_append (obj->pe32_bins, pe32_bin); } else if (check_pe64_bytes (buf->buf, module->size_of_image)) { r_list_foreach(obj->pe64_bins, it_dup, pe64_dup) { if (pe64_dup->vaddr == module->base_of_image) { dup = true; continue; } } if (dup) { continue; } if (!(pe64_bin = R_NEW0 (struct Pe64_r_bin_mdmp_pe_bin))) { continue; } r_bin_mdmp_patch_pe_headers (buf); pe64_bin->vaddr = module->base_of_image; pe64_bin->paddr = paddr; pe64_bin->bin = Pe64_r_bin_pe_new_buf (buf, 0); r_list_append (obj->pe64_bins, pe64_bin); } r_buf_free (buf); } return true; } static int r_bin_mdmp_init(struct r_bin_mdmp_obj *obj) { r_bin_mdmp_init_parsing (obj); if (!r_bin_mdmp_init_hdr (obj)) { eprintf ("[ERROR] Failed to initialise header\n"); return false; } if (!r_bin_mdmp_init_directory (obj)) { eprintf ("[ERROR] Failed to initialise directory structures!\n"); return false; } if (!r_bin_mdmp_init_pe_bins (obj)) { eprintf ("[ERROR] Failed to initialise pe binaries!\n"); return false; } return true; } struct r_bin_mdmp_obj *r_bin_mdmp_new_buf(struct r_buf_t *buf) { bool fail = false; struct r_bin_mdmp_obj *obj = R_NEW0 (struct r_bin_mdmp_obj); if (!obj) { return NULL; } obj->kv = sdb_new0 (); obj->b = r_buf_new (); obj->size = (ut32)buf->length; fail |= (!(obj->streams.ex_threads = r_list_new ())); fail |= (!(obj->streams.memories = r_list_new ())); fail |= (!(obj->streams.memories64.memories = r_list_new ())); fail |= (!(obj->streams.memory_infos = r_list_new ())); fail |= (!(obj->streams.modules = r_list_new ())); fail |= (!(obj->streams.operations = r_list_new ())); fail |= (!(obj->streams.thread_infos = r_list_new ())); fail |= (!(obj->streams.threads = r_list_new ())); fail |= (!(obj->streams.unloaded_modules = r_list_new ())); fail |= (!(obj->pe32_bins = r_list_newf (r_bin_mdmp_free_pe32_bin))); fail |= (!(obj->pe64_bins = r_list_newf (r_bin_mdmp_free_pe64_bin))); if (fail) { r_bin_mdmp_free (obj); return NULL; } if (!r_buf_set_bytes (obj->b, buf->buf, buf->length)) { r_bin_mdmp_free (obj); return NULL; } if (!r_bin_mdmp_init (obj)) { r_bin_mdmp_free (obj); return NULL; } return obj; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_235_0
crossvul-cpp_data_bad_5238_0
#ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /*! \brief Creates a gdImage from a TGA file * Creates a gdImage from a TGA binary file via a gdIOCtx. * \param infile Pointer to TGA binary file * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /*! \brief Creates a gdImage from a gdIOCtx * Creates a gdImage from a gdIOCtx referencing a TGA binary file. * \param ctx Pointer to a gdIOCtx structure * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; uint8_t* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int j = 0; uint8_t encoded_pixels; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < image_block_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 ); buffer_caret++; for (i = 0; i < encoded_pixels; i++) { for (j = 0; j < pixel_block_size; j++, bitmap_caret++) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; for (i = 0; i < encoded_pixels; i++) { for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } buffer_caret += pixel_block_size; } } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5238_0
crossvul-cpp_data_bad_210_1
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / ISO Media File Format sub-project * * GPAC 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, or (at your option) * any later version. * * GPAC 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; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/internal/isomedia_dev.h> #ifndef GPAC_DISABLE_ISOM void co64_del(GF_Box *s) { GF_ChunkLargeOffsetBox *ptr; ptr = (GF_ChunkLargeOffsetBox *) s; if (ptr == NULL) return; if (ptr->offsets) gf_free(ptr->offsets); gf_free(ptr); } GF_Err co64_Read(GF_Box *s,GF_BitStream *bs) { u32 entries; GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s; ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4) if (ptr->nb_entries > ptr->size / 8) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in co64\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } ptr->offsets = (u64 *) gf_malloc(ptr->nb_entries * sizeof(u64) ); if (ptr->offsets == NULL) return GF_OUT_OF_MEM; ptr->alloc_size = ptr->nb_entries; for (entries = 0; entries < ptr->nb_entries; entries++) { ptr->offsets[entries] = gf_bs_read_u64(bs); } return GF_OK; } GF_Box *co64_New() { ISOM_DECL_BOX_ALLOC(GF_ChunkLargeOffsetBox, GF_ISOM_BOX_TYPE_CO64); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err co64_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i = 0; i < ptr->nb_entries; i++ ) { gf_bs_write_u64(bs, ptr->offsets[i]); } return GF_OK; } GF_Err co64_Size(GF_Box *s) { GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s; ptr->size += 4 + (8 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void cprt_del(GF_Box *s) { GF_CopyrightBox *ptr = (GF_CopyrightBox *) s; if (ptr == NULL) return; if (ptr->notice) gf_free(ptr->notice); gf_free(ptr); } GF_Box *chpl_New() { ISOM_DECL_BOX_ALLOC(GF_ChapterListBox, GF_ISOM_BOX_TYPE_CHPL); tmp->list = gf_list_new(); tmp->version = 1; return (GF_Box *)tmp; } void chpl_del(GF_Box *s) { GF_ChapterListBox *ptr = (GF_ChapterListBox *) s; if (ptr == NULL) return; while (gf_list_count(ptr->list)) { GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, 0); if (ce->name) gf_free(ce->name); gf_free(ce); gf_list_rem(ptr->list, 0); } gf_list_del(ptr->list); gf_free(ptr); } /*this is using chpl format according to some NeroRecode samples*/ GF_Err chpl_Read(GF_Box *s,GF_BitStream *bs) { GF_ChapterEntry *ce; u32 nb_chaps, len, i, count; GF_ChapterListBox *ptr = (GF_ChapterListBox *)s; /*reserved or ???*/ gf_bs_read_u32(bs); nb_chaps = gf_bs_read_u8(bs); count = 0; while (nb_chaps) { GF_SAFEALLOC(ce, GF_ChapterEntry); if (!ce) return GF_OUT_OF_MEM; ce->start_time = gf_bs_read_u64(bs); len = gf_bs_read_u8(bs); if (len) { ce->name = (char *)gf_malloc(sizeof(char)*(len+1)); gf_bs_read_data(bs, ce->name, len); ce->name[len] = 0; } else { ce->name = gf_strdup(""); } for (i=0; i<count; i++) { GF_ChapterEntry *ace = (GF_ChapterEntry *) gf_list_get(ptr->list, i); if (ace->start_time >= ce->start_time) { gf_list_insert(ptr->list, ce, i); ce = NULL; break; } } if (ce) gf_list_add(ptr->list, ce); count++; nb_chaps--; } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err chpl_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 count, i; GF_ChapterListBox *ptr = (GF_ChapterListBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; count = gf_list_count(ptr->list); gf_bs_write_u32(bs, 0); gf_bs_write_u8(bs, count); for (i=0; i<count; i++) { u32 len; GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, i); gf_bs_write_u64(bs, ce->start_time); if (ce->name) { len = (u32) strlen(ce->name); if (len>255) len = 255; gf_bs_write_u8(bs, len); gf_bs_write_data(bs, ce->name, len); } else { gf_bs_write_u8(bs, 0); } } return GF_OK; } GF_Err chpl_Size(GF_Box *s) { u32 count, i; GF_ChapterListBox *ptr = (GF_ChapterListBox *)s; ptr->size += 5; count = gf_list_count(ptr->list); for (i=0; i<count; i++) { GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, i); ptr->size += 9; /*64bit time stamp + 8bit str len*/ if (ce->name) ptr->size += strlen(ce->name); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Err cprt_Read(GF_Box *s,GF_BitStream *bs) { GF_CopyrightBox *ptr = (GF_CopyrightBox *)s; gf_bs_read_int(bs, 1); //the spec is unclear here, just says "the value 0 is interpreted as undetermined" ptr->packedLanguageCode[0] = gf_bs_read_int(bs, 5); ptr->packedLanguageCode[1] = gf_bs_read_int(bs, 5); ptr->packedLanguageCode[2] = gf_bs_read_int(bs, 5); ISOM_DECREASE_SIZE(ptr, 2); //but before or after compaction ?? We assume before if (ptr->packedLanguageCode[0] || ptr->packedLanguageCode[1] || ptr->packedLanguageCode[2]) { ptr->packedLanguageCode[0] += 0x60; ptr->packedLanguageCode[1] += 0x60; ptr->packedLanguageCode[2] += 0x60; } else { ptr->packedLanguageCode[0] = 'u'; ptr->packedLanguageCode[1] = 'n'; ptr->packedLanguageCode[2] = 'd'; } if (ptr->size) { u32 bytesToRead = (u32) ptr->size; ptr->notice = (char*)gf_malloc(bytesToRead * sizeof(char)); if (ptr->notice == NULL) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->notice, bytesToRead); } return GF_OK; } GF_Box *cprt_New() { ISOM_DECL_BOX_ALLOC(GF_CopyrightBox, GF_ISOM_BOX_TYPE_CPRT); tmp->packedLanguageCode[0] = 'u'; tmp->packedLanguageCode[1] = 'n'; tmp->packedLanguageCode[2] = 'd'; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err cprt_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_CopyrightBox *ptr = (GF_CopyrightBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, 0, 1); if (ptr->packedLanguageCode[0]) { gf_bs_write_int(bs, ptr->packedLanguageCode[0] - 0x60, 5); gf_bs_write_int(bs, ptr->packedLanguageCode[1] - 0x60, 5); gf_bs_write_int(bs, ptr->packedLanguageCode[2] - 0x60, 5); } else { gf_bs_write_int(bs, 0, 15); } if (ptr->notice) { gf_bs_write_data(bs, ptr->notice, (u32) (strlen(ptr->notice) + 1) ); } return GF_OK; } GF_Err cprt_Size(GF_Box *s) { GF_CopyrightBox *ptr = (GF_CopyrightBox *)s; ptr->size += 2; if (ptr->notice) ptr->size += strlen(ptr->notice) + 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void kind_del(GF_Box *s) { GF_KindBox *ptr = (GF_KindBox *) s; if (ptr == NULL) return; if (ptr->schemeURI) gf_free(ptr->schemeURI); if (ptr->value) gf_free(ptr->value); gf_free(ptr); } GF_Err kind_Read(GF_Box *s,GF_BitStream *bs) { GF_KindBox *ptr = (GF_KindBox *)s; if (ptr->size) { u32 bytesToRead = (u32) ptr->size; char *data; u32 schemeURIlen; data = (char*)gf_malloc(bytesToRead * sizeof(char)); if (data == NULL) return GF_OUT_OF_MEM; gf_bs_read_data(bs, data, bytesToRead); /*safety check in case the string is not null-terminated*/ if (data[bytesToRead-1]) { char *str = (char*)gf_malloc((u32) bytesToRead + 1); memcpy(str, data, (u32) bytesToRead); str[ptr->size] = 0; gf_free(data); data = str; bytesToRead++; } ptr->schemeURI = gf_strdup(data); schemeURIlen = (u32) strlen(data); if (bytesToRead > schemeURIlen+1) { /* read the value */ char *data_value = data + schemeURIlen +1; ptr->value = gf_strdup(data_value); } gf_free(data); } return GF_OK; } GF_Box *kind_New() { ISOM_DECL_BOX_ALLOC(GF_KindBox, GF_ISOM_BOX_TYPE_KIND); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err kind_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_KindBox *ptr = (GF_KindBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->schemeURI, (u32) (strlen(ptr->schemeURI) + 1 )); if (ptr->value) { gf_bs_write_data(bs, ptr->value, (u32) (strlen(ptr->value) + 1) ); } return GF_OK; } GF_Err kind_Size(GF_Box *s) { GF_KindBox *ptr = (GF_KindBox *)s; ptr->size += strlen(ptr->schemeURI) + 1; if (ptr->value) { ptr->size += strlen(ptr->value) + 1; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void ctts_del(GF_Box *s) { GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err ctts_Read(GF_Box *s, GF_BitStream *bs) { u32 i; u32 sampleCount; GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s; ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->nb_entries > ptr->size / 8) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } ptr->alloc_size = ptr->nb_entries; ptr->entries = (GF_DttsEntry *)gf_malloc(sizeof(GF_DttsEntry)*ptr->alloc_size); if (!ptr->entries) return GF_OUT_OF_MEM; sampleCount = 0; for (i=0; i<ptr->nb_entries; i++) { ptr->entries[i].sampleCount = gf_bs_read_u32(bs); if (ptr->version) ptr->entries[i].decodingOffset = gf_bs_read_int(bs, 32); else ptr->entries[i].decodingOffset = (s32) gf_bs_read_u32(bs); sampleCount += ptr->entries[i].sampleCount; } #ifndef GPAC_DISABLE_ISOM_WRITE ptr->w_LastSampleNumber = sampleCount; #endif return GF_OK; } GF_Box *ctts_New() { ISOM_DECL_BOX_ALLOC(GF_CompositionOffsetBox, GF_ISOM_BOX_TYPE_CTTS); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err ctts_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++ ) { gf_bs_write_u32(bs, ptr->entries[i].sampleCount); if (ptr->version) { gf_bs_write_int(bs, ptr->entries[i].decodingOffset, 32); } else { gf_bs_write_u32(bs, (u32) ptr->entries[i].decodingOffset); } } return GF_OK; } GF_Err ctts_Size(GF_Box *s) { GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *) s; ptr->size += 4 + (8 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void cslg_del(GF_Box *s) { GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s; if (ptr == NULL) return; gf_free(ptr); return; } GF_Err cslg_Read(GF_Box *s, GF_BitStream *bs) { GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s; ptr->compositionToDTSShift = gf_bs_read_int(bs, 32); ptr->leastDecodeToDisplayDelta = gf_bs_read_int(bs, 32); ptr->greatestDecodeToDisplayDelta = gf_bs_read_int(bs, 32); ptr->compositionStartTime = gf_bs_read_int(bs, 32); ptr->compositionEndTime = gf_bs_read_int(bs, 32); return GF_OK; } GF_Box *cslg_New() { ISOM_DECL_BOX_ALLOC(GF_CompositionToDecodeBox, GF_ISOM_BOX_TYPE_CSLG); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err cslg_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->compositionToDTSShift, 32); gf_bs_write_int(bs, ptr->leastDecodeToDisplayDelta, 32); gf_bs_write_int(bs, ptr->greatestDecodeToDisplayDelta, 32); gf_bs_write_int(bs, ptr->compositionStartTime, 32); gf_bs_write_int(bs, ptr->compositionEndTime, 32); return GF_OK; } GF_Err cslg_Size(GF_Box *s) { GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s; ptr->size += 20; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void ccst_del(GF_Box *s) { GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s; if (ptr) gf_free(ptr); return; } GF_Err ccst_Read(GF_Box *s, GF_BitStream *bs) { GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s; ISOM_DECREASE_SIZE(ptr, 4); ptr->all_ref_pics_intra = gf_bs_read_int(bs, 1); ptr->intra_pred_used = gf_bs_read_int(bs, 1); ptr->max_ref_per_pic = gf_bs_read_int(bs, 4); ptr->reserved = gf_bs_read_int(bs, 26); return GF_OK; } GF_Box *ccst_New() { ISOM_DECL_BOX_ALLOC(GF_CodingConstraintsBox, GF_ISOM_BOX_TYPE_CCST); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err ccst_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->all_ref_pics_intra, 1); gf_bs_write_int(bs, ptr->intra_pred_used, 1); gf_bs_write_int(bs, ptr->max_ref_per_pic, 4); gf_bs_write_int(bs, 0, 26); return GF_OK; } GF_Err ccst_Size(GF_Box *s) { GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s; ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void url_del(GF_Box *s) { GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s; if (ptr == NULL) return; if (ptr->location) gf_free(ptr->location); gf_free(ptr); return; } GF_Err url_Read(GF_Box *s, GF_BitStream *bs) { GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s; if (ptr->size) { ptr->location = (char*)gf_malloc((u32) ptr->size); if (! ptr->location) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->location, (u32)ptr->size); } return GF_OK; } GF_Box *url_New() { ISOM_DECL_BOX_ALLOC(GF_DataEntryURLBox, GF_ISOM_BOX_TYPE_URL); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err url_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; //the flag set indicates we have a string (WE HAVE TO for URLs) if ( !(ptr->flags & 1)) { if (ptr->location) { gf_bs_write_data(bs, ptr->location, (u32)strlen(ptr->location) + 1); } } return GF_OK; } GF_Err url_Size(GF_Box *s) { GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s; if ( !(ptr->flags & 1)) { if (ptr->location) ptr->size += 1 + strlen(ptr->location); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void urn_del(GF_Box *s) { GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (ptr == NULL) return; if (ptr->location) gf_free(ptr->location); if (ptr->nameURN) gf_free(ptr->nameURN); gf_free(ptr); } GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; //here we have to handle that in a clever way to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; //get the data gf_bs_read_data(bs, tmpName, to_read); //then get the break i = 0; while ( (tmpName[i] != 0) && (i < to_read) ) { i++; } //check the data is consistent if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } //no NULL char, URL is not specified if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } //OK, this has both URN and URL ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; } GF_Box *urn_New() { ISOM_DECL_BOX_ALLOC(GF_DataEntryURNBox, GF_ISOM_BOX_TYPE_URN); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err urn_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; //the flag set indicates we have a string (WE HAVE TO for URLs) if ( !(ptr->flags & 1)) { //to check, the spec says: First name, then location if (ptr->nameURN) { gf_bs_write_data(bs, ptr->nameURN, (u32)strlen(ptr->nameURN) + 1); } if (ptr->location) { gf_bs_write_data(bs, ptr->location, (u32)strlen(ptr->location) + 1); } } return GF_OK; } GF_Err urn_Size(GF_Box *s) { GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if ( !(ptr->flags & 1)) { if (ptr->nameURN) ptr->size += 1 + strlen(ptr->nameURN); if (ptr->location) ptr->size += 1 + strlen(ptr->location); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void unkn_del(GF_Box *s) { GF_UnknownBox *ptr = (GF_UnknownBox *) s; if (!s) return; if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Err unkn_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 bytesToRead, sub_size, sub_a; GF_BitStream *sub_bs; GF_UnknownBox *ptr = (GF_UnknownBox *)s; if (ptr->size > 0xFFFFFFFF) return GF_ISOM_INVALID_FILE; bytesToRead = (u32) (ptr->size); if (!bytesToRead) return GF_OK; if (bytesToRead>1000000) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Unknown box %s (0x%08X) with payload larger than 1 MBytes, ignoring\n", gf_4cc_to_str(ptr->type), ptr->type )); gf_bs_skip_bytes(bs, ptr->dataSize); return GF_OK; } ptr->data = (char*)gf_malloc(bytesToRead); if (ptr->data == NULL ) return GF_OUT_OF_MEM; ptr->dataSize = bytesToRead; gf_bs_read_data(bs, ptr->data, ptr->dataSize); //try to parse container boxes, check if next 8 bytes match a subbox sub_bs = gf_bs_new(ptr->data, ptr->dataSize, GF_BITSTREAM_READ); sub_size = gf_bs_read_u32(sub_bs); sub_a = gf_bs_read_u8(sub_bs); e = (sub_size && (sub_size <= ptr->dataSize)) ? GF_OK : GF_NOT_SUPPORTED; if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED; sub_a = gf_bs_read_u8(sub_bs); if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED; sub_a = gf_bs_read_u8(sub_bs); if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED; sub_a = gf_bs_read_u8(sub_bs); if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED; if (e == GF_OK) { gf_bs_seek(sub_bs, 0); e = gf_isom_box_array_read(s, sub_bs, gf_isom_box_add_default); } gf_bs_del(sub_bs); if (e==GF_OK) { gf_free(ptr->data); ptr->data = NULL; ptr->dataSize = 0; } else if (s->other_boxes) { gf_isom_box_array_del(s->other_boxes); s->other_boxes=NULL; } return GF_OK; } GF_Box *unkn_New(u32 box_type) { ISOM_DECL_BOX_ALLOC(GF_UnknownBox, GF_ISOM_BOX_TYPE_UNKNOWN); tmp->original_4cc = box_type; return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err unkn_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 type = s->type; GF_UnknownBox *ptr = (GF_UnknownBox *)s; if (!s) return GF_BAD_PARAM; s->type = ptr->original_4cc; e = gf_isom_box_write_header(s, bs); s->type = type; if (e) return e; if (ptr->dataSize && ptr->data) { gf_bs_write_data(bs, ptr->data, ptr->dataSize); } return GF_OK; } GF_Err unkn_Size(GF_Box *s) { GF_UnknownBox *ptr = (GF_UnknownBox *)s; if (ptr->dataSize && ptr->data) { ptr->size += ptr->dataSize; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void def_cont_box_del(GF_Box *s) { if (s) gf_free(s); } GF_Err def_cont_box_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, gf_isom_box_add_default); } GF_Box *def_cont_box_New() { ISOM_DECL_BOX_ALLOC(GF_Box, 0); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITEHintSa GF_Err def_cont_box_Write(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_write_header(s, bs); } GF_Err def_cont_box_Size(GF_Box *s) { return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void uuid_del(GF_Box *s) { GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox *) s; if (!s) return; if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Err uuid_Read(GF_Box *s, GF_BitStream *bs) { u32 bytesToRead; GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox *)s; if (ptr->size > 0xFFFFFFFF) return GF_ISOM_INVALID_FILE; bytesToRead = (u32) (ptr->size); if (bytesToRead) { ptr->data = (char*)gf_malloc(bytesToRead); if (ptr->data == NULL ) return GF_OUT_OF_MEM; ptr->dataSize = bytesToRead; gf_bs_read_data(bs, ptr->data, ptr->dataSize); } return GF_OK; } GF_Box *uuid_New() { ISOM_DECL_BOX_ALLOC(GF_UnknownUUIDBox, GF_ISOM_BOX_TYPE_UUID); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err uuid_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox*)s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->data) { gf_bs_write_data(bs, ptr->data, ptr->dataSize); } return GF_OK; } GF_Err uuid_Size(GF_Box *s) { GF_UnknownUUIDBox*ptr = (GF_UnknownUUIDBox*)s; ptr->size += ptr->dataSize; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void dinf_del(GF_Box *s) { GF_DataInformationBox *ptr = (GF_DataInformationBox *)s; if (ptr == NULL) return; gf_isom_box_del((GF_Box *)ptr->dref); gf_free(ptr); } GF_Err dinf_AddBox(GF_Box *s, GF_Box *a) { GF_DataInformationBox *ptr = (GF_DataInformationBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_DREF: if (ptr->dref) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->dref = (GF_DataReferenceBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); } return GF_OK; } GF_Box *dinf_New() { ISOM_DECL_BOX_ALLOC(GF_DataInformationBox, GF_ISOM_BOX_TYPE_DINF); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dinf_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DataInformationBox *ptr = (GF_DataInformationBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->dref) { e = gf_isom_box_write((GF_Box *)ptr->dref, bs); if (e) return e; } return GF_OK; } GF_Err dinf_Size(GF_Box *s) { GF_Err e; GF_DataInformationBox *ptr = (GF_DataInformationBox *)s; if (ptr->dref) { e = gf_isom_box_size((GF_Box *) ptr->dref); if (e) return e; ptr->size += ptr->dref->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void dref_del(GF_Box *s) { GF_DataReferenceBox *ptr = (GF_DataReferenceBox *) s; if (ptr == NULL) return; gf_free(ptr); } GF_Err dref_AddDataEntry(GF_Box *ptr, GF_Box *entry) { if (entry->type==GF_ISOM_BOX_TYPE_ALIS) { GF_DataEntryURLBox *urle = (GF_DataEntryURLBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_URL); urle->flags = 1; gf_isom_box_del(entry); gf_isom_box_add_default(ptr, (GF_Box *)urle); GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[iso file] Apple \'alis\' box found, not supported - converting to self-pointing \'url \' \n" )); } else { return gf_isom_box_add_default(ptr, entry); } return GF_OK; } GF_Err dref_Read(GF_Box *s, GF_BitStream *bs) { GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s; if (ptr == NULL) return GF_BAD_PARAM; gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); return gf_isom_box_array_read(s, bs, dref_AddDataEntry); } GF_Box *dref_New() { ISOM_DECL_BOX_ALLOC(GF_DataReferenceBox, GF_ISOM_BOX_TYPE_DREF); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dref_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 count; GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; count = ptr->other_boxes ? gf_list_count(ptr->other_boxes) : 0; gf_bs_write_u32(bs, count); return GF_OK; } GF_Err dref_Size(GF_Box *s) { GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s; if (!s) return GF_BAD_PARAM; ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void edts_del(GF_Box *s) { GF_EditBox *ptr = (GF_EditBox *) s; gf_isom_box_del((GF_Box *)ptr->editList); gf_free(ptr); } GF_Err edts_AddBox(GF_Box *s, GF_Box *a) { GF_EditBox *ptr = (GF_EditBox *)s; if (a->type == GF_ISOM_BOX_TYPE_ELST) { if (ptr->editList) return GF_BAD_PARAM; ptr->editList = (GF_EditListBox *)a; return GF_OK; } else { return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err edts_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, edts_AddBox); } GF_Box *edts_New() { ISOM_DECL_BOX_ALLOC(GF_EditBox, GF_ISOM_BOX_TYPE_EDTS); return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err edts_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_EditBox *ptr = (GF_EditBox *)s; //here we have a trick: if editList is empty, skip the box if (ptr->editList && gf_list_count(ptr->editList->entryList)) { e = gf_isom_box_write_header(s, bs); if (e) return e; e = gf_isom_box_write((GF_Box *) ptr->editList, bs); if (e) return e; } return GF_OK; } GF_Err edts_Size(GF_Box *s) { GF_Err e; GF_EditBox *ptr = (GF_EditBox *)s; //here we have a trick: if editList is empty, skip the box if (!ptr->editList || ! gf_list_count(ptr->editList->entryList)) { ptr->size = 0; } else { e = gf_isom_box_size((GF_Box *)ptr->editList); if (e) return e; ptr->size += ptr->editList->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void elst_del(GF_Box *s) { GF_EditListBox *ptr; GF_EdtsEntry *p; u32 nb_entries; u32 i; ptr = (GF_EditListBox *)s; if (ptr == NULL) return; nb_entries = gf_list_count(ptr->entryList); for (i = 0; i < nb_entries; i++) { p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i); if (p) gf_free(p); } gf_list_del(ptr->entryList); gf_free(ptr); } GF_Err elst_Read(GF_Box *s, GF_BitStream *bs) { u32 entries; s32 tr; u32 nb_entries; GF_EdtsEntry *p; GF_EditListBox *ptr = (GF_EditListBox *)s; nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->version == 1) { if (nb_entries > ptr->size / 20) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", nb_entries)); return GF_ISOM_INVALID_FILE; } } else { if (nb_entries > ptr->size / 12) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", nb_entries)); return GF_ISOM_INVALID_FILE; } } for (entries = 0; entries < nb_entries; entries++) { p = (GF_EdtsEntry *) gf_malloc(sizeof(GF_EdtsEntry)); if (!p) return GF_OUT_OF_MEM; if (ptr->version == 1) { p->segmentDuration = gf_bs_read_u64(bs); p->mediaTime = (s64) gf_bs_read_u64(bs); } else { p->segmentDuration = gf_bs_read_u32(bs); tr = gf_bs_read_u32(bs); p->mediaTime = (s64) tr; } p->mediaRate = gf_bs_read_u16(bs); gf_bs_read_u16(bs); gf_list_add(ptr->entryList, p); } return GF_OK; } GF_Box *elst_New() { ISOM_DECL_BOX_ALLOC(GF_EditListBox, GF_ISOM_BOX_TYPE_ELST); tmp->entryList = gf_list_new(); if (!tmp->entryList) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err elst_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; u32 nb_entries; GF_EdtsEntry *p; GF_EditListBox *ptr = (GF_EditListBox *)s; if (!ptr) return GF_BAD_PARAM; nb_entries = gf_list_count(ptr->entryList); e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, nb_entries); for (i = 0; i < nb_entries; i++ ) { p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i); if (ptr->version == 1) { gf_bs_write_u64(bs, p->segmentDuration); gf_bs_write_u64(bs, p->mediaTime); } else { gf_bs_write_u32(bs, (u32) p->segmentDuration); gf_bs_write_u32(bs, (s32) p->mediaTime); } gf_bs_write_u16(bs, p->mediaRate); gf_bs_write_u16(bs, 0); } return GF_OK; } GF_Err elst_Size(GF_Box *s) { u32 durtimebytes; u32 i, nb_entries; GF_EditListBox *ptr = (GF_EditListBox *)s; //entry count ptr->size += 4; nb_entries = gf_list_count(ptr->entryList); ptr->version = 0; for (i=0; i<nb_entries; i++) { GF_EdtsEntry *p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i); if ((p->segmentDuration>0xFFFFFFFF) || (p->mediaTime>0xFFFFFFFF)) { ptr->version = 1; break; } } durtimebytes = (ptr->version == 1 ? 16 : 8) + 4; ptr->size += (nb_entries * durtimebytes); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void esds_del(GF_Box *s) { GF_ESDBox *ptr = (GF_ESDBox *)s; if (ptr == NULL) return; if (ptr->desc) gf_odf_desc_del((GF_Descriptor *)ptr->desc); gf_free(ptr); } GF_Err esds_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e=GF_OK; u32 descSize; char *enc_desc; u32 SLIsPredefined(GF_SLConfig *sl); GF_ESDBox *ptr = (GF_ESDBox *)s; descSize = (u32) (ptr->size); if (descSize) { enc_desc = (char*)gf_malloc(sizeof(char) * descSize); if (!enc_desc) return GF_OUT_OF_MEM; //get the payload gf_bs_read_data(bs, enc_desc, descSize); //send it to the OD Codec e = gf_odf_desc_read(enc_desc, descSize, (GF_Descriptor **) &ptr->desc); //OK, free our desc gf_free(enc_desc); if (ptr->desc && (ptr->desc->tag!=GF_ODF_ESD_TAG) ) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid descriptor tag 0x%x in esds\n", ptr->desc->tag)); gf_odf_desc_del((GF_Descriptor*)ptr->desc); ptr->desc=NULL; return GF_ISOM_INVALID_FILE; } if (e) { ptr->desc = NULL; } else { /*fix broken files*/ if (!ptr->desc->URLString) { if (!ptr->desc->slConfig) { ptr->desc->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); ptr->desc->slConfig->predefined = SLPredef_MP4; } else if (ptr->desc->slConfig->predefined != SLPredef_MP4) { ptr->desc->slConfig->predefined = SLPredef_MP4; gf_odf_slc_set_pref(ptr->desc->slConfig); } } } } return e; } GF_Box *esds_New() { ISOM_DECL_BOX_ALLOC(GF_ESDBox, GF_ISOM_BOX_TYPE_ESDS); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err esds_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; char *enc_desc; u32 descSize = 0; GF_ESDBox *ptr = (GF_ESDBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; e = gf_odf_desc_write((GF_Descriptor *)ptr->desc, &enc_desc, &descSize); if (e) return e; gf_bs_write_data(bs, enc_desc, descSize); //free our buffer gf_free(enc_desc); return GF_OK; } GF_Err esds_Size(GF_Box *s) { u32 descSize = 0; GF_ESDBox *ptr = (GF_ESDBox *)s; descSize = gf_odf_desc_size((GF_Descriptor *)ptr->desc); ptr->size += descSize; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void free_del(GF_Box *s) { GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s; if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Err free_Read(GF_Box *s, GF_BitStream *bs) { u32 bytesToRead; GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s; if (ptr->size > 0xFFFFFFFF) return GF_IO_ERR; bytesToRead = (u32) (ptr->size); if (bytesToRead) { ptr->data = (char*)gf_malloc(bytesToRead * sizeof(char)); gf_bs_read_data(bs, ptr->data, bytesToRead); ptr->dataSize = bytesToRead; } return GF_OK; } GF_Box *free_New() { ISOM_DECL_BOX_ALLOC(GF_FreeSpaceBox, GF_ISOM_BOX_TYPE_FREE); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err free_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s; if (ptr->original_4cc) { u32 t = s->type; s->type=ptr->original_4cc; e = gf_isom_box_write_header(s, bs); s->type=t; } else { e = gf_isom_box_write_header(s, bs); } if (e) return e; if (ptr->dataSize) { if (ptr->data) { gf_bs_write_data(bs, ptr->data, ptr->dataSize); } else { u32 i = 0; while (i<ptr->dataSize) { gf_bs_write_u8(bs, 0); i++; } } } return GF_OK; } GF_Err free_Size(GF_Box *s) { GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s; ptr->size += ptr->dataSize; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void ftyp_del(GF_Box *s) { GF_FileTypeBox *ptr = (GF_FileTypeBox *) s; if (ptr->altBrand) gf_free(ptr->altBrand); gf_free(ptr); } GF_Box *ftyp_New() { ISOM_DECL_BOX_ALLOC(GF_FileTypeBox, GF_ISOM_BOX_TYPE_FTYP); return (GF_Box *)tmp; } GF_Err ftyp_Read(GF_Box *s,GF_BitStream *bs) { u32 i; GF_FileTypeBox *ptr = (GF_FileTypeBox *)s; if (ptr->size < 8) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Found ftyp with size < 8, likely broken!\n")); return GF_BAD_PARAM; } ptr->majorBrand = gf_bs_read_u32(bs); ptr->minorVersion = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); ptr->altCount = ( (u32) (ptr->size)) / 4; if (!ptr->altCount) return GF_OK; if (ptr->altCount * 4 != (u32) (ptr->size)) return GF_ISOM_INVALID_FILE; ptr->altBrand = (u32*)gf_malloc(sizeof(u32)*ptr->altCount); for (i = 0; i<ptr->altCount; i++) { ptr->altBrand[i] = gf_bs_read_u32(bs); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err ftyp_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_FileTypeBox *ptr = (GF_FileTypeBox *) s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->majorBrand); gf_bs_write_u32(bs, ptr->minorVersion); for (i=0; i<ptr->altCount; i++) { gf_bs_write_u32(bs, ptr->altBrand[i]); } return GF_OK; } GF_Err ftyp_Size(GF_Box *s) { GF_FileTypeBox *ptr = (GF_FileTypeBox *)s; ptr->size += 8 + ptr->altCount * 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void gnrm_del(GF_Box *s) { GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr); if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Box *gnrm_New() { ISOM_DECL_BOX_ALLOC(GF_GenericSampleEntryBox, GF_ISOM_BOX_TYPE_GNRM); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); return (GF_Box *)tmp; } //dummy GF_Err gnrm_Read(GF_Box *s, GF_BitStream *bs) { return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err gnrm_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s; //carefull we are not writing the box type but the entry type so switch for write ptr->type = ptr->EntryType; e = gf_isom_box_write_header(s, bs); if (e) return e; ptr->type = GF_ISOM_BOX_TYPE_GNRM; gf_bs_write_data(bs, ptr->reserved, 6); gf_bs_write_u16(bs, ptr->dataReferenceIndex); gf_bs_write_data(bs, ptr->data, ptr->data_size); return GF_OK; } GF_Err gnrm_Size(GF_Box *s) { GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s; s->type = GF_ISOM_BOX_TYPE_GNRM; ptr->size += 8+ptr->data_size; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void gnrv_del(GF_Box *s) { GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr); if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Box *gnrv_New() { ISOM_DECL_BOX_ALLOC(GF_GenericVisualSampleEntryBox, GF_ISOM_BOX_TYPE_GNRV); gf_isom_video_sample_entry_init((GF_VisualSampleEntryBox*) tmp); return (GF_Box *)tmp; } //dummy GF_Err gnrv_Read(GF_Box *s, GF_BitStream *bs) { return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err gnrv_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s; //carefull we are not writing the box type but the entry type so switch for write ptr->type = ptr->EntryType; e = gf_isom_box_write_header(s, bs); if (e) return e; ptr->type = GF_ISOM_BOX_TYPE_GNRV; gf_isom_video_sample_entry_write((GF_VisualSampleEntryBox *)ptr, bs); gf_bs_write_data(bs, ptr->data, ptr->data_size); return GF_OK; } GF_Err gnrv_Size(GF_Box *s) { GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s; s->type = GF_ISOM_BOX_TYPE_GNRV; gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s); ptr->size += ptr->data_size; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void gnra_del(GF_Box *s) { GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr); if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Box *gnra_New() { ISOM_DECL_BOX_ALLOC(GF_GenericAudioSampleEntryBox, GF_ISOM_BOX_TYPE_GNRA); gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*) tmp); return (GF_Box *)tmp; } //dummy GF_Err gnra_Read(GF_Box *s, GF_BitStream *bs) { return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err gnra_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s; //carefull we are not writing the box type but the entry type so switch for write ptr->type = ptr->EntryType; e = gf_isom_box_write_header(s, bs); if (e) return e; ptr->type = GF_ISOM_BOX_TYPE_GNRA; gf_isom_audio_sample_entry_write((GF_AudioSampleEntryBox *)ptr, bs); if (ptr->data) { gf_bs_write_data(bs, ptr->data, ptr->data_size); } return GF_OK; } GF_Err gnra_Size(GF_Box *s) { GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s; s->type = GF_ISOM_BOX_TYPE_GNRA; gf_isom_audio_sample_entry_size((GF_AudioSampleEntryBox *)s); ptr->size += ptr->data_size; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void hdlr_del(GF_Box *s) { GF_HandlerBox *ptr = (GF_HandlerBox *)s; if (ptr == NULL) return; if (ptr->nameUTF8) gf_free(ptr->nameUTF8); gf_free(ptr); } GF_Err hdlr_Read(GF_Box *s, GF_BitStream *bs) { GF_HandlerBox *ptr = (GF_HandlerBox *)s; ptr->reserved1 = gf_bs_read_u32(bs); ptr->handlerType = gf_bs_read_u32(bs); gf_bs_read_data(bs, (char*)ptr->reserved2, 12); ISOM_DECREASE_SIZE(ptr, 20); if (ptr->size) { size_t len; ptr->nameUTF8 = (char*)gf_malloc((u32) ptr->size); if (ptr->nameUTF8 == NULL) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->nameUTF8, (u32) ptr->size); /*safety check in case the string is not null-terminated*/ if (ptr->nameUTF8[ptr->size-1]) { char *str = (char*)gf_malloc((u32) ptr->size + 1); memcpy(str, ptr->nameUTF8, (u32) ptr->size); str[ptr->size] = 0; gf_free(ptr->nameUTF8); ptr->nameUTF8 = str; } //patch for old QT files if (ptr->size > 1 && ptr->nameUTF8[0] == ptr->size-1) { len = strlen(ptr->nameUTF8 + 1); memmove(ptr->nameUTF8, ptr->nameUTF8+1, len ); ptr->nameUTF8[len] = 0; ptr->store_counted_string = GF_TRUE; } } return GF_OK; } GF_Box *hdlr_New() { ISOM_DECL_BOX_ALLOC(GF_HandlerBox, GF_ISOM_BOX_TYPE_HDLR); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err hdlr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_HandlerBox *ptr = (GF_HandlerBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->reserved1); gf_bs_write_u32(bs, ptr->handlerType); gf_bs_write_data(bs, (char*)ptr->reserved2, 12); if (ptr->nameUTF8) { u32 len = (u32)strlen(ptr->nameUTF8); if (ptr->store_counted_string) { gf_bs_write_u8(bs, len); gf_bs_write_data(bs, ptr->nameUTF8, len); } else { gf_bs_write_data(bs, ptr->nameUTF8, len); gf_bs_write_u8(bs, 0); } } else { gf_bs_write_u8(bs, 0); } return GF_OK; } GF_Err hdlr_Size(GF_Box *s) { GF_HandlerBox *ptr = (GF_HandlerBox *)s; ptr->size += 20 + 1; //null term or counted string if (ptr->nameUTF8) { ptr->size += strlen(ptr->nameUTF8); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void hinf_del(GF_Box *s) { GF_HintInfoBox *hinf = (GF_HintInfoBox *)s; gf_free(hinf); } GF_Box *hinf_New() { ISOM_DECL_BOX_ALLOC(GF_HintInfoBox, GF_ISOM_BOX_TYPE_HINF); tmp->other_boxes = gf_list_new(); return (GF_Box *)tmp; } GF_Err hinf_AddBox(GF_Box *s, GF_Box *a) { GF_MAXRBox *maxR; GF_HintInfoBox *hinf = (GF_HintInfoBox *)s; u32 i; switch (a->type) { case GF_ISOM_BOX_TYPE_MAXR: i=0; while ((maxR = (GF_MAXRBox *)gf_list_enum(hinf->other_boxes, &i))) { if ((maxR->type==GF_ISOM_BOX_TYPE_MAXR) && (maxR->granularity == ((GF_MAXRBox *)a)->granularity)) return GF_ISOM_INVALID_FILE; } break; } return gf_isom_box_add_default(s, a); } GF_Err hinf_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, hinf_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err hinf_Write(GF_Box *s, GF_BitStream *bs) { // GF_HintInfoBox *ptr = (GF_HintInfoBox *)s; if (!s) return GF_BAD_PARAM; return gf_isom_box_write_header(s, bs); } GF_Err hinf_Size(GF_Box *s) { return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void hmhd_del(GF_Box *s) { GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err hmhd_Read(GF_Box *s,GF_BitStream *bs) { GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s; ptr->maxPDUSize = gf_bs_read_u16(bs); ptr->avgPDUSize = gf_bs_read_u16(bs); ptr->maxBitrate = gf_bs_read_u32(bs); ptr->avgBitrate = gf_bs_read_u32(bs); ptr->slidingAverageBitrate = gf_bs_read_u32(bs); return GF_OK; } GF_Box *hmhd_New() { ISOM_DECL_BOX_ALLOC(GF_HintMediaHeaderBox, GF_ISOM_BOX_TYPE_HMHD); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err hmhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->maxPDUSize); gf_bs_write_u16(bs, ptr->avgPDUSize); gf_bs_write_u32(bs, ptr->maxBitrate); gf_bs_write_u32(bs, ptr->avgBitrate); gf_bs_write_u32(bs, ptr->slidingAverageBitrate); return GF_OK; } GF_Err hmhd_Size(GF_Box *s) { GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s; ptr->size += 16; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *hnti_New() { ISOM_DECL_BOX_ALLOC(GF_HintTrackInfoBox, GF_ISOM_BOX_TYPE_HNTI); return (GF_Box *)tmp; } void hnti_del(GF_Box *a) { gf_free(a); } GF_Err hnti_AddBox(GF_Box *s, GF_Box *a) { GF_HintTrackInfoBox *hnti = (GF_HintTrackInfoBox *)s; if (!hnti || !a) return GF_BAD_PARAM; switch (a->type) { //this is the value for GF_RTPBox - same as HintSampleEntry for RTP !!! case GF_ISOM_BOX_TYPE_RTP: case GF_ISOM_BOX_TYPE_SDP: if (hnti->SDP) return GF_BAD_PARAM; hnti->SDP = a; break; default: break; } return gf_isom_box_add_default(s, a); } GF_Err hnti_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read_ex(s, bs, hnti_AddBox, s->type); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err hnti_Write(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_write_header(s, bs); } GF_Err hnti_Size(GF_Box *s) { return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** GF_SDPBox **********************************************************/ void sdp_del(GF_Box *s) { GF_SDPBox *ptr = (GF_SDPBox *)s; if (ptr->sdpText) gf_free(ptr->sdpText); gf_free(ptr); } GF_Err sdp_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_SDPBox *ptr = (GF_SDPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; length = (u32) (ptr->size); //sdp text has no delimiter !!! ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1)); if (!ptr->sdpText) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->sdpText, length); ptr->sdpText[length] = 0; return GF_OK; } GF_Box *sdp_New() { ISOM_DECL_BOX_ALLOC(GF_SDPBox, GF_ISOM_BOX_TYPE_SDP); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err sdp_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SDPBox *ptr = (GF_SDPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; //don't write the NULL char!!! gf_bs_write_data(bs, ptr->sdpText, (u32) strlen(ptr->sdpText)); return GF_OK; } GF_Err sdp_Size(GF_Box *s) { GF_SDPBox *ptr = (GF_SDPBox *)s; //don't count the NULL char!!! ptr->size += strlen(ptr->sdpText); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void rtp_hnti_del(GF_Box *s) { GF_RTPBox *ptr = (GF_RTPBox *)s; if (ptr->sdpText) gf_free(ptr->sdpText); gf_free(ptr); } GF_Err rtp_hnti_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_RTPBox *ptr = (GF_RTPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; ISOM_DECREASE_SIZE(ptr, 4) ptr->subType = gf_bs_read_u32(bs); length = (u32) (ptr->size); //sdp text has no delimiter !!! ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1)); if (!ptr->sdpText) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->sdpText, length); ptr->sdpText[length] = 0; return GF_OK; } GF_Box *rtp_hnti_New() { ISOM_DECL_BOX_ALLOC(GF_RTPBox, GF_ISOM_BOX_TYPE_RTP); tmp->subType = GF_ISOM_BOX_TYPE_SDP; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err rtp_hnti_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_RTPBox *ptr = (GF_RTPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->subType); //don't write the NULL char!!! gf_bs_write_data(bs, ptr->sdpText, (u32) strlen(ptr->sdpText)); return GF_OK; } GF_Err rtp_hnti_Size(GF_Box *s) { GF_RTPBox *ptr = (GF_RTPBox *)s; ptr->size += 4 + strlen(ptr->sdpText); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TRPY GF_Box **********************************************************/ void trpy_del(GF_Box *s) { gf_free((GF_TRPYBox *)s); } GF_Err trpy_Read(GF_Box *s, GF_BitStream *bs) { GF_TRPYBox *ptr = (GF_TRPYBox *)s; ptr->nbBytes = gf_bs_read_u64(bs); return GF_OK; } GF_Box *trpy_New() { ISOM_DECL_BOX_ALLOC(GF_TRPYBox, GF_ISOM_BOX_TYPE_TRPY); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trpy_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TRPYBox *ptr = (GF_TRPYBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbBytes); return GF_OK; } GF_Err trpy_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TOTL GF_Box **********************************************************/ void totl_del(GF_Box *s) { gf_free((GF_TRPYBox *)s); } GF_Err totl_Read(GF_Box *s, GF_BitStream *bs) { GF_TOTLBox *ptr = (GF_TOTLBox *)s; ptr->nbBytes = gf_bs_read_u32(bs); return GF_OK; } GF_Box *totl_New() { ISOM_DECL_BOX_ALLOC(GF_TOTLBox, GF_ISOM_BOX_TYPE_TOTL); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err totl_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TOTLBox *ptr = (GF_TOTLBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nbBytes); return GF_OK; } GF_Err totl_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** NUMP GF_Box **********************************************************/ void nump_del(GF_Box *s) { gf_free((GF_NUMPBox *)s); } GF_Err nump_Read(GF_Box *s, GF_BitStream *bs) { GF_NUMPBox *ptr = (GF_NUMPBox *)s; ptr->nbPackets = gf_bs_read_u64(bs); return GF_OK; } GF_Box *nump_New() { ISOM_DECL_BOX_ALLOC(GF_NUMPBox, GF_ISOM_BOX_TYPE_NUMP); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err nump_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NUMPBox *ptr = (GF_NUMPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbPackets); return GF_OK; } GF_Err nump_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** NPCK GF_Box **********************************************************/ void npck_del(GF_Box *s) { gf_free((GF_NPCKBox *)s); } GF_Err npck_Read(GF_Box *s, GF_BitStream *bs) { GF_NPCKBox *ptr = (GF_NPCKBox *)s; ptr->nbPackets = gf_bs_read_u32(bs); return GF_OK; } GF_Box *npck_New() { ISOM_DECL_BOX_ALLOC(GF_NPCKBox, GF_ISOM_BOX_TYPE_NPCK); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err npck_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NPCKBox *ptr = (GF_NPCKBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nbPackets); return GF_OK; } GF_Err npck_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TPYL GF_Box **********************************************************/ void tpyl_del(GF_Box *s) { gf_free((GF_NTYLBox *)s); } GF_Err tpyl_Read(GF_Box *s, GF_BitStream *bs) { GF_NTYLBox *ptr = (GF_NTYLBox *)s; if (ptr == NULL) return GF_BAD_PARAM; ptr->nbBytes = gf_bs_read_u64(bs); return GF_OK; } GF_Box *tpyl_New() { ISOM_DECL_BOX_ALLOC(GF_NTYLBox, GF_ISOM_BOX_TYPE_TPYL); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tpyl_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NTYLBox *ptr = (GF_NTYLBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbBytes); return GF_OK; } GF_Err tpyl_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TPAY GF_Box **********************************************************/ void tpay_del(GF_Box *s) { gf_free((GF_TPAYBox *)s); } GF_Err tpay_Read(GF_Box *s, GF_BitStream *bs) { GF_TPAYBox *ptr = (GF_TPAYBox *)s; ptr->nbBytes = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tpay_New() { ISOM_DECL_BOX_ALLOC(GF_TPAYBox, GF_ISOM_BOX_TYPE_TPAY); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tpay_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TPAYBox *ptr = (GF_TPAYBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nbBytes); return GF_OK; } GF_Err tpay_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** MAXR GF_Box **********************************************************/ void maxr_del(GF_Box *s) { gf_free((GF_MAXRBox *)s); } GF_Err maxr_Read(GF_Box *s, GF_BitStream *bs) { GF_MAXRBox *ptr = (GF_MAXRBox *)s; if (ptr == NULL) return GF_BAD_PARAM; ptr->granularity = gf_bs_read_u32(bs); ptr->maxDataRate = gf_bs_read_u32(bs); return GF_OK; } GF_Box *maxr_New() { ISOM_DECL_BOX_ALLOC(GF_MAXRBox, GF_ISOM_BOX_TYPE_MAXR); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err maxr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MAXRBox *ptr = (GF_MAXRBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->granularity); gf_bs_write_u32(bs, ptr->maxDataRate); return GF_OK; } GF_Err maxr_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** DMED GF_Box **********************************************************/ void dmed_del(GF_Box *s) { gf_free((GF_DMEDBox *)s); } GF_Err dmed_Read(GF_Box *s, GF_BitStream *bs) { GF_DMEDBox *ptr = (GF_DMEDBox *)s; ptr->nbBytes = gf_bs_read_u64(bs); return GF_OK; } GF_Box *dmed_New() { ISOM_DECL_BOX_ALLOC(GF_DMEDBox, GF_ISOM_BOX_TYPE_DMED); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dmed_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DMEDBox *ptr = (GF_DMEDBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbBytes); return GF_OK; } GF_Err dmed_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** DIMM GF_Box **********************************************************/ void dimm_del(GF_Box *s) { gf_free((GF_DIMMBox *)s); } GF_Err dimm_Read(GF_Box *s, GF_BitStream *bs) { GF_DIMMBox *ptr = (GF_DIMMBox *)s; ptr->nbBytes = gf_bs_read_u64(bs); return GF_OK; } GF_Box *dimm_New() { ISOM_DECL_BOX_ALLOC(GF_DIMMBox, GF_ISOM_BOX_TYPE_DIMM); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dimm_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DIMMBox *ptr = (GF_DIMMBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbBytes); return GF_OK; } GF_Err dimm_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** DREP GF_Box **********************************************************/ void drep_del(GF_Box *s) { gf_free((GF_DREPBox *)s); } GF_Err drep_Read(GF_Box *s, GF_BitStream *bs) { GF_DREPBox *ptr = (GF_DREPBox *)s; ptr->nbBytes = gf_bs_read_u64(bs); return GF_OK; } GF_Box *drep_New() { ISOM_DECL_BOX_ALLOC(GF_DREPBox, GF_ISOM_BOX_TYPE_DREP); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err drep_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DREPBox *ptr = (GF_DREPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->nbBytes); return GF_OK; } GF_Err drep_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TMIN GF_Box **********************************************************/ void tmin_del(GF_Box *s) { gf_free((GF_TMINBox *)s); } GF_Err tmin_Read(GF_Box *s, GF_BitStream *bs) { GF_TMINBox *ptr = (GF_TMINBox *)s; ptr->minTime = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tmin_New() { ISOM_DECL_BOX_ALLOC(GF_TMINBox, GF_ISOM_BOX_TYPE_TMIN); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tmin_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TMINBox *ptr = (GF_TMINBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->minTime); return GF_OK; } GF_Err tmin_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** TMAX GF_Box **********************************************************/ void tmax_del(GF_Box *s) { gf_free((GF_TMAXBox *)s); } GF_Err tmax_Read(GF_Box *s, GF_BitStream *bs) { GF_TMAXBox *ptr = (GF_TMAXBox *)s; ptr->maxTime = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tmax_New() { ISOM_DECL_BOX_ALLOC(GF_TMAXBox, GF_ISOM_BOX_TYPE_TMAX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tmax_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TMAXBox *ptr = (GF_TMAXBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->maxTime); return GF_OK; } GF_Err tmax_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** PMAX GF_Box **********************************************************/ void pmax_del(GF_Box *s) { gf_free((GF_PMAXBox *)s); } GF_Err pmax_Read(GF_Box *s, GF_BitStream *bs) { GF_PMAXBox *ptr = (GF_PMAXBox *)s; ptr->maxSize = gf_bs_read_u32(bs); return GF_OK; } GF_Box *pmax_New() { ISOM_DECL_BOX_ALLOC(GF_PMAXBox, GF_ISOM_BOX_TYPE_PMAX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err pmax_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_PMAXBox *ptr = (GF_PMAXBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->maxSize); return GF_OK; } GF_Err pmax_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** DMAX GF_Box **********************************************************/ void dmax_del(GF_Box *s) { gf_free((GF_DMAXBox *)s); } GF_Err dmax_Read(GF_Box *s, GF_BitStream *bs) { GF_DMAXBox *ptr = (GF_DMAXBox *)s; ptr->maxDur = gf_bs_read_u32(bs); return GF_OK; } GF_Box *dmax_New() { ISOM_DECL_BOX_ALLOC(GF_DMAXBox, GF_ISOM_BOX_TYPE_DMAX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dmax_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_DMAXBox *ptr = (GF_DMAXBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->maxDur); return GF_OK; } GF_Err dmax_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** PAYT GF_Box **********************************************************/ void payt_del(GF_Box *s) { GF_PAYTBox *payt = (GF_PAYTBox *)s; if (payt->payloadString) gf_free(payt->payloadString); gf_free(payt); } GF_Err payt_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_PAYTBox *ptr = (GF_PAYTBox *)s; ptr->payloadCode = gf_bs_read_u32(bs); length = gf_bs_read_u8(bs); ptr->payloadString = (char*)gf_malloc(sizeof(char) * (length+1) ); if (! ptr->payloadString) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->payloadString, length); ptr->payloadString[length] = 0; ISOM_DECREASE_SIZE(ptr, (4+length+1) ); return GF_OK; } GF_Box *payt_New() { ISOM_DECL_BOX_ALLOC(GF_PAYTBox, GF_ISOM_BOX_TYPE_PAYT); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err payt_Write(GF_Box *s, GF_BitStream *bs) { u32 len; GF_Err e; GF_PAYTBox *ptr = (GF_PAYTBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->payloadCode); len = (u32) strlen(ptr->payloadString); gf_bs_write_u8(bs, len); if (len) gf_bs_write_data(bs, ptr->payloadString, len); return GF_OK; } GF_Err payt_Size(GF_Box *s) { GF_PAYTBox *ptr = (GF_PAYTBox *)s; s->size += 4; if (ptr->payloadString) ptr->size += strlen(ptr->payloadString) + 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /********************************************************** PAYT GF_Box **********************************************************/ void name_del(GF_Box *s) { GF_NameBox *name = (GF_NameBox *)s; if (name->string) gf_free(name->string); gf_free(name); } GF_Err name_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_NameBox *ptr = (GF_NameBox *)s; length = (u32) (ptr->size); ptr->string = (char*)gf_malloc(sizeof(char) * (length+1)); if (! ptr->string) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->string, length); ptr->string[length] = 0; return GF_OK; } GF_Box *name_New() { ISOM_DECL_BOX_ALLOC(GF_NameBox, GF_ISOM_BOX_TYPE_NAME); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err name_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NameBox *ptr = (GF_NameBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->string) { gf_bs_write_data(bs, ptr->string, (u32) strlen(ptr->string) + 1); } return GF_OK; } GF_Err name_Size(GF_Box *s) { GF_NameBox *ptr = (GF_NameBox *)s; if (ptr->string) ptr->size += strlen(ptr->string) + 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void tssy_del(GF_Box *s) { gf_free(s); } GF_Err tssy_Read(GF_Box *s, GF_BitStream *bs) { GF_TimeStampSynchronyBox *ptr = (GF_TimeStampSynchronyBox *)s; gf_bs_read_int(bs, 6); ptr->timestamp_sync = gf_bs_read_int(bs, 2); return GF_OK; } GF_Box *tssy_New() { ISOM_DECL_BOX_ALLOC(GF_TimeStampSynchronyBox, GF_ISOM_BOX_TYPE_TSSY); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tssy_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TimeStampSynchronyBox *ptr = (GF_TimeStampSynchronyBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_int(bs, 0, 6); gf_bs_write_int(bs, ptr->timestamp_sync, 2); return GF_OK; } GF_Err tssy_Size(GF_Box *s) { s->size += 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void srpp_del(GF_Box *s) { GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s; if (ptr->info) gf_isom_box_del((GF_Box*)ptr->info); if (ptr->scheme_type) gf_isom_box_del((GF_Box*)ptr->scheme_type); gf_free(s); } GF_Err srpp_AddBox(GF_Box *s, GF_Box *a) { GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_SCHI: if (ptr->info) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->info = (GF_SchemeInformationBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_SCHM: if (ptr->scheme_type) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->scheme_type = (GF_SchemeTypeBox *)a; return GF_OK; } return gf_isom_box_add_default(s, a); } GF_Err srpp_Read(GF_Box *s, GF_BitStream *bs) { GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s; ISOM_DECREASE_SIZE(s, 16) ptr->encryption_algorithm_rtp = gf_bs_read_u32(bs); ptr->encryption_algorithm_rtcp = gf_bs_read_u32(bs); ptr->integrity_algorithm_rtp = gf_bs_read_u32(bs); ptr->integrity_algorithm_rtp = gf_bs_read_u32(bs); return gf_isom_box_array_read(s, bs, gf_isom_box_add_default); } GF_Box *srpp_New() { ISOM_DECL_BOX_ALLOC(GF_SRTPProcessBox, GF_ISOM_BOX_TYPE_SRPP); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err srpp_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->encryption_algorithm_rtp); gf_bs_write_u32(bs, ptr->encryption_algorithm_rtcp); gf_bs_write_u32(bs, ptr->integrity_algorithm_rtp); gf_bs_write_u32(bs, ptr->integrity_algorithm_rtcp); if (ptr->info) { e = gf_isom_box_write((GF_Box*)ptr->info, bs); if (e) return e; } if (ptr->scheme_type) { e = gf_isom_box_write((GF_Box*)ptr->scheme_type, bs); if (e) return e; } return GF_OK; } GF_Err srpp_Size(GF_Box *s) { GF_Err e; GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s; s->size += 16; if (ptr->info) { e = gf_isom_box_size((GF_Box*)ptr->info); if (e) return e; ptr->size += ptr->info->size; } if (ptr->scheme_type) { e = gf_isom_box_size((GF_Box*)ptr->scheme_type); if (e) return e; ptr->size += ptr->scheme_type->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void rssr_del(GF_Box *s) { gf_free(s); } GF_Err rssr_Read(GF_Box *s, GF_BitStream *bs) { GF_ReceivedSsrcBox *ptr = (GF_ReceivedSsrcBox *)s; ptr->ssrc = gf_bs_read_u32(bs); return GF_OK; } GF_Box *rssr_New() { ISOM_DECL_BOX_ALLOC(GF_ReceivedSsrcBox, GF_ISOM_BOX_TYPE_RSSR); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err rssr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_ReceivedSsrcBox *ptr = (GF_ReceivedSsrcBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->ssrc); return GF_OK; } GF_Err rssr_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void iods_del(GF_Box *s) { GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s; if (ptr == NULL) return; if (ptr->descriptor) gf_odf_desc_del(ptr->descriptor); gf_free(ptr); } GF_Err iods_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 descSize; char *desc; GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s; //use the OD codec... descSize = (u32) (ptr->size); desc = (char*)gf_malloc(sizeof(char) * descSize); gf_bs_read_data(bs, desc, descSize); e = gf_odf_desc_read(desc, descSize, &ptr->descriptor); //OK, free our desc gf_free(desc); return e; } GF_Box *iods_New() { ISOM_DECL_BOX_ALLOC(GF_ObjectDescriptorBox, GF_ISOM_BOX_TYPE_IODS); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err iods_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 descSize; char *desc; GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; //call our OD codec e = gf_odf_desc_write(ptr->descriptor, &desc, &descSize); if (e) return e; gf_bs_write_data(bs, desc, descSize); //and free our stuff maybe!! gf_free(desc); return GF_OK; } GF_Err iods_Size(GF_Box *s) { GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s; ptr->size += gf_odf_desc_size(ptr->descriptor); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mdat_del(GF_Box *s) { GF_MediaDataBox *ptr = (GF_MediaDataBox *)s; if (!s) return; if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Err mdat_Read(GF_Box *s, GF_BitStream *bs) { GF_MediaDataBox *ptr = (GF_MediaDataBox *)s; if (ptr == NULL) return GF_BAD_PARAM; ptr->dataSize = s->size; ptr->bsOffset = gf_bs_get_position(bs); //then skip these bytes gf_bs_skip_bytes(bs, ptr->dataSize); return GF_OK; } GF_Box *mdat_New() { ISOM_DECL_BOX_ALLOC(GF_MediaDataBox, GF_ISOM_BOX_TYPE_MDAT); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mdat_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MediaDataBox *ptr = (GF_MediaDataBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; //make sure we have some data ... //if not, we handle that independantly (edit files) if (ptr->data) { gf_bs_write_data(bs, ptr->data, (u32) ptr->dataSize); } return GF_OK; } GF_Err mdat_Size(GF_Box *s) { GF_MediaDataBox *ptr = (GF_MediaDataBox *)s; ptr->size += ptr->dataSize; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mdhd_del(GF_Box *s) { GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err mdhd_Read(GF_Box *s, GF_BitStream *bs) { GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; if (ptr->version == 1) { ptr->creationTime = gf_bs_read_u64(bs); ptr->modificationTime = gf_bs_read_u64(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u64(bs); } else { ptr->creationTime = gf_bs_read_u32(bs); ptr->modificationTime = gf_bs_read_u32(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u32(bs); } if (!ptr->timeScale) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Media header timescale is 0 - defaulting to 90000\n" )); ptr->timeScale = 90000; } ptr->original_duration = ptr->duration; //our padding bit gf_bs_read_int(bs, 1); //the spec is unclear here, just says "the value 0 is interpreted as undetermined" ptr->packedLanguage[0] = gf_bs_read_int(bs, 5); ptr->packedLanguage[1] = gf_bs_read_int(bs, 5); ptr->packedLanguage[2] = gf_bs_read_int(bs, 5); //but before or after compaction ?? We assume before if (ptr->packedLanguage[0] || ptr->packedLanguage[1] || ptr->packedLanguage[2]) { ptr->packedLanguage[0] += 0x60; ptr->packedLanguage[1] += 0x60; ptr->packedLanguage[2] += 0x60; } else { ptr->packedLanguage[0] = 'u'; ptr->packedLanguage[1] = 'n'; ptr->packedLanguage[2] = 'd'; } ptr->reserved = gf_bs_read_u16(bs); return GF_OK; } GF_Box *mdhd_New() { ISOM_DECL_BOX_ALLOC(GF_MediaHeaderBox, GF_ISOM_BOX_TYPE_MDHD); tmp->packedLanguage[0] = 'u'; tmp->packedLanguage[1] = 'n'; tmp->packedLanguage[2] = 'd'; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mdhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->version == 1) { gf_bs_write_u64(bs, ptr->creationTime); gf_bs_write_u64(bs, ptr->modificationTime); gf_bs_write_u32(bs, ptr->timeScale); gf_bs_write_u64(bs, ptr->duration); } else { gf_bs_write_u32(bs, (u32) ptr->creationTime); gf_bs_write_u32(bs, (u32) ptr->modificationTime); gf_bs_write_u32(bs, ptr->timeScale); gf_bs_write_u32(bs, (u32) ptr->duration); } //SPECS: BIT(1) of padding gf_bs_write_int(bs, 0, 1); gf_bs_write_int(bs, ptr->packedLanguage[0] - 0x60, 5); gf_bs_write_int(bs, ptr->packedLanguage[1] - 0x60, 5); gf_bs_write_int(bs, ptr->packedLanguage[2] - 0x60, 5); gf_bs_write_u16(bs, ptr->reserved); return GF_OK; } GF_Err mdhd_Size(GF_Box *s) { GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0; ptr->size += 4; ptr->size += (ptr->version == 1) ? 28 : 16; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mdia_del(GF_Box *s) { GF_MediaBox *ptr = (GF_MediaBox *)s; if (ptr == NULL) return; if (ptr->mediaHeader) gf_isom_box_del((GF_Box *)ptr->mediaHeader); if (ptr->information) gf_isom_box_del((GF_Box *)ptr->information); if (ptr->handler) gf_isom_box_del((GF_Box *)ptr->handler); gf_free(ptr); } GF_Err mdia_AddBox(GF_Box *s, GF_Box *a) { GF_MediaBox *ptr = (GF_MediaBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_MDHD: if (ptr->mediaHeader) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mediaHeader = (GF_MediaHeaderBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_HDLR: if (ptr->handler) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->handler = (GF_HandlerBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_MINF: if (ptr->information) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->information = (GF_MediaInformationBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err mdia_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, mdia_AddBox); if (e) return e; if (!((GF_MediaBox *)s)->information) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaInformationBox\n")); return GF_ISOM_INVALID_FILE; } if (!((GF_MediaBox *)s)->handler) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing HandlerBox\n")); return GF_ISOM_INVALID_FILE; } if (!((GF_MediaBox *)s)->mediaHeader) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaHeaderBox\n")); return GF_ISOM_INVALID_FILE; } return GF_OK; } GF_Box *mdia_New() { ISOM_DECL_BOX_ALLOC(GF_MediaBox, GF_ISOM_BOX_TYPE_MDIA); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mdia_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MediaBox *ptr = (GF_MediaBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; //Header first if (ptr->mediaHeader) { e = gf_isom_box_write((GF_Box *) ptr->mediaHeader, bs); if (e) return e; } //then handler if (ptr->handler) { e = gf_isom_box_write((GF_Box *) ptr->handler, bs); if (e) return e; } if (ptr->information) { e = gf_isom_box_write((GF_Box *) ptr->information, bs); if (e) return e; } return GF_OK; } GF_Err mdia_Size(GF_Box *s) { GF_Err e; GF_MediaBox *ptr = (GF_MediaBox *)s; if (ptr->mediaHeader) { e = gf_isom_box_size((GF_Box *) ptr->mediaHeader); if (e) return e; ptr->size += ptr->mediaHeader->size; } if (ptr->handler) { e = gf_isom_box_size((GF_Box *) ptr->handler); if (e) return e; ptr->size += ptr->handler->size; } if (ptr->information) { e = gf_isom_box_size((GF_Box *) ptr->information); if (e) return e; ptr->size += ptr->information->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mfra_del(GF_Box *s) { GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s; if (ptr == NULL) return; if (ptr->mfro) gf_isom_box_del((GF_Box*)ptr->mfro); gf_isom_box_array_del(ptr->tfra_list); gf_free(ptr); } GF_Box *mfra_New() { ISOM_DECL_BOX_ALLOC(GF_MovieFragmentRandomAccessBox, GF_ISOM_BOX_TYPE_MFRA); tmp->tfra_list = gf_list_new(); return (GF_Box *)tmp; } GF_Err mfra_AddBox(GF_Box *s, GF_Box *a) { GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_TFRA: return gf_list_add(ptr->tfra_list, a); case GF_ISOM_BOX_TYPE_MFRO: if (ptr->mfro) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mfro = (GF_MovieFragmentRandomAccessOffsetBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err mfra_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, mfra_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mfra_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; e = gf_isom_box_array_write(s, ptr->tfra_list, bs); if (e) return e; if (ptr->mfro) { e = gf_isom_box_write((GF_Box *) ptr->mfro, bs); if (e) return e; } return GF_OK; } GF_Err mfra_Size(GF_Box *s) { GF_Err e; GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s; if (ptr->mfro) { e = gf_isom_box_size((GF_Box *)ptr->mfro); if (e) return e; ptr->size += ptr->mfro->size; } return gf_isom_box_array_size(s, ptr->tfra_list); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void tfra_del(GF_Box *s) { GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s; if (ptr == NULL) return; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Box *tfra_New() { ISOM_DECL_BOX_ALLOC(GF_TrackFragmentRandomAccessBox, GF_ISOM_BOX_TYPE_TFRA); return (GF_Box *)tmp; } GF_Err tfra_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_RandomAccessEntry *p = 0; GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s; if (ptr->size<12) return GF_ISOM_INVALID_FILE; ptr->track_id = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (gf_bs_read_int(bs, 26) !=0) return GF_ISOM_INVALID_FILE; ptr->traf_bits = (gf_bs_read_int(bs, 2)+1)*8; ptr->trun_bits = (gf_bs_read_int(bs, 2)+1)*8; ptr->sample_bits = (gf_bs_read_int(bs, 2)+1)*8; ISOM_DECREASE_SIZE(ptr, 4); ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->version==1) { if (ptr->nb_entries > ptr->size / (16+(ptr->traf_bits+ptr->trun_bits+ptr->sample_bits)/8)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in traf\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } } else { if (ptr->nb_entries > ptr->size / (8+(ptr->traf_bits+ptr->trun_bits+ptr->sample_bits)/8)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in traf\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } } if (ptr->nb_entries) { p = (GF_RandomAccessEntry *) gf_malloc(sizeof(GF_RandomAccessEntry) * ptr->nb_entries); if (!p) return GF_OUT_OF_MEM; } ptr->entries = p; for (i=0; i<ptr->nb_entries; i++) { memset(p, 0, sizeof(GF_RandomAccessEntry)); if (ptr->version==1) { p->time = gf_bs_read_u64(bs); p->moof_offset = gf_bs_read_u64(bs); } else { p->time = gf_bs_read_u32(bs); p->moof_offset = gf_bs_read_u32(bs); } p->traf_number = gf_bs_read_int(bs, ptr->traf_bits); p->trun_number = gf_bs_read_int(bs, ptr->trun_bits); p->sample_number = gf_bs_read_int(bs, ptr->sample_bits); ++p; } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tfra_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->track_id); gf_bs_write_int(bs, 0, 26); gf_bs_write_int(bs, ptr->traf_bits/8 - 1, 2); gf_bs_write_int(bs, ptr->trun_bits/8 - 1, 2); gf_bs_write_int(bs, ptr->sample_bits/8 - 1, 2); gf_bs_write_u32(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++) { GF_RandomAccessEntry *p = &ptr->entries[i]; if (ptr->version==1) { gf_bs_write_u64(bs, p->time); gf_bs_write_u64(bs, p->moof_offset); } else { gf_bs_write_u32(bs, (u32) p->time); gf_bs_write_u32(bs, (u32) p->moof_offset); } gf_bs_write_int(bs, p->traf_number, ptr->traf_bits); gf_bs_write_int(bs, p->trun_number, ptr->trun_bits); gf_bs_write_int(bs, p->sample_number, ptr->sample_bits); } return GF_OK; } GF_Err tfra_Size(GF_Box *s) { GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s; ptr->size += 12; ptr->size += ptr->nb_entries * ( ((ptr->version==1) ? 16 : 8 ) + ptr->traf_bits/8 + ptr->trun_bits/8 + ptr->sample_bits/8); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mfro_del(GF_Box *s) { GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Box *mfro_New() { ISOM_DECL_BOX_ALLOC(GF_MovieFragmentRandomAccessOffsetBox, GF_ISOM_BOX_TYPE_MFRO); return (GF_Box *)tmp; } GF_Err mfro_Read(GF_Box *s, GF_BitStream *bs) { GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s; ptr->container_size = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mfro_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->container_size); return GF_OK; } GF_Err mfro_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void elng_del(GF_Box *s) { GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s; if (ptr == NULL) return; if (ptr->extended_language) gf_free(ptr->extended_language); gf_free(ptr); } GF_Err elng_Read(GF_Box *s, GF_BitStream *bs) { GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s; if (ptr->size) { ptr->extended_language = (char*)gf_malloc((u32) ptr->size); if (ptr->extended_language == NULL) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->extended_language, (u32) ptr->size); /*safety check in case the string is not null-terminated*/ if (ptr->extended_language[ptr->size-1]) { char *str = (char*)gf_malloc((u32) ptr->size + 1); memcpy(str, ptr->extended_language, (u32) ptr->size); str[ptr->size] = 0; gf_free(ptr->extended_language); ptr->extended_language = str; } } return GF_OK; } GF_Box *elng_New() { ISOM_DECL_BOX_ALLOC(GF_MediaBox, GF_ISOM_BOX_TYPE_ELNG); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err elng_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->extended_language) { gf_bs_write_data(bs, ptr->extended_language, (u32)(strlen(ptr->extended_language)+1)); } return GF_OK; } GF_Err elng_Size(GF_Box *s) { GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s; if (ptr->extended_language) { ptr->size += strlen(ptr->extended_language)+1; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void mfhd_del(GF_Box *s) { GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err mfhd_Read(GF_Box *s, GF_BitStream *bs) { GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *)s; ptr->sequence_number = gf_bs_read_u32(bs); return GF_OK; } GF_Box *mfhd_New() { ISOM_DECL_BOX_ALLOC(GF_MovieFragmentHeaderBox, GF_ISOM_BOX_TYPE_MFHD); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mfhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->sequence_number); return GF_OK; } GF_Err mfhd_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void minf_del(GF_Box *s) { GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s; if (ptr == NULL) return; //if we have a Handler not self-contained, delete it (the self-contained belongs to the movie) if (ptr->dataHandler) { gf_isom_datamap_close(ptr); } if (ptr->InfoHeader) gf_isom_box_del((GF_Box *)ptr->InfoHeader); if (ptr->dataInformation) gf_isom_box_del((GF_Box *)ptr->dataInformation); if (ptr->sampleTable) gf_isom_box_del((GF_Box *)ptr->sampleTable); gf_free(ptr); } GF_Err minf_AddBox(GF_Box *s, GF_Box *a) { GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_NMHD: case GF_ISOM_BOX_TYPE_STHD: case GF_ISOM_BOX_TYPE_VMHD: case GF_ISOM_BOX_TYPE_SMHD: case GF_ISOM_BOX_TYPE_HMHD: case GF_ISOM_BOX_TYPE_GMHD: if (ptr->InfoHeader) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->InfoHeader = a; return GF_OK; case GF_ISOM_BOX_TYPE_DINF: if (ptr->dataInformation) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->dataInformation = (GF_DataInformationBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_STBL: if (ptr->sampleTable ) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->sampleTable = (GF_SampleTableBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err minf_Read(GF_Box *s, GF_BitStream *bs) { GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s; GF_Err e; e = gf_isom_box_array_read(s, bs, minf_AddBox); if (! ptr->dataInformation) { GF_Box *dinf, *dref, *url; Bool dump_mode = GF_FALSE; GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing DataInformationBox\n")); //commented on purpose, we are still able to handle the file, we only throw an error but keep processing // e = GF_ISOM_INVALID_FILE; //add a dinf box to avoid any access to a null dinf dinf = gf_isom_box_new(GF_ISOM_BOX_TYPE_DINF); if (!dinf) return GF_OUT_OF_MEM; if (ptr->InfoHeader && gf_list_find(ptr->other_boxes, ptr->InfoHeader)>=0) dump_mode = GF_TRUE; if (ptr->sampleTable && gf_list_find(ptr->other_boxes, ptr->sampleTable)>=0) dump_mode = GF_TRUE; ptr->dataInformation = (GF_DataInformationBox *)dinf; dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); if (!dref) return GF_OUT_OF_MEM; e = dinf_AddBox(dinf, dref); url = gf_isom_box_new(GF_ISOM_BOX_TYPE_URL); if (!url) return GF_OUT_OF_MEM; ((GF_FullBox*)url)->flags = 1; e = gf_isom_box_add_default(dref, url); if (dump_mode) { gf_list_add(ptr->other_boxes, ptr->dataInformation); if (!dinf->other_boxes) dinf->other_boxes = gf_list_new(); gf_list_add(dinf->other_boxes, dref); } } return e; } GF_Box *minf_New() { ISOM_DECL_BOX_ALLOC(GF_MediaInformationBox, GF_ISOM_BOX_TYPE_MINF); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err minf_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; //Header first if (ptr->InfoHeader) { e = gf_isom_box_write((GF_Box *) ptr->InfoHeader, bs); if (e) return e; } //then dataInfo if (ptr->dataInformation) { e = gf_isom_box_write((GF_Box *) ptr->dataInformation, bs); if (e) return e; } //then sampleTable if (ptr->sampleTable) { e = gf_isom_box_write((GF_Box *) ptr->sampleTable, bs); if (e) return e; } return GF_OK; } GF_Err minf_Size(GF_Box *s) { GF_Err e; GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s; if (ptr->InfoHeader) { e = gf_isom_box_size((GF_Box *) ptr->InfoHeader); if (e) return e; ptr->size += ptr->InfoHeader->size; } if (ptr->dataInformation) { e = gf_isom_box_size((GF_Box *) ptr->dataInformation); if (e) return e; ptr->size += ptr->dataInformation->size; } if (ptr->sampleTable) { e = gf_isom_box_size((GF_Box *) ptr->sampleTable); if (e) return e; ptr->size += ptr->sampleTable->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void moof_del(GF_Box *s) { GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s; if (ptr == NULL) return; if (ptr->mfhd) gf_isom_box_del((GF_Box *) ptr->mfhd); gf_isom_box_array_del(ptr->TrackList); if (ptr->mdat) gf_free(ptr->mdat); gf_free(ptr); } GF_Err moof_AddBox(GF_Box *s, GF_Box *a) { GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_MFHD: if (ptr->mfhd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mfhd = (GF_MovieFragmentHeaderBox *) a; return GF_OK; case GF_ISOM_BOX_TYPE_TRAF: return gf_list_add(ptr->TrackList, a); case GF_ISOM_BOX_TYPE_PSSH: default: return gf_isom_box_add_default(s, a); } } GF_Err moof_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, moof_AddBox); } GF_Box *moof_New() { ISOM_DECL_BOX_ALLOC(GF_MovieFragmentBox, GF_ISOM_BOX_TYPE_MOOF); tmp->TrackList = gf_list_new(); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err moof_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; //Header First if (ptr->mfhd) { e = gf_isom_box_write((GF_Box *) ptr->mfhd, bs); if (e) return e; } //then the track list return gf_isom_box_array_write(s, ptr->TrackList, bs); } GF_Err moof_Size(GF_Box *s) { GF_Err e; GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s; if (ptr->mfhd) { e = gf_isom_box_size((GF_Box *)ptr->mfhd); if (e) return e; ptr->size += ptr->mfhd->size; } return gf_isom_box_array_size(s, ptr->TrackList); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void moov_del(GF_Box *s) { GF_MovieBox *ptr = (GF_MovieBox *)s; if (ptr == NULL) return; if (ptr->mvhd) gf_isom_box_del((GF_Box *)ptr->mvhd); if (ptr->meta) gf_isom_box_del((GF_Box *)ptr->meta); if (ptr->iods) gf_isom_box_del((GF_Box *)ptr->iods); if (ptr->udta) gf_isom_box_del((GF_Box *)ptr->udta); #ifndef GPAC_DISABLE_ISOM_FRAGMENTS if (ptr->mvex) gf_isom_box_del((GF_Box *)ptr->mvex); #endif gf_isom_box_array_del(ptr->trackList); gf_free(ptr); } GF_Err moov_AddBox(GF_Box *s, GF_Box *a) { GF_MovieBox *ptr = (GF_MovieBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_IODS: if (ptr->iods) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->iods = (GF_ObjectDescriptorBox *)a; //if no IOD, delete the box if (!ptr->iods->descriptor) { ptr->iods = NULL; gf_isom_box_del(a); } return GF_OK; case GF_ISOM_BOX_TYPE_MVHD: if (ptr->mvhd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mvhd = (GF_MovieHeaderBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_UDTA: if (ptr->udta) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->udta = (GF_UserDataBox *)a; return GF_OK; #ifndef GPAC_DISABLE_ISOM_FRAGMENTS case GF_ISOM_BOX_TYPE_MVEX: if (ptr->mvex) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mvex = (GF_MovieExtendsBox *)a; ptr->mvex->mov = ptr->mov; return GF_OK; #endif case GF_ISOM_BOX_TYPE_META: if (ptr->meta) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->meta = (GF_MetaBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_TRAK: //set our pointer to this obj ((GF_TrackBox *)a)->moov = ptr; return gf_list_add(ptr->trackList, a); case GF_ISOM_BOX_TYPE_PSSH: default: return gf_isom_box_add_default(s, a); } } GF_Err moov_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; e = gf_isom_box_array_read(s, bs, moov_AddBox); if (e) { return e; } else { if (!((GF_MovieBox *)s)->mvhd) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MovieHeaderBox\n")); return GF_ISOM_INVALID_FILE; } } return e; } GF_Box *moov_New() { ISOM_DECL_BOX_ALLOC(GF_MovieBox, GF_ISOM_BOX_TYPE_MOOV); tmp->trackList = gf_list_new(); if (!tmp->trackList) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err moov_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieBox *ptr = (GF_MovieBox *)s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->mvhd) { e = gf_isom_box_write((GF_Box *) ptr->mvhd, bs); if (e) return e; } if (ptr->iods) { e = gf_isom_box_write((GF_Box *) ptr->iods, bs); if (e) return e; } if (ptr->meta) { e = gf_isom_box_write((GF_Box *) ptr->meta, bs); if (e) return e; } #ifndef GPAC_DISABLE_ISOM_FRAGMENTS if (ptr->mvex) { e = gf_isom_box_write((GF_Box *) ptr->mvex, bs); if (e) return e; } #endif e = gf_isom_box_array_write(s, ptr->trackList, bs); if (e) return e; if (ptr->udta) { e = gf_isom_box_write((GF_Box *) ptr->udta, bs); if (e) return e; } return GF_OK; } GF_Err moov_Size(GF_Box *s) { GF_Err e; GF_MovieBox *ptr = (GF_MovieBox *)s; if (ptr->mvhd) { e = gf_isom_box_size((GF_Box *) ptr->mvhd); if (e) return e; ptr->size += ptr->mvhd->size; } if (ptr->iods) { e = gf_isom_box_size((GF_Box *) ptr->iods); if (e) return e; ptr->size += ptr->iods->size; } if (ptr->udta) { e = gf_isom_box_size((GF_Box *) ptr->udta); if (e) return e; ptr->size += ptr->udta->size; } if (ptr->meta) { e = gf_isom_box_size((GF_Box *) ptr->meta); if (e) return e; ptr->size += ptr->meta->size; } #ifndef GPAC_DISABLE_ISOM_FRAGMENTS if (ptr->mvex) { e = gf_isom_box_size((GF_Box *) ptr->mvex); if (e) return e; ptr->size += ptr->mvex->size; } #endif return gf_isom_box_array_size(s, ptr->trackList); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void audio_sample_entry_del(GF_Box *s) { GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s; if (ptr == NULL) return; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s); if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd); if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc); if (ptr->cfg_ac3) gf_isom_box_del((GF_Box *)ptr->cfg_ac3); if (ptr->cfg_3gpp) gf_isom_box_del((GF_Box *)ptr->cfg_3gpp); gf_free(ptr); } GF_Err audio_sample_entry_AddBox(GF_Box *s, GF_Box *a) { GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_ESDS: if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->esd = (GF_ESDBox *)a; break; case GF_ISOM_BOX_TYPE_SINF: gf_list_add(ptr->protections, a); break; case GF_ISOM_BOX_TYPE_DAMR: case GF_ISOM_BOX_TYPE_DEVC: case GF_ISOM_BOX_TYPE_DQCP: case GF_ISOM_BOX_TYPE_DSMV: ptr->cfg_3gpp = (GF_3GPPConfigBox *) a; /*for 3GP config, remember sample entry type in config*/ ptr->cfg_3gpp->cfg.type = ptr->type; break; case GF_ISOM_BOX_TYPE_DAC3: ptr->cfg_ac3 = (GF_AC3ConfigBox *) a; break; case GF_ISOM_BOX_TYPE_DEC3: ptr->cfg_ac3 = (GF_AC3ConfigBox *) a; break; case GF_ISOM_BOX_TYPE_UNKNOWN: if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr) /*HACK for QT files: get the esds box from the track*/ { GF_UnknownBox *wave = (GF_UnknownBox *)a; //wave subboxes may have been properly parsed if ((wave->original_4cc == GF_ISOM_BOX_TYPE_WAVE) && gf_list_count(wave->other_boxes)) { u32 i; for (i =0; i<gf_list_count(wave->other_boxes); i++) { GF_Box *inner_box = (GF_Box *)gf_list_get(wave->other_boxes, i); if (inner_box->type == GF_ISOM_BOX_TYPE_ESDS) { ptr->esd = (GF_ESDBox *)inner_box; } } return gf_isom_box_add_default(s, a); } //unknown fomat, look for 'es' (esds) and try to parse box else if (wave->data != NULL) { u32 offset = 0; while ((wave->data[offset + 4] != 'e') && (wave->data[offset + 5] != 's')) { offset++; if (offset == wave->dataSize) break; } if (offset < wave->dataSize) { GF_Box *a; GF_Err e; GF_BitStream *bs = gf_bs_new(wave->data + offset, wave->dataSize - offset, GF_BITSTREAM_READ); e = gf_isom_box_parse(&a, bs); gf_bs_del(bs); if (e) return e; ptr->esd = (GF_ESDBox *)a; gf_isom_box_add_for_dump_mode((GF_Box *)ptr, a); } GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Cannot process box %s!\n", gf_4cc_to_str(wave->original_4cc))); return gf_isom_box_add_default(s, a); } gf_isom_box_del(a); return GF_ISOM_INVALID_MEDIA; } break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs) { GF_MPEGAudioSampleEntryBox *ptr; char *data; u32 i, size; GF_Err e; u64 pos; e = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs); if (e) return e; pos = gf_bs_get_position(bs); size = (u32) s->size; e = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox); if (!e) return GF_OK; if (size<8) return GF_ISOM_INVALID_FILE; /*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/ ptr = (GF_MPEGAudioSampleEntryBox *)s; gf_bs_seek(bs, pos); data = (char*)gf_malloc(sizeof(char) * size); gf_bs_read_data(bs, data, size); for (i=0; i<size-8; i++) { if (GF_4CC(data[i+4], data[i+5], data[i+6], data[i+7]) == GF_ISOM_BOX_TYPE_ESDS) { GF_BitStream *mybs = gf_bs_new(data + i, size - i, GF_BITSTREAM_READ); e = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs); gf_bs_del(mybs); break; } } gf_free(data); return e; } GF_Box *audio_sample_entry_New() { ISOM_DECL_BOX_ALLOC(GF_MPEGAudioSampleEntryBox, GF_ISOM_BOX_TYPE_MP4A); gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*)tmp); return (GF_Box *)tmp; } GF_Box *enca_New() { ISOM_DECL_BOX_ALLOC(GF_MPEGAudioSampleEntryBox, GF_ISOM_BOX_TYPE_ENCA); gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*)tmp); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err audio_sample_entry_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_isom_audio_sample_entry_write((GF_AudioSampleEntryBox*)s, bs); if (ptr->esd) { e = gf_isom_box_write((GF_Box *)ptr->esd, bs); if (e) return e; } if (ptr->cfg_3gpp) { e = gf_isom_box_write((GF_Box *)ptr->cfg_3gpp, bs); if (e) return e; } if (ptr->cfg_ac3) { e = gf_isom_box_write((GF_Box *)ptr->cfg_ac3, bs); if (e) return e; } return gf_isom_box_array_write(s, ptr->protections, bs); } GF_Err audio_sample_entry_Size(GF_Box *s) { GF_Err e; GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s; gf_isom_audio_sample_entry_size((GF_AudioSampleEntryBox*)s); if (ptr->esd) { e = gf_isom_box_size((GF_Box *)ptr->esd); if (e) return e; ptr->size += ptr->esd->size; } if (ptr->cfg_3gpp) { e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp); if (e) return e; ptr->size += ptr->cfg_3gpp->size; } if (ptr->cfg_ac3) { e = gf_isom_box_size((GF_Box *)ptr->cfg_ac3); if (e) return e; ptr->size += ptr->cfg_ac3->size; } return gf_isom_box_array_size(s, ptr->protections); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void mp4s_del(GF_Box *s) { GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s; if (ptr == NULL) return; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s); if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd); if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc); gf_free(ptr); } GF_Err mp4s_AddBox(GF_Box *s, GF_Box *a) { GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_ESDS: if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->esd = (GF_ESDBox *)a; break; case GF_ISOM_BOX_TYPE_SINF: gf_list_add(ptr->protections, a); break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err mp4s_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s; e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs); if (e) return e; ISOM_DECREASE_SIZE(ptr, 8); return gf_isom_box_array_read(s, bs, mp4s_AddBox); } GF_Box *mp4s_New() { ISOM_DECL_BOX_ALLOC(GF_MPEGSampleEntryBox, GF_ISOM_BOX_TYPE_MP4S); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); return (GF_Box *)tmp; } GF_Box *encs_New() { ISOM_DECL_BOX_ALLOC(GF_MPEGSampleEntryBox, GF_ISOM_BOX_TYPE_ENCS); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mp4s_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->reserved, 6); gf_bs_write_u16(bs, ptr->dataReferenceIndex); e = gf_isom_box_write((GF_Box *)ptr->esd, bs); if (e) return e; return gf_isom_box_array_write(s, ptr->protections, bs); } GF_Err mp4s_Size(GF_Box *s) { GF_Err e; GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s; ptr->size += 8; e = gf_isom_box_size((GF_Box *)ptr->esd); if (e) return e; ptr->size += ptr->esd->size; return gf_isom_box_array_size(s, ptr->protections); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void video_sample_entry_del(GF_Box *s) { GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; if (ptr == NULL) return; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s); if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd); if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc); /*for publishing*/ if (ptr->emul_esd) gf_odf_desc_del((GF_Descriptor *)ptr->emul_esd); if (ptr->avc_config) gf_isom_box_del((GF_Box *) ptr->avc_config); if (ptr->svc_config) gf_isom_box_del((GF_Box *) ptr->svc_config); if (ptr->mvc_config) gf_isom_box_del((GF_Box *) ptr->mvc_config); if (ptr->hevc_config) gf_isom_box_del((GF_Box *) ptr->hevc_config); if (ptr->lhvc_config) gf_isom_box_del((GF_Box *) ptr->lhvc_config); if (ptr->cfg_3gpp) gf_isom_box_del((GF_Box *)ptr->cfg_3gpp); if (ptr->descr) gf_isom_box_del((GF_Box *) ptr->descr); if (ptr->ipod_ext) gf_isom_box_del((GF_Box *)ptr->ipod_ext); if (ptr->pasp) gf_isom_box_del((GF_Box *)ptr->pasp); if (ptr->clap) gf_isom_box_del((GF_Box *)ptr->clap); if (ptr->rinf) gf_isom_box_del((GF_Box *)ptr->rinf); if (ptr->rvcc) gf_isom_box_del((GF_Box *)ptr->rvcc); gf_free(ptr); } GF_Err video_sample_entry_AddBox(GF_Box *s, GF_Box *a) { GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_ESDS: if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->esd = (GF_ESDBox *)a; break; case GF_ISOM_BOX_TYPE_SINF: gf_list_add(ptr->protections, a); break; case GF_ISOM_BOX_TYPE_RINF: if (ptr->rinf) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->rinf = (GF_RestrictedSchemeInfoBox *) a; break; case GF_ISOM_BOX_TYPE_AVCC: if (ptr->avc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->avc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_HVCC: if (ptr->hevc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->hevc_config = (GF_HEVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_SVCC: if (ptr->svc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->svc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_MVCC: if (ptr->mvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->mvc_config = (GF_AVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_LHVC: if (ptr->lhvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->lhvc_config = (GF_HEVCConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_M4DS: if (ptr->descr) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->descr = (GF_MPEG4ExtensionDescriptorsBox *)a; break; case GF_ISOM_BOX_TYPE_UUID: if (! memcmp(((GF_UnknownUUIDBox*)a)->uuid, GF_ISOM_IPOD_EXT, 16)) { if (ptr->ipod_ext) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->ipod_ext = (GF_UnknownUUIDBox *)a; } else { return gf_isom_box_add_default(s, a); } break; case GF_ISOM_BOX_TYPE_D263: ptr->cfg_3gpp = (GF_3GPPConfigBox *)a; /*for 3GP config, remember sample entry type in config*/ ptr->cfg_3gpp->cfg.type = ptr->type; break; break; case GF_ISOM_BOX_TYPE_PASP: if (ptr->pasp) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->pasp = (GF_PixelAspectRatioBox *)a; break; case GF_ISOM_BOX_TYPE_CLAP: if (ptr->clap) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->clap = (GF_CleanAppertureBox *)a; break; case GF_ISOM_BOX_TYPE_RVCC: if (ptr->rvcc) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->rvcc = (GF_RVCConfigurationBox *)a; break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err video_sample_entry_Read(GF_Box *s, GF_BitStream *bs) { GF_MPEGVisualSampleEntryBox *mp4v = (GF_MPEGVisualSampleEntryBox*)s; GF_Err e; e = gf_isom_video_sample_entry_read((GF_VisualSampleEntryBox *)s, bs); if (e) return e; e = gf_isom_box_array_read(s, bs, video_sample_entry_AddBox); if (e) return e; /*this is an AVC sample desc*/ if (mp4v->avc_config || mp4v->svc_config || mp4v->mvc_config) AVC_RewriteESDescriptor(mp4v); /*this is an HEVC sample desc*/ if (mp4v->hevc_config || mp4v->lhvc_config || (mp4v->type==GF_ISOM_BOX_TYPE_HVT1)) HEVC_RewriteESDescriptor(mp4v); return GF_OK; } GF_Box *video_sample_entry_New() { GF_MPEGVisualSampleEntryBox *tmp; GF_SAFEALLOC(tmp, GF_MPEGVisualSampleEntryBox); if (tmp == NULL) return NULL; gf_isom_video_sample_entry_init((GF_VisualSampleEntryBox *)tmp); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err video_sample_entry_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_isom_video_sample_entry_write((GF_VisualSampleEntryBox *)s, bs); /*mp4v*/ if (ptr->esd) { e = gf_isom_box_write((GF_Box *)ptr->esd, bs); if (e) return e; } /*mp4v*/ else if (ptr->cfg_3gpp) { e = gf_isom_box_write((GF_Box *)ptr->cfg_3gpp, bs); if (e) return e; } /*avc or hevc*/ else { if (ptr->avc_config && ptr->avc_config->config) { e = gf_isom_box_write((GF_Box *) ptr->avc_config, bs); if (e) return e; } if (ptr->hevc_config && ptr->hevc_config->config) { e = gf_isom_box_write((GF_Box *) ptr->hevc_config, bs); if (e) return e; } if (ptr->ipod_ext) { e = gf_isom_box_write((GF_Box *) ptr->ipod_ext, bs); if (e) return e; } if (ptr->descr) { e = gf_isom_box_write((GF_Box *) ptr->descr, bs); if (e) return e; } if (ptr->svc_config && ptr->svc_config->config) { e = gf_isom_box_write((GF_Box *) ptr->svc_config, bs); if (e) return e; } if (ptr->mvc_config && ptr->mvc_config->config) { e = gf_isom_box_write((GF_Box *) ptr->mvc_config, bs); if (e) return e; } if (ptr->lhvc_config && ptr->lhvc_config->config) { e = gf_isom_box_write((GF_Box *) ptr->lhvc_config, bs); if (e) return e; } } if (ptr->pasp) { e = gf_isom_box_write((GF_Box *)ptr->pasp, bs); if (e) return e; } if (ptr->clap) { e = gf_isom_box_write((GF_Box *)ptr->clap, bs); if (e) return e; } if (ptr->rvcc) { e = gf_isom_box_write((GF_Box *)ptr->rvcc, bs); if (e) return e; } if (ptr->rinf) { e = gf_isom_box_write((GF_Box *)ptr->rinf, bs); if (e) return e; } return gf_isom_box_array_write(s, ptr->protections, bs); } GF_Err video_sample_entry_Size(GF_Box *s) { GF_Err e; GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s); if (ptr->esd) { e = gf_isom_box_size((GF_Box *)ptr->esd); if (e) return e; ptr->size += ptr->esd->size; } else if (ptr->cfg_3gpp) { e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp); if (e) return e; ptr->size += ptr->cfg_3gpp->size; } else { if (!ptr->avc_config && !ptr->svc_config && !ptr->hevc_config && !ptr->lhvc_config && (ptr->type!=GF_ISOM_BOX_TYPE_HVT1) ) { return GF_ISOM_INVALID_FILE; } if (ptr->hevc_config && ptr->hevc_config->config) { e = gf_isom_box_size((GF_Box *)ptr->hevc_config); if (e) return e; ptr->size += ptr->hevc_config->size; } if (ptr->avc_config && ptr->avc_config->config) { e = gf_isom_box_size((GF_Box *) ptr->avc_config); if (e) return e; ptr->size += ptr->avc_config->size; } if (ptr->svc_config && ptr->svc_config->config) { e = gf_isom_box_size((GF_Box *) ptr->svc_config); if (e) return e; ptr->size += ptr->svc_config->size; } if (ptr->mvc_config && ptr->mvc_config->config) { e = gf_isom_box_size((GF_Box *) ptr->mvc_config); if (e) return e; ptr->size += ptr->mvc_config->size; } if (ptr->lhvc_config && ptr->lhvc_config->config) { e = gf_isom_box_size((GF_Box *) ptr->lhvc_config); if (e) return e; ptr->size += ptr->lhvc_config->size; } if (ptr->ipod_ext) { e = gf_isom_box_size((GF_Box *) ptr->ipod_ext); if (e) return e; ptr->size += ptr->ipod_ext->size; } if (ptr->descr) { e = gf_isom_box_size((GF_Box *) ptr->descr); if (e) return e; ptr->size += ptr->descr->size; } } if (ptr->pasp) { e = gf_isom_box_size((GF_Box *)ptr->pasp); if (e) return e; ptr->size += ptr->pasp->size; } if (ptr->clap) { e = gf_isom_box_size((GF_Box *)ptr->clap); if (e) return e; ptr->size += ptr->clap->size; } if (ptr->rvcc) { e = gf_isom_box_size((GF_Box *)ptr->rvcc); if (e) return e; ptr->size += ptr->rvcc->size; } if (ptr->rinf) { e = gf_isom_box_size((GF_Box *)ptr->rinf); if (e) return e; ptr->size += ptr->rinf->size; } return gf_isom_box_array_size(s, ptr->protections); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void mvex_del(GF_Box *s) { GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s; if (ptr == NULL) return; if (ptr->mehd) gf_isom_box_del((GF_Box*)ptr->mehd); gf_isom_box_array_del(ptr->TrackExList); gf_isom_box_array_del(ptr->TrackExPropList); gf_free(ptr); } GF_Err mvex_AddBox(GF_Box *s, GF_Box *a) { GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_TREX: return gf_list_add(ptr->TrackExList, a); case GF_ISOM_BOX_TYPE_TREP: return gf_list_add(ptr->TrackExPropList, a); case GF_ISOM_BOX_TYPE_MEHD: if (ptr->mehd) break; ptr->mehd = (GF_MovieExtendsHeaderBox*)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err mvex_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, mvex_AddBox); } GF_Box *mvex_New() { ISOM_DECL_BOX_ALLOC(GF_MovieExtendsBox, GF_ISOM_BOX_TYPE_MVEX); tmp->TrackExList = gf_list_new(); if (!tmp->TrackExList) { gf_free(tmp); return NULL; } tmp->TrackExPropList = gf_list_new(); if (!tmp->TrackExPropList) { gf_list_del(tmp->TrackExList); gf_free(tmp); return NULL; } return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mvex_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->mehd) { e = gf_isom_box_write((GF_Box *)ptr->mehd, bs); if (e) return e; } e = gf_isom_box_array_write(s, ptr->TrackExList, bs); if (e) return e; return gf_isom_box_array_write(s, ptr->TrackExPropList, bs); } GF_Err mvex_Size(GF_Box *s) { GF_Err e; GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s; if (ptr->mehd) { e = gf_isom_box_size((GF_Box *)ptr->mehd); if (e) return e; ptr->size += ptr->mehd->size; } e = gf_isom_box_array_size(s, ptr->TrackExList); if (e) return e; return gf_isom_box_array_size(s, ptr->TrackExPropList); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *mehd_New() { ISOM_DECL_BOX_ALLOC(GF_MovieExtendsHeaderBox, GF_ISOM_BOX_TYPE_MEHD); return (GF_Box *)tmp; } void mehd_del(GF_Box *s) { gf_free(s); } GF_Err mehd_Read(GF_Box *s, GF_BitStream *bs) { GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s; if (ptr->version==1) { ptr->fragment_duration = gf_bs_read_u64(bs); } else { ptr->fragment_duration = (u64) gf_bs_read_u32(bs); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mehd_Write(GF_Box *s, GF_BitStream *bs) { GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s; GF_Err e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->version == 1) { gf_bs_write_u64(bs, ptr->fragment_duration); } else { gf_bs_write_u32(bs, (u32) ptr->fragment_duration); } return GF_OK; } GF_Err mehd_Size(GF_Box *s) { GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s; ptr->version = (ptr->fragment_duration>0xFFFFFFFF) ? 1 : 0; s->size += (ptr->version == 1) ? 8 : 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void mvhd_del(GF_Box *s) { GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err mvhd_Read(GF_Box *s, GF_BitStream *bs) { GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s; if (ptr == NULL) return GF_BAD_PARAM; if (ptr->version == 1) { ptr->creationTime = gf_bs_read_u64(bs); ptr->modificationTime = gf_bs_read_u64(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u64(bs); } else { ptr->creationTime = gf_bs_read_u32(bs); ptr->modificationTime = gf_bs_read_u32(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u32(bs); } if (!ptr->timeScale) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Movie header timescale is invalid (0) - defaulting to 600\n" )); ptr->timeScale = 600; } ptr->preferredRate = gf_bs_read_u32(bs); ptr->preferredVolume = gf_bs_read_u16(bs); gf_bs_read_data(bs, ptr->reserved, 10); ptr->matrixA = gf_bs_read_u32(bs); ptr->matrixB = gf_bs_read_u32(bs); ptr->matrixU = gf_bs_read_u32(bs); ptr->matrixC = gf_bs_read_u32(bs); ptr->matrixD = gf_bs_read_u32(bs); ptr->matrixV = gf_bs_read_u32(bs); ptr->matrixX = gf_bs_read_u32(bs); ptr->matrixY = gf_bs_read_u32(bs); ptr->matrixW = gf_bs_read_u32(bs); ptr->previewTime = gf_bs_read_u32(bs); ptr->previewDuration = gf_bs_read_u32(bs); ptr->posterTime = gf_bs_read_u32(bs); ptr->selectionTime = gf_bs_read_u32(bs); ptr->selectionDuration = gf_bs_read_u32(bs); ptr->currentTime = gf_bs_read_u32(bs); ptr->nextTrackID = gf_bs_read_u32(bs); ptr->original_duration = ptr->duration; return GF_OK; } GF_Box *mvhd_New() { ISOM_DECL_BOX_ALLOC(GF_MovieHeaderBox, GF_ISOM_BOX_TYPE_MVHD); tmp->preferredRate = (1<<16); tmp->preferredVolume = (1<<8); tmp->matrixA = (1<<16); tmp->matrixD = (1<<16); tmp->matrixW = (1<<30); tmp->nextTrackID = 1; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err mvhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->version == 1) { gf_bs_write_u64(bs, ptr->creationTime); gf_bs_write_u64(bs, ptr->modificationTime); gf_bs_write_u32(bs, ptr->timeScale); gf_bs_write_u64(bs, ptr->duration); } else { gf_bs_write_u32(bs, (u32) ptr->creationTime); gf_bs_write_u32(bs, (u32) ptr->modificationTime); gf_bs_write_u32(bs, ptr->timeScale); gf_bs_write_u32(bs, (u32) ptr->duration); } gf_bs_write_u32(bs, ptr->preferredRate); gf_bs_write_u16(bs, ptr->preferredVolume); gf_bs_write_data(bs, ptr->reserved, 10); gf_bs_write_u32(bs, ptr->matrixA); gf_bs_write_u32(bs, ptr->matrixB); gf_bs_write_u32(bs, ptr->matrixU); gf_bs_write_u32(bs, ptr->matrixC); gf_bs_write_u32(bs, ptr->matrixD); gf_bs_write_u32(bs, ptr->matrixV); gf_bs_write_u32(bs, ptr->matrixX); gf_bs_write_u32(bs, ptr->matrixY); gf_bs_write_u32(bs, ptr->matrixW); gf_bs_write_u32(bs, ptr->previewTime); gf_bs_write_u32(bs, ptr->previewDuration); gf_bs_write_u32(bs, ptr->posterTime); gf_bs_write_u32(bs, ptr->selectionTime); gf_bs_write_u32(bs, ptr->selectionDuration); gf_bs_write_u32(bs, ptr->currentTime); gf_bs_write_u32(bs, ptr->nextTrackID); return GF_OK; } GF_Err mvhd_Size(GF_Box *s) { GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s; if (ptr->duration==(u64) -1) ptr->version = 0; else ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0; ptr->size += (ptr->version == 1) ? 28 : 16; ptr->size += 80; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void nmhd_del(GF_Box *s) { GF_MPEGMediaHeaderBox *ptr = (GF_MPEGMediaHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err nmhd_Read(GF_Box *s, GF_BitStream *bs) { return GF_OK; } GF_Box *nmhd_New() { ISOM_DECL_BOX_ALLOC(GF_MPEGMediaHeaderBox, GF_ISOM_BOX_TYPE_NMHD); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err nmhd_Write(GF_Box *s, GF_BitStream *bs) { return gf_isom_full_box_write(s, bs); } GF_Err nmhd_Size(GF_Box *s) { return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void padb_del(GF_Box *s) { GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *) s; if (ptr == NULL) return; if (ptr->padbits) gf_free(ptr->padbits); gf_free(ptr); } GF_Err padb_Read(GF_Box *s,GF_BitStream *bs) { u32 i; GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *)s; ptr->SampleCount = gf_bs_read_u32(bs); ptr->padbits = (u8 *)gf_malloc(sizeof(u8)*ptr->SampleCount); for (i=0; i<ptr->SampleCount; i += 2) { gf_bs_read_int(bs, 1); if (i+1 < ptr->SampleCount) { ptr->padbits[i+1] = gf_bs_read_int(bs, 3); } else { gf_bs_read_int(bs, 3); } gf_bs_read_int(bs, 1); ptr->padbits[i] = gf_bs_read_int(bs, 3); } return GF_OK; } GF_Box *padb_New() { ISOM_DECL_BOX_ALLOC(GF_PaddingBitsBox, GF_ISOM_BOX_TYPE_PADB); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err padb_Write(GF_Box *s, GF_BitStream *bs) { u32 i; GF_Err e; GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->SampleCount, 32); for (i=0 ; i<ptr->SampleCount; i += 2) { gf_bs_write_int(bs, 0, 1); if (i+1 < ptr->SampleCount) { gf_bs_write_int(bs, ptr->padbits[i+1], 3); } else { gf_bs_write_int(bs, 0, 3); } gf_bs_write_int(bs, 0, 1); gf_bs_write_int(bs, ptr->padbits[i], 3); } return GF_OK; } GF_Err padb_Size(GF_Box *s) { GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *)s; ptr->size += 4; if (ptr->SampleCount) ptr->size += (ptr->SampleCount + 1) / 2; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void rely_del(GF_Box *s) { GF_RelyHintBox *rely = (GF_RelyHintBox *)s; gf_free(rely); } GF_Err rely_Read(GF_Box *s, GF_BitStream *bs) { GF_RelyHintBox *ptr = (GF_RelyHintBox *)s; ptr->reserved = gf_bs_read_int(bs, 6); ptr->prefered = gf_bs_read_int(bs, 1); ptr->required = gf_bs_read_int(bs, 1); return GF_OK; } GF_Box *rely_New() { ISOM_DECL_BOX_ALLOC(GF_RelyHintBox, GF_ISOM_BOX_TYPE_RELY); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err rely_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_RelyHintBox *ptr = (GF_RelyHintBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->reserved, 6); gf_bs_write_int(bs, ptr->prefered, 1); gf_bs_write_int(bs, ptr->required, 1); return GF_OK; } GF_Err rely_Size(GF_Box *s) { s->size += 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void rtpo_del(GF_Box *s) { GF_RTPOBox *rtpo = (GF_RTPOBox *)s; gf_free(rtpo); } GF_Err rtpo_Read(GF_Box *s, GF_BitStream *bs) { GF_RTPOBox *ptr = (GF_RTPOBox *)s; ptr->timeOffset = gf_bs_read_u32(bs); return GF_OK; } GF_Box *rtpo_New() { ISOM_DECL_BOX_ALLOC(GF_RTPOBox, GF_ISOM_BOX_TYPE_RTPO); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err rtpo_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_RTPOBox *ptr = (GF_RTPOBox *)s; if (ptr == NULL) return GF_BAD_PARAM; //here we have no pb, just remembed that some entries will have to //be 4-bytes aligned ... e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->timeOffset); return GF_OK; } GF_Err rtpo_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void smhd_del(GF_Box *s) { GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s; if (ptr == NULL ) return; gf_free(ptr); } GF_Err smhd_Read(GF_Box *s, GF_BitStream *bs) { GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s; ptr->balance = gf_bs_read_u16(bs); ptr->reserved = gf_bs_read_u16(bs); return GF_OK; } GF_Box *smhd_New() { ISOM_DECL_BOX_ALLOC(GF_SoundMediaHeaderBox, GF_ISOM_BOX_TYPE_SMHD); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err smhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->balance); gf_bs_write_u16(bs, ptr->reserved); return GF_OK; } GF_Err smhd_Size(GF_Box *s) { GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s; ptr->reserved = 0; ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void snro_del(GF_Box *s) { GF_SeqOffHintEntryBox *snro = (GF_SeqOffHintEntryBox *)s; gf_free(snro); } GF_Err snro_Read(GF_Box *s, GF_BitStream *bs) { GF_SeqOffHintEntryBox *ptr = (GF_SeqOffHintEntryBox *)s; ptr->SeqOffset = gf_bs_read_u32(bs); return GF_OK; } GF_Box *snro_New() { ISOM_DECL_BOX_ALLOC(GF_SeqOffHintEntryBox, GF_ISOM_BOX_TYPE_SNRO); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err snro_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SeqOffHintEntryBox *ptr = (GF_SeqOffHintEntryBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->SeqOffset); return GF_OK; } GF_Err snro_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #define WRITE_SAMPLE_FRAGMENTS 1 void stbl_del(GF_Box *s) { GF_SampleTableBox *ptr = (GF_SampleTableBox *)s; if (ptr == NULL) return; if (ptr->ChunkOffset) gf_isom_box_del(ptr->ChunkOffset); if (ptr->CompositionOffset) gf_isom_box_del((GF_Box *) ptr->CompositionOffset); if (ptr->CompositionToDecode) gf_isom_box_del((GF_Box *) ptr->CompositionToDecode); if (ptr->DegradationPriority) gf_isom_box_del((GF_Box *) ptr->DegradationPriority); if (ptr->SampleDescription) gf_isom_box_del((GF_Box *) ptr->SampleDescription); if (ptr->SampleSize) gf_isom_box_del((GF_Box *) ptr->SampleSize); if (ptr->SampleToChunk) gf_isom_box_del((GF_Box *) ptr->SampleToChunk); if (ptr->ShadowSync) gf_isom_box_del((GF_Box *) ptr->ShadowSync); if (ptr->SyncSample) gf_isom_box_del((GF_Box *) ptr->SyncSample); if (ptr->TimeToSample) gf_isom_box_del((GF_Box *) ptr->TimeToSample); if (ptr->SampleDep) gf_isom_box_del((GF_Box *) ptr->SampleDep); if (ptr->PaddingBits) gf_isom_box_del((GF_Box *) ptr->PaddingBits); if (ptr->Fragments) gf_isom_box_del((GF_Box *) ptr->Fragments); if (ptr->sub_samples) gf_isom_box_array_del(ptr->sub_samples); if (ptr->sampleGroups) gf_isom_box_array_del(ptr->sampleGroups); if (ptr->sampleGroupsDescription) gf_isom_box_array_del(ptr->sampleGroupsDescription); if (ptr->sai_sizes) gf_isom_box_array_del(ptr->sai_sizes); if (ptr->sai_offsets) gf_isom_box_array_del(ptr->sai_offsets); gf_free(ptr); } GF_Err stbl_AddBox(GF_Box *s, GF_Box *a) { GF_SampleTableBox *ptr = (GF_SampleTableBox *)s; if (!a) return GF_OK; switch (a->type) { case GF_ISOM_BOX_TYPE_STTS: if (ptr->TimeToSample) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->TimeToSample = (GF_TimeToSampleBox *)a; break; case GF_ISOM_BOX_TYPE_CTTS: if (ptr->CompositionOffset) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->CompositionOffset = (GF_CompositionOffsetBox *)a; break; case GF_ISOM_BOX_TYPE_CSLG: if (ptr->CompositionToDecode) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->CompositionToDecode = (GF_CompositionToDecodeBox *)a; break; case GF_ISOM_BOX_TYPE_STSS: if (ptr->SyncSample) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->SyncSample = (GF_SyncSampleBox *)a; break; case GF_ISOM_BOX_TYPE_STSD: if (ptr->SampleDescription) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->SampleDescription =(GF_SampleDescriptionBox *)a; break; case GF_ISOM_BOX_TYPE_STZ2: case GF_ISOM_BOX_TYPE_STSZ: if (ptr->SampleSize) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->SampleSize = (GF_SampleSizeBox *)a; break; case GF_ISOM_BOX_TYPE_STSC: if (ptr->SampleToChunk) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->SampleToChunk = (GF_SampleToChunkBox *)a; break; case GF_ISOM_BOX_TYPE_PADB: if (ptr->PaddingBits) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->PaddingBits = (GF_PaddingBitsBox *) a; break; //WARNING: AS THIS MAY CHANGE DYNAMICALLY DURING EDIT, case GF_ISOM_BOX_TYPE_CO64: case GF_ISOM_BOX_TYPE_STCO: if (ptr->ChunkOffset) { gf_isom_box_del(ptr->ChunkOffset); } ptr->ChunkOffset = a; return GF_OK; case GF_ISOM_BOX_TYPE_STSH: if (ptr->ShadowSync) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->ShadowSync = (GF_ShadowSyncBox *)a; break; case GF_ISOM_BOX_TYPE_STDP: if (ptr->DegradationPriority) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->DegradationPriority = (GF_DegradationPriorityBox *)a; break; case GF_ISOM_BOX_TYPE_SDTP: if (ptr->SampleDep) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->SampleDep= (GF_SampleDependencyTypeBox *)a; break; case GF_ISOM_BOX_TYPE_STSF: if (ptr->Fragments) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->Fragments = (GF_SampleFragmentBox *)a; break; case GF_ISOM_BOX_TYPE_SUBS: if (!ptr->sub_samples) ptr->sub_samples = gf_list_new(); gf_list_add(ptr->sub_samples, a); //check subsample box { GF_SubSampleInformationBox *subs = (GF_SubSampleInformationBox *)a; GF_SubSampleInfoEntry *ent = gf_list_get(subs->Samples, 0); if (ent->sample_delta==0) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] first entry in SubSample in track SampleTable has sample_delta of 0, should be one. Fixing\n")); ent->sample_delta = 1; } } break; case GF_ISOM_BOX_TYPE_SBGP: if (!ptr->sampleGroups) ptr->sampleGroups = gf_list_new(); gf_list_add(ptr->sampleGroups, a); break; case GF_ISOM_BOX_TYPE_SGPD: if (!ptr->sampleGroupsDescription) ptr->sampleGroupsDescription = gf_list_new(); gf_list_add(ptr->sampleGroupsDescription, a); break; case GF_ISOM_BOX_TYPE_SAIZ: if (!ptr->sai_sizes) ptr->sai_sizes = gf_list_new(); gf_list_add(ptr->sai_sizes, a); break; case GF_ISOM_BOX_TYPE_SAIO: if (!ptr->sai_offsets) ptr->sai_offsets = gf_list_new(); gf_list_add(ptr->sai_offsets, a); break; default: return gf_isom_box_add_default((GF_Box *)ptr, a); } return GF_OK; } GF_Err stbl_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; //we need to parse DegPrior in a special way GF_SampleTableBox *ptr = (GF_SampleTableBox *)s; e = gf_isom_box_array_read(s, bs, stbl_AddBox); if (e) return e; if (!ptr->SyncSample) ptr->no_sync_found = 1; ptr->nb_sgpd_in_stbl = gf_list_count(ptr->sampleGroupsDescription); ptr->nb_other_boxes_in_stbl = gf_list_count(ptr->other_boxes); return GF_OK; } GF_Box *stbl_New() { ISOM_DECL_BOX_ALLOC(GF_SampleTableBox, GF_ISOM_BOX_TYPE_STBL); //maxSamplePer chunk is 10 by default tmp->MaxSamplePerChunk = 10; tmp->groupID = 1; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stbl_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SampleTableBox *ptr = (GF_SampleTableBox *)s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->SampleDescription) { e = gf_isom_box_write((GF_Box *) ptr->SampleDescription, bs); if (e) return e; } if (ptr->TimeToSample) { e = gf_isom_box_write((GF_Box *) ptr->TimeToSample, bs); if (e) return e; } if (ptr->CompositionOffset) { e = gf_isom_box_write((GF_Box *) ptr->CompositionOffset, bs); if (e) return e; } if (ptr->CompositionToDecode) { e = gf_isom_box_write((GF_Box *) ptr->CompositionToDecode, bs); if (e) return e; } if (ptr->SyncSample) { e = gf_isom_box_write((GF_Box *) ptr->SyncSample, bs); if (e) return e; } if (ptr->ShadowSync) { e = gf_isom_box_write((GF_Box *) ptr->ShadowSync, bs); if (e) return e; } if (ptr->SampleToChunk) { e = gf_isom_box_write((GF_Box *) ptr->SampleToChunk, bs); if (e) return e; } if (ptr->SampleSize) { e = gf_isom_box_write((GF_Box *) ptr->SampleSize, bs); if (e) return e; } if (ptr->ChunkOffset) { e = gf_isom_box_write(ptr->ChunkOffset, bs); if (e) return e; } if (ptr->DegradationPriority) { e = gf_isom_box_write((GF_Box *) ptr->DegradationPriority, bs); if (e) return e; } if (ptr->SampleDep && ptr->SampleDep->sampleCount) { e = gf_isom_box_write((GF_Box *) ptr->SampleDep, bs); if (e) return e; } if (ptr->PaddingBits) { e = gf_isom_box_write((GF_Box *) ptr->PaddingBits, bs); if (e) return e; } if (ptr->sub_samples) { e = gf_isom_box_array_write(s, ptr->sub_samples, bs); if (e) return e; } if (ptr->sampleGroupsDescription) { e = gf_isom_box_array_write(s, ptr->sampleGroupsDescription, bs); if (e) return e; } if (ptr->sampleGroups) { e = gf_isom_box_array_write(s, ptr->sampleGroups, bs); if (e) return e; } if (ptr->sai_sizes) { e = gf_isom_box_array_write(s, ptr->sai_sizes, bs); if (e) return e; } if (ptr->sai_offsets) { e = gf_isom_box_array_write(s, ptr->sai_offsets, bs); if (e) return e; } #if WRITE_SAMPLE_FRAGMENTS //sampleFragments if (ptr->Fragments) { e = gf_isom_box_write((GF_Box *) ptr->Fragments, bs); if (e) return e; } #endif return GF_OK; } GF_Err stbl_Size(GF_Box *s) { GF_Err e; GF_SampleTableBox *ptr = (GF_SampleTableBox *)s; //Mandatory boxs (but not internally :) if (ptr->SampleDescription) { e = gf_isom_box_size((GF_Box *) ptr->SampleDescription); if (e) return e; ptr->size += ptr->SampleDescription->size; } if (ptr->SampleSize) { e = gf_isom_box_size((GF_Box *) ptr->SampleSize); if (e) return e; ptr->size += ptr->SampleSize->size; } if (ptr->SampleToChunk) { e = gf_isom_box_size((GF_Box *) ptr->SampleToChunk); if (e) return e; ptr->size += ptr->SampleToChunk->size; } if (ptr->TimeToSample) { e = gf_isom_box_size((GF_Box *) ptr->TimeToSample); if (e) return e; ptr->size += ptr->TimeToSample->size; } if (ptr->ChunkOffset) { e = gf_isom_box_size(ptr->ChunkOffset); if (e) return e; ptr->size += ptr->ChunkOffset->size; } //optional boxs if (ptr->CompositionOffset) { e = gf_isom_box_size((GF_Box *) ptr->CompositionOffset); if (e) return e; ptr->size += ptr->CompositionOffset->size; } if (ptr->CompositionToDecode) { e = gf_isom_box_size((GF_Box *) ptr->CompositionToDecode); if (e) return e; ptr->size += ptr->CompositionToDecode->size; } if (ptr->DegradationPriority) { e = gf_isom_box_size((GF_Box *) ptr->DegradationPriority); if (e) return e; ptr->size += ptr->DegradationPriority->size; } if (ptr->ShadowSync) { e = gf_isom_box_size((GF_Box *) ptr->ShadowSync); if (e) return e; ptr->size += ptr->ShadowSync->size; } if (ptr->SyncSample) { e = gf_isom_box_size((GF_Box *) ptr->SyncSample); if (e) return e; ptr->size += ptr->SyncSample->size; } if (ptr->SampleDep && ptr->SampleDep->sampleCount) { e = gf_isom_box_size((GF_Box *) ptr->SampleDep); if (e) return e; ptr->size += ptr->SampleDep->size; } //padb if (ptr->PaddingBits) { e = gf_isom_box_size((GF_Box *) ptr->PaddingBits); if (e) return e; ptr->size += ptr->PaddingBits->size; } #if WRITE_SAMPLE_FRAGMENTS //sample fragments if (ptr->Fragments) { e = gf_isom_box_size((GF_Box *) ptr->Fragments); if (e) return e; ptr->size += ptr->Fragments->size; } #endif if (ptr->sub_samples) { e = gf_isom_box_array_size(s, ptr->sub_samples); if (e) return e; } if (ptr->sampleGroups) { e = gf_isom_box_array_size(s, ptr->sampleGroups); if (e) return e; } if (ptr->sampleGroupsDescription) { e = gf_isom_box_array_size(s, ptr->sampleGroupsDescription); if (e) return e; } if (ptr->sai_sizes) { e = gf_isom_box_array_size(s, ptr->sai_sizes); if (e) return e; } if (ptr->sai_offsets) { e = gf_isom_box_array_size(s, ptr->sai_offsets); if (e) return e; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stco_del(GF_Box *s) { GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s; if (ptr == NULL) return; if (ptr->offsets) gf_free(ptr->offsets); gf_free(ptr); } GF_Err stco_Read(GF_Box *s, GF_BitStream *bs) { u32 entries; GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s; ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->nb_entries > ptr->size / 4) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stco\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } if (ptr->nb_entries) { ptr->offsets = (u32 *) gf_malloc(ptr->nb_entries * sizeof(u32) ); if (ptr->offsets == NULL) return GF_OUT_OF_MEM; ptr->alloc_size = ptr->nb_entries; for (entries = 0; entries < ptr->nb_entries; entries++) { ptr->offsets[entries] = gf_bs_read_u32(bs); } } return GF_OK; } GF_Box *stco_New() { ISOM_DECL_BOX_ALLOC(GF_ChunkOffsetBox, GF_ISOM_BOX_TYPE_STCO); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stco_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i = 0; i < ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->offsets[i]); } return GF_OK; } GF_Err stco_Size(GF_Box *s) { GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s; ptr->size += 4 + (4 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stdp_del(GF_Box *s) { GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s; if (ptr == NULL ) return; if (ptr->priorities) gf_free(ptr->priorities); gf_free(ptr); } //this is called through stbl_read... GF_Err stdp_Read(GF_Box *s, GF_BitStream *bs) { u32 entry; GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s; /*out-of-order stdp, assume no padding at the end and take the entire remaining data for entries*/ if (!ptr->nb_entries) ptr->nb_entries = (u32) ptr->size / 2; else if (ptr->nb_entries > ptr->size / 2) return GF_ISOM_INVALID_FILE; ptr->priorities = (u16 *) gf_malloc(ptr->nb_entries * sizeof(u16)); if (ptr->priorities == NULL) return GF_OUT_OF_MEM; for (entry = 0; entry < ptr->nb_entries; entry++) { ptr->priorities[entry] = gf_bs_read_u16(bs); } ISOM_DECREASE_SIZE(ptr, (2*ptr->nb_entries) ); return GF_OK; } GF_Box *stdp_New() { ISOM_DECL_BOX_ALLOC(GF_DegradationPriorityBox, GF_ISOM_BOX_TYPE_STDP); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stdp_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; for (i = 0; i < ptr->nb_entries; i++) { gf_bs_write_u16(bs, ptr->priorities[i]); } return GF_OK; } GF_Err stdp_Size(GF_Box *s) { GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s; ptr->size += (2 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsc_del(GF_Box *s) { GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s; if (ptr == NULL) return; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err stsc_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s; ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->nb_entries > ptr->size / 12) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsc\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } ptr->alloc_size = ptr->nb_entries; ptr->entries = gf_malloc(sizeof(GF_StscEntry)*ptr->alloc_size); if (!ptr->entries) return GF_OUT_OF_MEM; for (i = 0; i < ptr->nb_entries; i++) { ptr->entries[i].firstChunk = gf_bs_read_u32(bs); ptr->entries[i].samplesPerChunk = gf_bs_read_u32(bs); ptr->entries[i].sampleDescriptionIndex = gf_bs_read_u32(bs); ptr->entries[i].isEdited = 0; ptr->entries[i].nextChunk = 0; if (!ptr->entries[i].firstChunk) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] invalid first chunk 0 in stsc entry\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } //update the next chunk in the previous entry if (i) ptr->entries[i-1].nextChunk = ptr->entries[i].firstChunk; } ptr->currentIndex = 0; ptr->firstSampleInCurrentChunk = 0; ptr->currentChunk = 0; ptr->ghostNumber = 0; return GF_OK; } GF_Box *stsc_New() { ISOM_DECL_BOX_ALLOC(GF_SampleToChunkBox, GF_ISOM_BOX_TYPE_STSC); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsc_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->entries[i].firstChunk); gf_bs_write_u32(bs, ptr->entries[i].samplesPerChunk); gf_bs_write_u32(bs, ptr->entries[i].sampleDescriptionIndex); } return GF_OK; } GF_Err stsc_Size(GF_Box *s) { GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s; ptr->size += 4 + (12 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsd_del(GF_Box *s) { GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err stsd_AddBox(GF_Box *s, GF_Box *a) { GF_UnknownBox *def; GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s; if (!a) return GF_OK; switch (a->type) { case GF_ISOM_BOX_TYPE_MP4S: case GF_ISOM_BOX_TYPE_ENCS: case GF_ISOM_BOX_TYPE_MP4A: case GF_ISOM_BOX_TYPE_ENCA: case GF_ISOM_BOX_TYPE_MP4V: case GF_ISOM_BOX_TYPE_ENCV: case GF_ISOM_BOX_TYPE_RESV: case GF_ISOM_BOX_TYPE_GHNT: case GF_ISOM_BOX_TYPE_RTP_STSD: case GF_ISOM_BOX_TYPE_SRTP_STSD: case GF_ISOM_BOX_TYPE_FDP_STSD: case GF_ISOM_BOX_TYPE_RRTP_STSD: case GF_ISOM_BOX_TYPE_RTCP_STSD: case GF_ISOM_BOX_TYPE_AVC1: case GF_ISOM_BOX_TYPE_AVC2: case GF_ISOM_BOX_TYPE_AVC3: case GF_ISOM_BOX_TYPE_AVC4: case GF_ISOM_BOX_TYPE_SVC1: case GF_ISOM_BOX_TYPE_MVC1: case GF_ISOM_BOX_TYPE_HVC1: case GF_ISOM_BOX_TYPE_HEV1: case GF_ISOM_BOX_TYPE_HVC2: case GF_ISOM_BOX_TYPE_HEV2: case GF_ISOM_BOX_TYPE_HVT1: case GF_ISOM_BOX_TYPE_LHV1: case GF_ISOM_BOX_TYPE_LHE1: case GF_ISOM_BOX_TYPE_TX3G: case GF_ISOM_BOX_TYPE_TEXT: case GF_ISOM_BOX_TYPE_ENCT: case GF_ISOM_BOX_TYPE_METX: case GF_ISOM_BOX_TYPE_METT: case GF_ISOM_BOX_TYPE_STXT: case GF_ISOM_BOX_TYPE_DIMS: case GF_ISOM_BOX_TYPE_AC3: case GF_ISOM_BOX_TYPE_EC3: case GF_ISOM_BOX_TYPE_LSR1: case GF_ISOM_BOX_TYPE_WVTT: case GF_ISOM_BOX_TYPE_STPP: case GF_ISOM_BOX_TYPE_SBTT: case GF_ISOM_BOX_TYPE_ELNG: case GF_ISOM_BOX_TYPE_MP3: case GF_ISOM_BOX_TYPE_JPEG: case GF_ISOM_BOX_TYPE_JP2K: case GF_ISOM_BOX_TYPE_PNG: case GF_ISOM_SUBTYPE_3GP_AMR: case GF_ISOM_SUBTYPE_3GP_AMR_WB: case GF_ISOM_SUBTYPE_3GP_EVRC: case GF_ISOM_SUBTYPE_3GP_QCELP: case GF_ISOM_SUBTYPE_3GP_SMV: case GF_ISOM_SUBTYPE_3GP_H263: return gf_isom_box_add_default((GF_Box*)ptr, a); //unknown sample description: we need a specific box to handle the data ref index //rather than a default box ... case GF_ISOM_BOX_TYPE_UNKNOWN: def = (GF_UnknownBox *)a; /*we need at least 8 bytes for unknown sample entries*/ if (def->dataSize < 8) { gf_isom_box_del(a); return GF_OK; } return gf_isom_box_add_default((GF_Box*)ptr, a); default: GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Cannot process box of type %s\n", gf_4cc_to_str(a->type))); return GF_ISOM_INVALID_FILE; } } GF_Err stsd_Read(GF_Box *s, GF_BitStream *bs) { gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(s, 4) return gf_isom_box_array_read_ex(s, bs, stsd_AddBox, GF_ISOM_BOX_TYPE_STSD); } GF_Box *stsd_New() { ISOM_DECL_BOX_ALLOC(GF_SampleDescriptionBox, GF_ISOM_BOX_TYPE_STSD); tmp->other_boxes = gf_list_new(); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 nb_entries; GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; nb_entries = gf_list_count(ptr->other_boxes); gf_bs_write_u32(bs, nb_entries); return GF_OK; } GF_Err stsd_Size(GF_Box *s) { GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s; ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsf_del(GF_Box *s) { u32 nb_entries; u32 i; GF_StsfEntry *pe; GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s; if (ptr == NULL) return; if (ptr->entryList) { nb_entries = gf_list_count(ptr->entryList); for ( i = 0; i < nb_entries; i++ ) { pe = (GF_StsfEntry*)gf_list_get(ptr->entryList, i); if (pe->fragmentSizes) gf_free(pe->fragmentSizes); gf_free(pe); } gf_list_del(ptr->entryList); } gf_free(ptr); } GF_Err stsf_Read(GF_Box *s, GF_BitStream *bs) { u32 entries, i; u32 nb_entries; GF_StsfEntry *p; GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s; p = NULL; if (!ptr) return GF_BAD_PARAM; nb_entries = gf_bs_read_u32(bs); p = NULL; for ( entries = 0; entries < nb_entries; entries++ ) { p = (GF_StsfEntry *) gf_malloc(sizeof(GF_StsfEntry)); if (!p) return GF_OUT_OF_MEM; p->SampleNumber = gf_bs_read_u32(bs); p->fragmentCount = gf_bs_read_u32(bs); p->fragmentSizes = (u16*)gf_malloc(sizeof(GF_StsfEntry) * p->fragmentCount); for (i=0; i<p->fragmentCount; i++) { p->fragmentSizes[i] = gf_bs_read_u16(bs); } gf_list_add(ptr->entryList, p); } #ifndef GPAC_DISABLE_ISOM_WRITE ptr->w_currentEntry = p; ptr->w_currentEntryIndex = nb_entries-1; #endif return GF_OK; } GF_Box *stsf_New() { ISOM_DECL_BOX_ALLOC(GF_SampleFragmentBox, GF_ISOM_BOX_TYPE_STSF); tmp->entryList = gf_list_new(); if (! tmp->entryList) { gf_free(tmp); return NULL; } return (GF_Box *) tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsf_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i, j; u32 nb_entries; GF_StsfEntry *p; GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; nb_entries = gf_list_count(ptr->entryList); gf_bs_write_u32(bs, nb_entries); for ( i = 0; i < nb_entries; i++ ) { p = (GF_StsfEntry*)gf_list_get(ptr->entryList, i); gf_bs_write_u32(bs, p->SampleNumber); gf_bs_write_u32(bs, p->fragmentCount); for (j=0; j<p->fragmentCount; j++) { gf_bs_write_u16(bs, p->fragmentSizes[j]); } } return GF_OK; } GF_Err stsf_Size(GF_Box *s) { GF_StsfEntry *p; u32 nb_entries, i; GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *) s; nb_entries = gf_list_count(ptr->entryList); ptr->size += 4; for (i=0; i<nb_entries; i++) { p = (GF_StsfEntry *)gf_list_get(ptr->entryList, i); ptr->size += 8 + 2*p->fragmentCount; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsh_del(GF_Box *s) { u32 i = 0; GF_StshEntry *ent; GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s; if (ptr == NULL) return; while ( (ent = (GF_StshEntry *)gf_list_enum(ptr->entries, &i)) ) { gf_free(ent); } gf_list_del(ptr->entries); gf_free(ptr); } GF_Err stsh_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 count, i; GF_StshEntry *ent; GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s; count = gf_bs_read_u32(bs); for (i = 0; i < count; i++) { ent = (GF_StshEntry *) gf_malloc(sizeof(GF_StshEntry)); if (!ent) return GF_OUT_OF_MEM; ent->shadowedSampleNumber = gf_bs_read_u32(bs); ent->syncSampleNumber = gf_bs_read_u32(bs); e = gf_list_add(ptr->entries, ent); if (e) return e; } return GF_OK; } GF_Box *stsh_New() { ISOM_DECL_BOX_ALLOC(GF_ShadowSyncBox, GF_ISOM_BOX_TYPE_STSH); tmp->entries = gf_list_new(); if (!tmp->entries) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsh_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_StshEntry *ent; GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, gf_list_count(ptr->entries)); i=0; while ((ent = (GF_StshEntry *)gf_list_enum(ptr->entries, &i))) { gf_bs_write_u32(bs, ent->shadowedSampleNumber); gf_bs_write_u32(bs, ent->syncSampleNumber); } return GF_OK; } GF_Err stsh_Size(GF_Box *s) { GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s; ptr->size += 4 + (8 * gf_list_count(ptr->entries)); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stss_del(GF_Box *s) { GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s; if (ptr == NULL) return; if (ptr->sampleNumbers) gf_free(ptr->sampleNumbers); gf_free(ptr); } GF_Err stss_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s; ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->nb_entries > ptr->size / 4) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stss\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } ptr->alloc_size = ptr->nb_entries; ptr->sampleNumbers = (u32 *) gf_malloc( ptr->alloc_size * sizeof(u32)); if (ptr->sampleNumbers == NULL) return GF_OUT_OF_MEM; for (i = 0; i < ptr->nb_entries; i++) { ptr->sampleNumbers[i] = gf_bs_read_u32(bs); } return GF_OK; } GF_Box *stss_New() { ISOM_DECL_BOX_ALLOC(GF_SyncSampleBox, GF_ISOM_BOX_TYPE_STSS); return (GF_Box*)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stss_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i = 0; i < ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->sampleNumbers[i]); } return GF_OK; } GF_Err stss_Size(GF_Box *s) { GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s; ptr->size += 4 + (4 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsz_del(GF_Box *s) { GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s; if (ptr == NULL) return; if (ptr->sizes) gf_free(ptr->sizes); gf_free(ptr); } GF_Err stsz_Read(GF_Box *s, GF_BitStream *bs) { u32 i, estSize; GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s; if (ptr == NULL) return GF_BAD_PARAM; //support for CompactSizes if (s->type == GF_ISOM_BOX_TYPE_STSZ) { ptr->sampleSize = gf_bs_read_u32(bs); ptr->sampleCount = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); } else { //24-reserved gf_bs_read_int(bs, 24); i = gf_bs_read_u8(bs); ptr->sampleCount = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); switch (i) { case 4: case 8: case 16: ptr->sampleSize = i; break; default: //try to fix the file //no samples, no parsing pb if (!ptr->sampleCount) { ptr->sampleSize = 16; return GF_OK; } estSize = (u32) (ptr->size) / ptr->sampleCount; if (!estSize && ((ptr->sampleCount+1)/2 == (ptr->size)) ) { ptr->sampleSize = 4; break; } else if (estSize == 1 || estSize == 2) { ptr->sampleSize = 8 * estSize; } else { return GF_ISOM_INVALID_FILE; } } } if (s->type == GF_ISOM_BOX_TYPE_STSZ) { if (! ptr->sampleSize && ptr->sampleCount) { if (ptr->sampleCount > ptr->size / 4) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount)); return GF_ISOM_INVALID_FILE; } ptr->sizes = (u32 *) gf_malloc(ptr->sampleCount * sizeof(u32)); ptr->alloc_size = ptr->sampleCount; if (! ptr->sizes) return GF_OUT_OF_MEM; for (i = 0; i < ptr->sampleCount; i++) { ptr->sizes[i] = gf_bs_read_u32(bs); } } } else { if (ptr->sampleSize==4) { if (ptr->sampleCount / 2 > ptr->size) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount)); return GF_ISOM_INVALID_FILE; } } else { if (ptr->sampleCount > ptr->size / (ptr->sampleSize/8)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount)); return GF_ISOM_INVALID_FILE; } } //note we could optimize the mem usage by keeping the table compact //in memory. But that would complicate both caching and editing //we therefore keep all sizes as u32 and uncompress the table ptr->sizes = (u32 *) gf_malloc(ptr->sampleCount * sizeof(u32)); if (! ptr->sizes) return GF_OUT_OF_MEM; ptr->alloc_size = ptr->sampleCount; for (i = 0; i < ptr->sampleCount; ) { switch (ptr->sampleSize) { case 4: ptr->sizes[i] = gf_bs_read_int(bs, 4); if (i+1 < ptr->sampleCount) { ptr->sizes[i+1] = gf_bs_read_int(bs, 4); } else { //0 padding in odd sample count gf_bs_read_int(bs, 4); } i += 2; break; default: ptr->sizes[i] = gf_bs_read_int(bs, ptr->sampleSize); i += 1; break; } } } return GF_OK; } GF_Box *stsz_New() { ISOM_DECL_BOX_ALLOC(GF_SampleSizeBox, 0); //type is unknown here, can be regular or compact table return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsz_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; //in both versions this is still valid if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) { gf_bs_write_u32(bs, ptr->sampleSize); } else { gf_bs_write_u24(bs, 0); gf_bs_write_u8(bs, ptr->sampleSize); } gf_bs_write_u32(bs, ptr->sampleCount); if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) { if (! ptr->sampleSize) { for (i = 0; i < ptr->sampleCount; i++) { gf_bs_write_u32(bs, ptr->sizes ? ptr->sizes[i] : 0); } } } else { for (i = 0; i < ptr->sampleCount; ) { switch (ptr->sampleSize) { case 4: gf_bs_write_int(bs, ptr->sizes[i], 4); if (i+1 < ptr->sampleCount) { gf_bs_write_int(bs, ptr->sizes[i+1], 4); } else { //0 padding in odd sample count gf_bs_write_int(bs, 0, 4); } i += 2; break; default: gf_bs_write_int(bs, ptr->sizes[i], ptr->sampleSize); i += 1; break; } } } return GF_OK; } GF_Err stsz_Size(GF_Box *s) { u32 i, fieldSize, size; GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s; ptr->size += 8; if (!ptr->sampleCount) return GF_OK; //regular table if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) { if (ptr->sampleSize) return GF_OK; ptr->size += (4 * ptr->sampleCount); return GF_OK; } fieldSize = 4; size = ptr->sizes[0]; for (i=0; i < ptr->sampleCount; i++) { if (ptr->sizes[i] <= 0xF) continue; //switch to 8-bit table else if (ptr->sizes[i] <= 0xFF) { fieldSize = 8; } //switch to 16-bit table else if (ptr->sizes[i] <= 0xFFFF) { fieldSize = 16; } //switch to 32-bit table else { fieldSize = 32; } //check the size if (size != ptr->sizes[i]) size = 0; } //if all samples are of the same size, switch to regular (more compact) if (size) { ptr->type = GF_ISOM_BOX_TYPE_STSZ; ptr->sampleSize = size; gf_free(ptr->sizes); ptr->sizes = NULL; } if (fieldSize == 32) { //oops, doesn't fit in a compact table ptr->type = GF_ISOM_BOX_TYPE_STSZ; ptr->size += (4 * ptr->sampleCount); return GF_OK; } //make sure we are a compact table (no need to change the mem representation) ptr->type = GF_ISOM_BOX_TYPE_STZ2; ptr->sampleSize = fieldSize; if (fieldSize == 4) { //do not forget the 0 padding field for odd count ptr->size += (ptr->sampleCount + 1) / 2; } else { ptr->size += (ptr->sampleCount) * (fieldSize/8); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stts_del(GF_Box *s) { GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err stts_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s; #ifndef GPAC_DISABLE_ISOM_WRITE ptr->w_LastDTS = 0; #endif ptr->nb_entries = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->nb_entries > ptr->size / 8) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stts\n", ptr->nb_entries)); return GF_ISOM_INVALID_FILE; } ptr->alloc_size = ptr->nb_entries; ptr->entries = gf_malloc(sizeof(GF_SttsEntry)*ptr->alloc_size); if (!ptr->entries) return GF_OUT_OF_MEM; for (i=0; i<ptr->nb_entries; i++) { ptr->entries[i].sampleCount = gf_bs_read_u32(bs); ptr->entries[i].sampleDelta = gf_bs_read_u32(bs); #ifndef GPAC_DISABLE_ISOM_WRITE ptr->w_currentSampleNum += ptr->entries[i].sampleCount; ptr->w_LastDTS += (u64)ptr->entries[i].sampleCount * ptr->entries[i].sampleDelta; #endif if (!ptr->entries[i].sampleDelta) { if ((i+1<ptr->nb_entries) ) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Found stts entry with sample_delta=0 - forbidden ! Fixing to 1\n" )); ptr->entries[i].sampleDelta = 1; } else if (ptr->entries[i].sampleCount>1) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] more than one stts entry at the end of the track with sample_delta=0 - forbidden ! Fixing to 1\n" )); ptr->entries[i].sampleDelta = 1; } } else if ((s32) ptr->entries[i].sampleDelta < 0) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] stts entry %d has negative duration %d - forbidden ! Fixing to 1, sync may get lost (consider reimport raw media)\n", i, (s32) ptr->entries[i].sampleDelta )); ptr->entries[i].sampleDelta = 1; } } if (ptr->size<(ptr->nb_entries*8)) return GF_ISOM_INVALID_FILE; ISOM_DECREASE_SIZE(ptr, ptr->nb_entries*8); //remove the last sample delta. #ifndef GPAC_DISABLE_ISOM_WRITE if (ptr->nb_entries) ptr->w_LastDTS -= ptr->entries[ptr->nb_entries-1].sampleDelta; #endif return GF_OK; } GF_Box *stts_New() { ISOM_DECL_BOX_ALLOC(GF_TimeToSampleBox, GF_ISOM_BOX_TYPE_STTS); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stts_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->entries[i].sampleCount); gf_bs_write_u32(bs, ptr->entries[i].sampleDelta); } return GF_OK; } GF_Err stts_Size(GF_Box *s) { GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s; ptr->size += 4 + (8 * ptr->nb_entries); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void tfhd_del(GF_Box *s) { GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err tfhd_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s; ptr->trackID = gf_bs_read_u32(bs); //The rest depends on the flags if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) { ptr->base_data_offset = gf_bs_read_u64(bs); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) { ptr->sample_desc_index = gf_bs_read_u32(bs); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) { ptr->def_sample_duration = gf_bs_read_u32(bs); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) { ptr->def_sample_size = gf_bs_read_u32(bs); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) { ptr->def_sample_flags = gf_bs_read_u32(bs); } return GF_OK; } GF_Box *tfhd_New() { ISOM_DECL_BOX_ALLOC(GF_TrackFragmentHeaderBox, GF_ISOM_BOX_TYPE_TFHD); //NO FLAGS SET BY DEFAULT return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tfhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->trackID); //The rest depends on the flags if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) { gf_bs_write_u64(bs, ptr->base_data_offset); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) { gf_bs_write_u32(bs, ptr->sample_desc_index); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) { gf_bs_write_u32(bs, ptr->def_sample_duration); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) { gf_bs_write_u32(bs, ptr->def_sample_size); } if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) { gf_bs_write_u32(bs, ptr->def_sample_flags); } return GF_OK; } GF_Err tfhd_Size(GF_Box *s) { GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s; ptr->size += 4; //The rest depends on the flags if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) ptr->size += 8; if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) ptr->size += 4; if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) ptr->size += 4; if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ptr->size += 4; if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void tims_del(GF_Box *s) { GF_TSHintEntryBox *tims = (GF_TSHintEntryBox *)s; gf_free(tims); } GF_Err tims_Read(GF_Box *s, GF_BitStream *bs) { GF_TSHintEntryBox *ptr = (GF_TSHintEntryBox *)s; ptr->timeScale = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tims_New() { ISOM_DECL_BOX_ALLOC(GF_TSHintEntryBox, GF_ISOM_BOX_TYPE_TIMS); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tims_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TSHintEntryBox *ptr = (GF_TSHintEntryBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->timeScale); return GF_OK; } GF_Err tims_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void tkhd_del(GF_Box *s) { GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); return; } GF_Err tkhd_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s; if (ptr->version == 1) { ptr->creationTime = gf_bs_read_u64(bs); ptr->modificationTime = gf_bs_read_u64(bs); ptr->trackID = gf_bs_read_u32(bs); ptr->reserved1 = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u64(bs); } else { ptr->creationTime = gf_bs_read_u32(bs); ptr->modificationTime = gf_bs_read_u32(bs); ptr->trackID = gf_bs_read_u32(bs); ptr->reserved1 = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u32(bs); } ptr->reserved2[0] = gf_bs_read_u32(bs); ptr->reserved2[1] = gf_bs_read_u32(bs); ptr->layer = gf_bs_read_u16(bs); ptr->alternate_group = gf_bs_read_u16(bs); ptr->volume = gf_bs_read_u16(bs); ptr->reserved3 = gf_bs_read_u16(bs); ptr->matrix[0] = gf_bs_read_u32(bs); ptr->matrix[1] = gf_bs_read_u32(bs); ptr->matrix[2] = gf_bs_read_u32(bs); ptr->matrix[3] = gf_bs_read_u32(bs); ptr->matrix[4] = gf_bs_read_u32(bs); ptr->matrix[5] = gf_bs_read_u32(bs); ptr->matrix[6] = gf_bs_read_u32(bs); ptr->matrix[7] = gf_bs_read_u32(bs); ptr->matrix[8] = gf_bs_read_u32(bs); ptr->width = gf_bs_read_u32(bs); ptr->height = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tkhd_New() { ISOM_DECL_BOX_ALLOC(GF_TrackHeaderBox, GF_ISOM_BOX_TYPE_TKHD); tmp->matrix[0] = 0x00010000; tmp->matrix[4] = 0x00010000; tmp->matrix[8] = 0x40000000; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tkhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->version == 1) { gf_bs_write_u64(bs, ptr->creationTime); gf_bs_write_u64(bs, ptr->modificationTime); gf_bs_write_u32(bs, ptr->trackID); gf_bs_write_u32(bs, ptr->reserved1); gf_bs_write_u64(bs, ptr->duration); } else { gf_bs_write_u32(bs, (u32) ptr->creationTime); gf_bs_write_u32(bs, (u32) ptr->modificationTime); gf_bs_write_u32(bs, ptr->trackID); gf_bs_write_u32(bs, ptr->reserved1); gf_bs_write_u32(bs, (u32) ptr->duration); } gf_bs_write_u32(bs, ptr->reserved2[0]); gf_bs_write_u32(bs, ptr->reserved2[1]); gf_bs_write_u16(bs, ptr->layer); gf_bs_write_u16(bs, ptr->alternate_group); gf_bs_write_u16(bs, ptr->volume); gf_bs_write_u16(bs, ptr->reserved3); gf_bs_write_u32(bs, ptr->matrix[0]); gf_bs_write_u32(bs, ptr->matrix[1]); gf_bs_write_u32(bs, ptr->matrix[2]); gf_bs_write_u32(bs, ptr->matrix[3]); gf_bs_write_u32(bs, ptr->matrix[4]); gf_bs_write_u32(bs, ptr->matrix[5]); gf_bs_write_u32(bs, ptr->matrix[6]); gf_bs_write_u32(bs, ptr->matrix[7]); gf_bs_write_u32(bs, ptr->matrix[8]); gf_bs_write_u32(bs, ptr->width); gf_bs_write_u32(bs, ptr->height); return GF_OK; } GF_Err tkhd_Size(GF_Box *s) { GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s; if (ptr->duration==(u64) -1) ptr->version = 0; else ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0; ptr->size += (ptr->version == 1) ? 32 : 20; ptr->size += 60; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void traf_del(GF_Box *s) { GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s; if (ptr == NULL) return; if (ptr->tfhd) gf_isom_box_del((GF_Box *) ptr->tfhd); if (ptr->sdtp) gf_isom_box_del((GF_Box *) ptr->sdtp); if (ptr->sub_samples) gf_isom_box_array_del(ptr->sub_samples); if (ptr->tfdt) gf_isom_box_del((GF_Box *) ptr->tfdt); if (ptr->sample_encryption) gf_isom_box_del((GF_Box *) ptr->sample_encryption); gf_isom_box_array_del(ptr->TrackRuns); if (ptr->sampleGroups) gf_isom_box_array_del(ptr->sampleGroups); if (ptr->sampleGroupsDescription) gf_isom_box_array_del(ptr->sampleGroupsDescription); if (ptr->sai_sizes) gf_isom_box_array_del(ptr->sai_sizes); if (ptr->sai_offsets) gf_isom_box_array_del(ptr->sai_offsets); gf_free(ptr); } GF_Err traf_AddBox(GF_Box *s, GF_Box *a) { GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_TFHD: if (ptr->tfhd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->tfhd = (GF_TrackFragmentHeaderBox *) a; return GF_OK; case GF_ISOM_BOX_TYPE_TRUN: return gf_list_add(ptr->TrackRuns, a); case GF_ISOM_BOX_TYPE_SDTP: if (ptr->sdtp) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->sdtp = (GF_SampleDependencyTypeBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_TFDT: if (ptr->tfdt) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->tfdt = (GF_TFBaseMediaDecodeTimeBox*) a; return GF_OK; case GF_ISOM_BOX_TYPE_SUBS: if (!ptr->sub_samples) ptr->sub_samples = gf_list_new(); return gf_list_add(ptr->sub_samples, a); case GF_ISOM_BOX_TYPE_SBGP: if (!ptr->sampleGroups) ptr->sampleGroups = gf_list_new(); gf_list_add(ptr->sampleGroups, a); return GF_OK; case GF_ISOM_BOX_TYPE_SGPD: if (!ptr->sampleGroupsDescription) ptr->sampleGroupsDescription = gf_list_new(); gf_list_add(ptr->sampleGroupsDescription, a); return GF_OK; case GF_ISOM_BOX_TYPE_SAIZ: if (!ptr->sai_sizes) ptr->sai_sizes = gf_list_new(); gf_list_add(ptr->sai_sizes, a); return GF_OK; case GF_ISOM_BOX_TYPE_SAIO: if (!ptr->sai_offsets) ptr->sai_offsets = gf_list_new(); gf_list_add(ptr->sai_offsets, a); return GF_OK; //we will throw an error if both PIFF_PSEC and SENC are found. Not such files seen yet case GF_ISOM_BOX_TYPE_UUID: if ( ((GF_UUIDBox *)a)->internal_4cc==GF_ISOM_BOX_UUID_PSEC) { if (ptr->sample_encryption) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->sample_encryption = (GF_SampleEncryptionBox *)a; ptr->sample_encryption->traf = ptr; return GF_OK; } else { return gf_isom_box_add_default(s, a); } case GF_ISOM_BOX_TYPE_SENC: if (ptr->sample_encryption) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->sample_encryption = (GF_SampleEncryptionBox *)a; ptr->sample_encryption->traf = ptr; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err traf_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s; GF_Err e = gf_isom_box_array_read(s, bs, traf_AddBox); if (e) return e; if (!ptr->tfhd) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing TrackFragmentHeaderBox \n")); return GF_ISOM_INVALID_FILE; } return GF_OK; } GF_Box *traf_New() { ISOM_DECL_BOX_ALLOC(GF_TrackFragmentBox, GF_ISOM_BOX_TYPE_TRAF); tmp->TrackRuns = gf_list_new(); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Box *tfxd_New() { ISOM_DECL_BOX_ALLOC(GF_MSSTimeExtBox, GF_ISOM_BOX_TYPE_UUID); tmp->internal_4cc = GF_ISOM_BOX_UUID_TFXD; return (GF_Box *)tmp; } void tfxd_del(GF_Box *s) { gf_free(s); } GF_Err tfxd_Read(GF_Box *s, GF_BitStream *bs) { GF_MSSTimeExtBox *ptr = (GF_MSSTimeExtBox *)s; if (ptr->size<4) return GF_ISOM_INVALID_FILE; ptr->version = gf_bs_read_u8(bs); ptr->flags = gf_bs_read_u24(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->version == 0x01) { ptr->absolute_time_in_track_timescale = gf_bs_read_u64(bs); ptr->fragment_duration_in_track_timescale = gf_bs_read_u64(bs); } else { ptr->absolute_time_in_track_timescale = gf_bs_read_u32(bs); ptr->fragment_duration_in_track_timescale = gf_bs_read_u32(bs); } return GF_OK; } GF_Err tfxd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e = GF_OK; GF_MSSTimeExtBox *uuid = (GF_MSSTimeExtBox*)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u8(bs, 1); gf_bs_write_u24(bs, 0); gf_bs_write_u64(bs, uuid->absolute_time_in_track_timescale); gf_bs_write_u64(bs, uuid->fragment_duration_in_track_timescale); return GF_OK; } GF_Err tfxd_Size(GF_Box *s) { s->size += 20; return GF_OK; } GF_Err traf_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; //Header first if (ptr->tfhd) { e = gf_isom_box_write((GF_Box *) ptr->tfhd, bs); if (e) return e; } if (ptr->sub_samples) { e = gf_isom_box_array_write(s, ptr->sub_samples, bs); if (e) return e; } if (ptr->tfdt) { e = gf_isom_box_write((GF_Box *) ptr->tfdt, bs); if (e) return e; } if (ptr->sdtp) { e = gf_isom_box_write((GF_Box *) ptr->sdtp, bs); if (e) return e; } if (ptr->sampleGroupsDescription) { e = gf_isom_box_array_write(s, ptr->sampleGroupsDescription, bs); if (e) return e; } if (ptr->sampleGroups) { e = gf_isom_box_array_write(s, ptr->sampleGroups, bs); if (e) return e; } if (ptr->sai_sizes) { e = gf_isom_box_array_write(s, ptr->sai_sizes, bs); if (e) return e; } if (ptr->sai_offsets) { e = gf_isom_box_array_write(s, ptr->sai_offsets, bs); if (e) return e; } e = gf_isom_box_array_write(s, ptr->TrackRuns, bs); if (e) return e; if (ptr->sample_encryption) { e = gf_isom_box_write((GF_Box *) ptr->sample_encryption, bs); if (e) return e; } //tfxd should be last ... if (ptr->tfxd) { e = gf_isom_box_write((GF_Box *) ptr->tfxd, bs); if (e) return e; } return GF_OK; } GF_Err traf_Size(GF_Box *s) { GF_Err e; GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s; if (ptr->tfhd) { e = gf_isom_box_size((GF_Box *) ptr->tfhd); if (e) return e; ptr->size += ptr->tfhd->size; } if (ptr->sub_samples) { e = gf_isom_box_array_size(s, ptr->sub_samples); if (e) return e; } if (ptr->sdtp) { e = gf_isom_box_size((GF_Box *) ptr->sdtp); if (e) return e; ptr->size += ptr->sdtp->size; } if (ptr->tfdt) { e = gf_isom_box_size((GF_Box *) ptr->tfdt); if (e) return e; ptr->size += ptr->tfdt->size; } if (ptr->sampleGroups) { e = gf_isom_box_array_size(s, ptr->sampleGroups); if (e) return e; } if (ptr->sampleGroupsDescription) { e = gf_isom_box_array_size(s, ptr->sampleGroupsDescription); if (e) return e; } if (ptr->sai_sizes) { e = gf_isom_box_array_size(s, ptr->sai_sizes); if (e) return e; } if (ptr->sai_offsets) { e = gf_isom_box_array_size(s, ptr->sai_offsets); if (e) return e; } if (ptr->sample_encryption) { e = gf_isom_box_size((GF_Box *) ptr->sample_encryption); if (e) return e; ptr->size += ptr->sample_encryption->size; } if (ptr->tfxd) { e = gf_isom_box_size((GF_Box *)ptr->tfxd); if (e) return e; s->size += ptr->tfxd->size; } return gf_isom_box_array_size(s, ptr->TrackRuns); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void trak_del(GF_Box *s) { GF_TrackBox *ptr = (GF_TrackBox *) s; if (ptr == NULL) return; if (ptr->Header) gf_isom_box_del((GF_Box *)ptr->Header); if (ptr->udta) gf_isom_box_del((GF_Box *)ptr->udta); if (ptr->Media) gf_isom_box_del((GF_Box *)ptr->Media); if (ptr->References) gf_isom_box_del((GF_Box *)ptr->References); if (ptr->editBox) gf_isom_box_del((GF_Box *)ptr->editBox); if (ptr->meta) gf_isom_box_del((GF_Box *)ptr->meta); if (ptr->name) gf_free(ptr->name); if (ptr->groups) gf_isom_box_del((GF_Box *)ptr->groups); gf_free(ptr); } static void gf_isom_check_sample_desc(GF_TrackBox *trak) { GF_BitStream *bs; GF_UnknownBox *a; u32 i; if (!trak->Media || !trak->Media->information) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no media box !\n" )); return; } if (!trak->Media->information->sampleTable) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no sample table !\n" )); trak->Media->information->sampleTable = (GF_SampleTableBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STBL); } if (!trak->Media->information->sampleTable->SampleDescription) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no sample description box !\n" )); trak->Media->information->sampleTable->SampleDescription = (GF_SampleDescriptionBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STSD); return; } i=0; while ((a = (GF_UnknownBox*)gf_list_enum(trak->Media->information->sampleTable->SampleDescription->other_boxes, &i))) { switch (a->type) { case GF_ISOM_BOX_TYPE_MP4S: case GF_ISOM_BOX_TYPE_ENCS: case GF_ISOM_BOX_TYPE_MP4A: case GF_ISOM_BOX_TYPE_ENCA: case GF_ISOM_BOX_TYPE_MP4V: case GF_ISOM_BOX_TYPE_ENCV: case GF_ISOM_BOX_TYPE_RESV: case GF_ISOM_SUBTYPE_3GP_AMR: case GF_ISOM_SUBTYPE_3GP_AMR_WB: case GF_ISOM_SUBTYPE_3GP_EVRC: case GF_ISOM_SUBTYPE_3GP_QCELP: case GF_ISOM_SUBTYPE_3GP_SMV: case GF_ISOM_SUBTYPE_3GP_H263: case GF_ISOM_BOX_TYPE_GHNT: case GF_ISOM_BOX_TYPE_RTP_STSD: case GF_ISOM_BOX_TYPE_SRTP_STSD: case GF_ISOM_BOX_TYPE_FDP_STSD: case GF_ISOM_BOX_TYPE_RRTP_STSD: case GF_ISOM_BOX_TYPE_RTCP_STSD: case GF_ISOM_BOX_TYPE_METX: case GF_ISOM_BOX_TYPE_METT: case GF_ISOM_BOX_TYPE_STXT: case GF_ISOM_BOX_TYPE_AVC1: case GF_ISOM_BOX_TYPE_AVC2: case GF_ISOM_BOX_TYPE_AVC3: case GF_ISOM_BOX_TYPE_AVC4: case GF_ISOM_BOX_TYPE_SVC1: case GF_ISOM_BOX_TYPE_MVC1: case GF_ISOM_BOX_TYPE_HVC1: case GF_ISOM_BOX_TYPE_HEV1: case GF_ISOM_BOX_TYPE_HVC2: case GF_ISOM_BOX_TYPE_HEV2: case GF_ISOM_BOX_TYPE_HVT1: case GF_ISOM_BOX_TYPE_LHV1: case GF_ISOM_BOX_TYPE_LHE1: case GF_ISOM_BOX_TYPE_TX3G: case GF_ISOM_BOX_TYPE_TEXT: case GF_ISOM_BOX_TYPE_ENCT: case GF_ISOM_BOX_TYPE_DIMS: case GF_ISOM_BOX_TYPE_AC3: case GF_ISOM_BOX_TYPE_EC3: case GF_ISOM_BOX_TYPE_LSR1: case GF_ISOM_BOX_TYPE_WVTT: case GF_ISOM_BOX_TYPE_STPP: case GF_ISOM_BOX_TYPE_SBTT: case GF_ISOM_BOX_TYPE_MP3: case GF_ISOM_BOX_TYPE_JPEG: case GF_ISOM_BOX_TYPE_PNG: case GF_ISOM_BOX_TYPE_JP2K: continue; case GF_ISOM_BOX_TYPE_UNKNOWN: break; default: GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Unexpected box %s in stsd!\n", gf_4cc_to_str(a->type))); continue; } //we are sure to have an unknown box here assert(a->type==GF_ISOM_BOX_TYPE_UNKNOWN); if (!a->data || (a->dataSize<8) ) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Sample description %s does not have at least 8 bytes!\n", gf_4cc_to_str(a->original_4cc) )); continue; } else if (a->dataSize > a->size) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Sample description %s has wrong data size %d!\n", gf_4cc_to_str(a->original_4cc), a->dataSize)); continue; } /*only process visual or audio*/ switch (trak->Media->handler->handlerType) { case GF_ISOM_MEDIA_VISUAL: case GF_ISOM_MEDIA_AUXV: case GF_ISOM_MEDIA_PICT: { GF_GenericVisualSampleEntryBox *genv; /*remove entry*/ gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1); genv = (GF_GenericVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRV); bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ); genv->size = a->size-8; gf_isom_video_sample_entry_read((GF_VisualSampleEntryBox *) genv, bs); if (gf_bs_available(bs)) { u64 pos = gf_bs_get_position(bs); //try to parse as boxes GF_Err e = gf_isom_box_array_read((GF_Box *) genv, bs, gf_isom_box_add_default); if (e) { gf_bs_seek(bs, pos); genv->data_size = (u32) gf_bs_available(bs); if (genv->data_size) { genv->data = a->data; a->data = NULL; memmove(genv->data, genv->data + pos, genv->data_size); } } else { genv->data_size = 0; } } gf_bs_del(bs); if (!genv->data_size && genv->data) { gf_free(genv->data); genv->data = NULL; } genv->size = 0; genv->EntryType = a->original_4cc; gf_isom_box_del((GF_Box *)a); gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, genv, i-1); } break; case GF_ISOM_MEDIA_AUDIO: { GF_GenericAudioSampleEntryBox *gena; /*remove entry*/ gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1); gena = (GF_GenericAudioSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRA); gena->size = a->size-8; bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ); gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox *) gena, bs); if (gf_bs_available(bs)) { u64 pos = gf_bs_get_position(bs); //try to parse as boxes GF_Err e = gf_isom_box_array_read((GF_Box *) gena, bs, gf_isom_box_add_default); if (e) { gf_bs_seek(bs, pos); gena->data_size = (u32) gf_bs_available(bs); if (gena->data_size) { gena->data = a->data; a->data = NULL; memmove(gena->data, gena->data + pos, gena->data_size); } } else { gena->data_size = 0; } } gf_bs_del(bs); if (!gena->data_size && gena->data) { gf_free(gena->data); gena->data = NULL; } gena->size = 0; gena->EntryType = a->original_4cc; gf_isom_box_del((GF_Box *)a); gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, gena, i-1); } break; default: { GF_Err e; GF_GenericSampleEntryBox *genm; /*remove entry*/ gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1); genm = (GF_GenericSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRM); genm->size = a->size-8; bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ); e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)genm, bs); if (e) return; genm->size -= 8; if (gf_bs_available(bs)) { u64 pos = gf_bs_get_position(bs); //try to parse as boxes GF_Err e = gf_isom_box_array_read((GF_Box *) genm, bs, gf_isom_box_add_default); if (e) { gf_bs_seek(bs, pos); genm->data_size = (u32) gf_bs_available(bs); if (genm->data_size) { genm->data = a->data; a->data = NULL; memmove(genm->data, genm->data + pos, genm->data_size); } } else { genm->data_size = 0; } } gf_bs_del(bs); if (!genm->data_size && genm->data) { gf_free(genm->data); genm->data = NULL; } genm->size = 0; genm->EntryType = a->original_4cc; gf_isom_box_del((GF_Box *)a); gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, genm, i-1); } break; } } } GF_Err trak_AddBox(GF_Box *s, GF_Box *a) { GF_TrackBox *ptr = (GF_TrackBox *)s; if (!a) return GF_OK; switch(a->type) { case GF_ISOM_BOX_TYPE_TKHD: if (ptr->Header) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->Header = (GF_TrackHeaderBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_EDTS: if (ptr->editBox) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->editBox = (GF_EditBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_UDTA: if (ptr->udta) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->udta = (GF_UserDataBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_META: if (ptr->meta) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->meta = (GF_MetaBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_TREF: if (ptr->References) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->References = (GF_TrackReferenceBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_MDIA: if (ptr->Media) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->Media = (GF_MediaBox *)a; ((GF_MediaBox *)a)->mediaTrack = ptr; return GF_OK; case GF_ISOM_BOX_TYPE_TRGR: if (ptr->groups) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->groups = (GF_TrackGroupBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_SENC: ptr->sample_encryption = (GF_SampleEncryptionBox*)a; return gf_isom_box_add_default((GF_Box *)ptr, a); case GF_ISOM_BOX_TYPE_UUID: if (((GF_UnknownUUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC) { ptr->sample_encryption = (GF_SampleEncryptionBox*) a; return gf_isom_box_add_default((GF_Box *)ptr, a); } default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err trak_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_TrackBox *ptr = (GF_TrackBox *)s; e = gf_isom_box_array_read(s, bs, trak_AddBox); if (e) return e; gf_isom_check_sample_desc(ptr); if (!ptr->Header) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing TrackHeaderBox\n")); return GF_ISOM_INVALID_FILE; } if (!ptr->Media) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaBox\n")); return GF_ISOM_INVALID_FILE; } for (i=0; i<gf_list_count(ptr->Media->information->sampleTable->other_boxes); i++) { GF_Box *a = gf_list_get(ptr->Media->information->sampleTable->other_boxes, i); if ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) { ptr->sample_encryption = (struct __sample_encryption_box *) a; break; } else if (a->type == GF_ISOM_BOX_TYPE_SENC) { ptr->sample_encryption = (struct __sample_encryption_box *)a; break; } } return e; } GF_Box *trak_New() { ISOM_DECL_BOX_ALLOC(GF_TrackBox, GF_ISOM_BOX_TYPE_TRAK); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trak_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackBox *ptr = (GF_TrackBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->Header) { e = gf_isom_box_write((GF_Box *) ptr->Header, bs); if (e) return e; } if (ptr->References) { e = gf_isom_box_write((GF_Box *) ptr->References, bs); if (e) return e; } if (ptr->editBox) { e = gf_isom_box_write((GF_Box *) ptr->editBox, bs); if (e) return e; } if (ptr->Media) { e = gf_isom_box_write((GF_Box *) ptr->Media, bs); if (e) return e; } if (ptr->meta) { e = gf_isom_box_write((GF_Box *) ptr->meta, bs); if (e) return e; } if (ptr->groups) { e = gf_isom_box_write((GF_Box *) ptr->groups, bs); if (e) return e; } if (ptr->udta) { e = gf_isom_box_write((GF_Box *) ptr->udta, bs); if (e) return e; } return GF_OK; } GF_Err trak_Size(GF_Box *s) { GF_Err e; GF_TrackBox *ptr = (GF_TrackBox *)s; if (ptr->Header) { e = gf_isom_box_size((GF_Box *) ptr->Header); if (e) return e; ptr->size += ptr->Header->size; } if (ptr->udta) { e = gf_isom_box_size((GF_Box *) ptr->udta); if (e) return e; ptr->size += ptr->udta->size; } if (ptr->References) { e = gf_isom_box_size((GF_Box *) ptr->References); if (e) return e; ptr->size += ptr->References->size; } if (ptr->editBox) { e = gf_isom_box_size((GF_Box *) ptr->editBox); if (e) return e; ptr->size += ptr->editBox->size; } if (ptr->Media) { e = gf_isom_box_size((GF_Box *) ptr->Media); if (e) return e; ptr->size += ptr->Media->size; } if (ptr->meta) { e = gf_isom_box_size((GF_Box *) ptr->meta); if (e) return e; ptr->size += ptr->meta->size; } if (ptr->groups) { e = gf_isom_box_size((GF_Box *) ptr->groups); if (e) return e; ptr->size += ptr->groups->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stri_del(GF_Box *s) { GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s; if (ptr == NULL) return; if (ptr->attribute_list) gf_free(ptr->attribute_list); gf_free(ptr); } GF_Err stri_Read(GF_Box *s, GF_BitStream *bs) { size_t i; GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s; ptr->switch_group = gf_bs_read_u16(bs); ptr->alternate_group = gf_bs_read_u16(bs); ptr->sub_track_id = gf_bs_read_u32(bs); ptr->size -= 8; ptr->attribute_count = ptr->size / 4; GF_SAFE_ALLOC_N(ptr->attribute_list, (size_t)ptr->attribute_count, u32); if (!ptr->attribute_list) return GF_OUT_OF_MEM; for (i = 0; i < ptr->attribute_count; i++) { ptr->attribute_list[i] = gf_bs_read_u32(bs); } return GF_OK; } GF_Box *stri_New() { ISOM_DECL_BOX_ALLOC(GF_SubTrackInformationBox, GF_ISOM_BOX_TYPE_STRI); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stri_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->switch_group); gf_bs_write_u16(bs, ptr->alternate_group); gf_bs_write_u32(bs, ptr->sub_track_id); for (i = 0; i < ptr->attribute_count; i++) { gf_bs_write_u32(bs, ptr->attribute_list[i]); } return GF_OK; } GF_Err stri_Size(GF_Box *s) { GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s; ptr->size += 8 + 4 * ptr->attribute_count; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void stsg_del(GF_Box *s) { GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; if (ptr == NULL) return; if (ptr->group_description_index) gf_free(ptr->group_description_index); gf_free(ptr); } GF_Err stsg_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; ISOM_DECREASE_SIZE(s, 6); ptr->grouping_type = gf_bs_read_u32(bs); ptr->nb_groups = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(s, ptr->nb_groups*4); GF_SAFE_ALLOC_N(ptr->group_description_index, ptr->nb_groups, u32); if (!ptr->group_description_index) return GF_OUT_OF_MEM; for (i = 0; i < ptr->nb_groups; i++) { ptr->group_description_index[i] = gf_bs_read_u32(bs); } return GF_OK; } GF_Box *stsg_New() { ISOM_DECL_BOX_ALLOC(GF_SubTrackSampleGroupBox, GF_ISOM_BOX_TYPE_STSG); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stsg_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->grouping_type); gf_bs_write_u16(bs, ptr->nb_groups); for (i = 0; i < ptr->nb_groups; i++) { gf_bs_write_u32(bs, ptr->group_description_index[i]); } return GF_OK; } GF_Err stsg_Size(GF_Box *s) { GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; ptr->size += 6 + 4 * ptr->nb_groups; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void strk_del(GF_Box *s) { GF_SubTrackBox *ptr = (GF_SubTrackBox *)s; if (ptr == NULL) return; if (ptr->info) gf_isom_box_del((GF_Box *)ptr->info); gf_free(ptr); } GF_Err strk_AddBox(GF_Box *s, GF_Box *a) { GF_SubTrackBox *ptr = (GF_SubTrackBox *)s; if (!a) return GF_OK; switch (a->type) { case GF_ISOM_BOX_TYPE_STRI: if (ptr->info) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->info = (GF_SubTrackInformationBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_STRD: if (ptr->strd) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->strd = a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err strk_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SubTrackBox *ptr = (GF_SubTrackBox *)s; e = gf_isom_box_array_read(s, bs, strk_AddBox); if (e) return e; if (!ptr->info) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing SubTrackInformationBox\n")); return GF_ISOM_INVALID_FILE; } return e; } GF_Box *strk_New() { ISOM_DECL_BOX_ALLOC(GF_SubTrackBox, GF_ISOM_BOX_TYPE_STRK); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err strk_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SubTrackBox *ptr = (GF_SubTrackBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->info) { e = gf_isom_box_write((GF_Box *)ptr->info, bs); if (e) return e; } return GF_OK; } GF_Err strk_Size(GF_Box *s) { GF_Err e; GF_SubTrackBox *ptr = (GF_SubTrackBox *)s; if (ptr->info) { e = gf_isom_box_size((GF_Box *)ptr->info); if (e) return e; ptr->size += ptr->info->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Err tref_AddBox(GF_Box *ptr, GF_Box *a) { return gf_isom_box_add_default(ptr, a); } void tref_del(GF_Box *s) { GF_TrackReferenceBox *ptr = (GF_TrackReferenceBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err tref_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read_ex(s, bs, gf_isom_box_add_default, s->type); } GF_Box *tref_New() { ISOM_DECL_BOX_ALLOC(GF_TrackReferenceBox, GF_ISOM_BOX_TYPE_TREF); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tref_Write(GF_Box *s, GF_BitStream *bs) { // GF_TrackReferenceBox *ptr = (GF_TrackReferenceBox *)s; return gf_isom_box_write_header(s, bs); } GF_Err tref_Size(GF_Box *s) { return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void reftype_del(GF_Box *s) { GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s; if (!ptr) return; if (ptr->trackIDs) gf_free(ptr->trackIDs); gf_free(ptr); } GF_Err reftype_Read(GF_Box *s, GF_BitStream *bs) { u32 bytesToRead; u32 i; GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s; bytesToRead = (u32) (ptr->size); if (!bytesToRead) return GF_OK; ptr->trackIDCount = (u32) (bytesToRead) / sizeof(u32); ptr->trackIDs = (u32 *) gf_malloc(ptr->trackIDCount * sizeof(u32)); if (!ptr->trackIDs) return GF_OUT_OF_MEM; for (i = 0; i < ptr->trackIDCount; i++) { ptr->trackIDs[i] = gf_bs_read_u32(bs); } return GF_OK; } GF_Box *reftype_New() { ISOM_DECL_BOX_ALLOC(GF_TrackReferenceTypeBox, GF_ISOM_BOX_TYPE_REFT); return (GF_Box *)tmp; } GF_Err reftype_AddRefTrack(GF_TrackReferenceTypeBox *ref, u32 trackID, u16 *outRefIndex) { u32 i; if (!ref || !trackID) return GF_BAD_PARAM; if (outRefIndex) *outRefIndex = 0; //don't add a dep if already here !! for (i = 0; i < ref->trackIDCount; i++) { if (ref->trackIDs[i] == trackID) { if (outRefIndex) *outRefIndex = i+1; return GF_OK; } } ref->trackIDs = (u32 *) gf_realloc(ref->trackIDs, (ref->trackIDCount + 1) * sizeof(u32) ); if (!ref->trackIDs) return GF_OUT_OF_MEM; ref->trackIDs[ref->trackIDCount] = trackID; ref->trackIDCount++; if (outRefIndex) *outRefIndex = ref->trackIDCount; return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err reftype_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s; ptr->type = ptr->reference_type; if (!ptr->trackIDCount) return GF_OK; e = gf_isom_box_write_header(s, bs); ptr->type = GF_ISOM_BOX_TYPE_REFT; if (e) return e; for (i = 0; i < ptr->trackIDCount; i++) { gf_bs_write_u32(bs, ptr->trackIDs[i]); } return GF_OK; } GF_Err reftype_Size(GF_Box *s) { GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s; if (!ptr->trackIDCount) ptr->size=0; else ptr->size += (ptr->trackIDCount * sizeof(u32)); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void trex_del(GF_Box *s) { GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err trex_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s; ptr->trackID = gf_bs_read_u32(bs); ptr->def_sample_desc_index = gf_bs_read_u32(bs); ptr->def_sample_duration = gf_bs_read_u32(bs); ptr->def_sample_size = gf_bs_read_u32(bs); ptr->def_sample_flags = gf_bs_read_u32(bs); if (!ptr->def_sample_desc_index) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] TREX with default sample description set to 0, likely broken ! Fixing to 1\n" )); ptr->def_sample_desc_index = 1; } return GF_OK; } GF_Box *trex_New() { ISOM_DECL_BOX_ALLOC(GF_TrackExtendsBox, GF_ISOM_BOX_TYPE_TREX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trex_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->trackID); gf_bs_write_u32(bs, ptr->def_sample_desc_index); gf_bs_write_u32(bs, ptr->def_sample_duration); gf_bs_write_u32(bs, ptr->def_sample_size); gf_bs_write_u32(bs, ptr->def_sample_flags); return GF_OK; } GF_Err trex_Size(GF_Box *s) { GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s; ptr->size += 20; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void trep_del(GF_Box *s) { GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err trep_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s; ptr->trackID = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); return gf_isom_box_array_read(s, bs, gf_isom_box_add_default); } GF_Box *trep_New() { ISOM_DECL_BOX_ALLOC(GF_TrackExtensionPropertiesBox, GF_ISOM_BOX_TYPE_TREP); tmp->other_boxes = gf_list_new(); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trep_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->trackID); return GF_OK; } GF_Err trep_Size(GF_Box *s) { GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s; ptr->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ #ifndef GPAC_DISABLE_ISOM_FRAGMENTS void trun_del(GF_Box *s) { GF_TrunEntry *p; GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s; if (ptr == NULL) return; while (gf_list_count(ptr->entries)) { p = (GF_TrunEntry*)gf_list_get(ptr->entries, 0); gf_list_rem(ptr->entries, 0); gf_free(p); } gf_list_del(ptr->entries); if (ptr->cache) gf_bs_del(ptr->cache); gf_free(ptr); } GF_Err trun_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_TrunEntry *p; GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s; //check this is a good file if ((ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) && (ptr->flags & GF_ISOM_TRUN_FLAGS)) return GF_ISOM_INVALID_FILE; ptr->sample_count = gf_bs_read_u32(bs); //The rest depends on the flags if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) { ptr->data_offset = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); } if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) { ptr->first_sample_flags = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); } //read each entry (even though nothing may be written) for (i=0; i<ptr->sample_count; i++) { u32 trun_size = 0; p = (GF_TrunEntry *) gf_malloc(sizeof(GF_TrunEntry)); if (!p) return GF_OUT_OF_MEM; memset(p, 0, sizeof(GF_TrunEntry)); if (ptr->flags & GF_ISOM_TRUN_DURATION) { p->Duration = gf_bs_read_u32(bs); trun_size += 4; } if (ptr->flags & GF_ISOM_TRUN_SIZE) { p->size = gf_bs_read_u32(bs); trun_size += 4; } //SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED if (ptr->flags & GF_ISOM_TRUN_FLAGS) { p->flags = gf_bs_read_u32(bs); trun_size += 4; } if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) { if (ptr->version==0) { p->CTS_Offset = (u32) gf_bs_read_u32(bs); } else { p->CTS_Offset = (s32) gf_bs_read_u32(bs); } } gf_list_add(ptr->entries, p); ISOM_DECREASE_SIZE(ptr, trun_size); } return GF_OK; } GF_Box *trun_New() { ISOM_DECL_BOX_ALLOC(GF_TrackFragmentRunBox, GF_ISOM_BOX_TYPE_TRUN); tmp->entries = gf_list_new(); //NO FLAGS SET BY DEFAULT return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trun_Write(GF_Box *s, GF_BitStream *bs) { GF_TrunEntry *p; GF_Err e; u32 i, count; GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->sample_count); //The rest depends on the flags if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) { gf_bs_write_u32(bs, ptr->data_offset); } if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) { gf_bs_write_u32(bs, ptr->first_sample_flags); } //if nothing to do, this will be skipped automatically count = gf_list_count(ptr->entries); for (i=0; i<count; i++) { p = (GF_TrunEntry*)gf_list_get(ptr->entries, i); if (ptr->flags & GF_ISOM_TRUN_DURATION) { gf_bs_write_u32(bs, p->Duration); } if (ptr->flags & GF_ISOM_TRUN_SIZE) { gf_bs_write_u32(bs, p->size); } //SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED if (ptr->flags & GF_ISOM_TRUN_FLAGS) { gf_bs_write_u32(bs, p->flags); } if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) { if (ptr->version==0) { gf_bs_write_u32(bs, p->CTS_Offset); } else { gf_bs_write_u32(bs, (u32) p->CTS_Offset); } } } return GF_OK; } GF_Err trun_Size(GF_Box *s) { u32 i, count; GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s; ptr->size += 4; //The rest depends on the flags if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) ptr->size += 4; if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) ptr->size += 4; //if nothing to do, this will be skipped automatically count = gf_list_count(ptr->entries); for (i=0; i<count; i++) { if (ptr->flags & GF_ISOM_TRUN_DURATION) ptr->size += 4; if (ptr->flags & GF_ISOM_TRUN_SIZE) ptr->size += 4; //SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED if (ptr->flags & GF_ISOM_TRUN_FLAGS) ptr->size += 4; if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) ptr->size += 4; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ void tsro_del(GF_Box *s) { GF_TimeOffHintEntryBox *tsro = (GF_TimeOffHintEntryBox *)s; gf_free(tsro); } GF_Err tsro_Read(GF_Box *s, GF_BitStream *bs) { GF_TimeOffHintEntryBox *ptr = (GF_TimeOffHintEntryBox *)s; ptr->TimeOffset = gf_bs_read_u32(bs); return GF_OK; } GF_Box *tsro_New() { ISOM_DECL_BOX_ALLOC(GF_TimeOffHintEntryBox, GF_ISOM_BOX_TYPE_TSRO); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tsro_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TimeOffHintEntryBox *ptr = (GF_TimeOffHintEntryBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->TimeOffset); return GF_OK; } GF_Err tsro_Size(GF_Box *s) { s->size += 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void udta_del(GF_Box *s) { u32 i; GF_UserDataMap *map; GF_UserDataBox *ptr = (GF_UserDataBox *)s; if (ptr == NULL) return; i=0; while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) { gf_isom_box_array_del(map->other_boxes); gf_free(map); } gf_list_del(ptr->recordList); gf_free(ptr); } GF_UserDataMap *udta_getEntry(GF_UserDataBox *ptr, u32 box_type, bin128 *uuid) { u32 i; GF_UserDataMap *map; if (ptr == NULL) return NULL; i=0; while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) { if (map->boxType == box_type) { if ((box_type != GF_ISOM_BOX_TYPE_UUID) || !uuid) return map; if (!memcmp(map->uuid, *uuid, 16)) return map; } } return NULL; } GF_Err udta_AddBox(GF_Box *s, GF_Box *a) { GF_Err e; u32 box_type; GF_UserDataMap *map; GF_UserDataBox *ptr = (GF_UserDataBox *)s; if (!ptr) return GF_BAD_PARAM; if (!a) return GF_OK; /* for unknown udta boxes, we reference them by their original box type */ box_type = a->type; if (box_type == GF_ISOM_BOX_TYPE_UNKNOWN) { GF_UnknownBox* unkn = (GF_UnknownBox *)a; if (unkn) box_type = unkn->original_4cc; } map = udta_getEntry(ptr, box_type, (a->type==GF_ISOM_BOX_TYPE_UUID) ? & ((GF_UUIDBox *)a)->uuid : NULL); if (map == NULL) { map = (GF_UserDataMap *) gf_malloc(sizeof(GF_UserDataMap)); if (map == NULL) return GF_OUT_OF_MEM; memset(map, 0, sizeof(GF_UserDataMap)); map->boxType = box_type; if (a->type == GF_ISOM_BOX_TYPE_UUID) memcpy(map->uuid, ((GF_UUIDBox *)a)->uuid, 16); map->other_boxes = gf_list_new(); if (!map->other_boxes) { gf_free(map); return GF_OUT_OF_MEM; } e = gf_list_add(ptr->recordList, map); if (e) return e; } return gf_list_add(map->other_boxes, a); } GF_Err udta_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, udta_AddBox); } GF_Box *udta_New() { ISOM_DECL_BOX_ALLOC(GF_UserDataBox, GF_ISOM_BOX_TYPE_UDTA); tmp->recordList = gf_list_new(); if (!tmp->recordList) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err udta_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_UserDataMap *map; GF_UserDataBox *ptr = (GF_UserDataBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; i=0; while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) { //warning: here we are not passing the actual "parent" of the list //but the UDTA box. The parent itself is not an box, we don't care about it e = gf_isom_box_array_write(s, map->other_boxes, bs); if (e) return e; } return GF_OK; } GF_Err udta_Size(GF_Box *s) { GF_Err e; u32 i; GF_UserDataMap *map; GF_UserDataBox *ptr = (GF_UserDataBox *)s; i=0; while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) { //warning: here we are not passing the actual "parent" of the list //but the UDTA box. The parent itself is not an box, we don't care about it e = gf_isom_box_array_size(s, map->other_boxes); if (e) return e; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void vmhd_del(GF_Box *s) { GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err vmhd_Read(GF_Box *s, GF_BitStream *bs) { GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s; ptr->reserved = gf_bs_read_u64(bs); return GF_OK; } GF_Box *vmhd_New() { ISOM_DECL_BOX_ALLOC(GF_VideoMediaHeaderBox, GF_ISOM_BOX_TYPE_VMHD); tmp->flags = 1; return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err vmhd_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u64(bs, ptr->reserved); return GF_OK; } GF_Err vmhd_Size(GF_Box *s) { GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s; ptr->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void void_del(GF_Box *s) { gf_free(s); } GF_Err void_Read(GF_Box *s, GF_BitStream *bs) { if (s->size) return GF_ISOM_INVALID_FILE; return GF_OK; } GF_Box *void_New() { ISOM_DECL_BOX_ALLOC(GF_Box, GF_ISOM_BOX_TYPE_VOID); return tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err void_Write(GF_Box *s, GF_BitStream *bs) { gf_bs_write_u32(bs, 0); return GF_OK; } GF_Err void_Size(GF_Box *s) { s->size = 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *pdin_New() { ISOM_DECL_BOX_ALLOC(GF_ProgressiveDownloadBox, GF_ISOM_BOX_TYPE_PDIN); tmp->flags = 1; return (GF_Box *)tmp; } void pdin_del(GF_Box *s) { GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox*)s; if (ptr == NULL) return; if (ptr->rates) gf_free(ptr->rates); if (ptr->times) gf_free(ptr->times); gf_free(ptr); } GF_Err pdin_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox*)s; ptr->count = (u32) (ptr->size) / 8; ptr->rates = (u32*)gf_malloc(sizeof(u32)*ptr->count); ptr->times = (u32*)gf_malloc(sizeof(u32)*ptr->count); for (i=0; i<ptr->count; i++) { ptr->rates[i] = gf_bs_read_u32(bs); ptr->times[i] = gf_bs_read_u32(bs); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err pdin_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; for (i=0; i<ptr->count; i++) { gf_bs_write_u32(bs, ptr->rates[i]); gf_bs_write_u32(bs, ptr->times[i]); } return GF_OK; } GF_Err pdin_Size(GF_Box *s) { GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox *)s; ptr->size += 8*ptr->count; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *sdtp_New() { ISOM_DECL_BOX_ALLOC(GF_SampleDependencyTypeBox, GF_ISOM_BOX_TYPE_SDTP); tmp->flags = 1; return (GF_Box *)tmp; } void sdtp_del(GF_Box *s) { GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox*)s; if (ptr == NULL) return; if (ptr->sample_info) gf_free(ptr->sample_info); gf_free(ptr); } GF_Err sdtp_Read(GF_Box *s, GF_BitStream *bs) { GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox*)s; /*out-of-order sdtp, assume no padding at the end*/ if (!ptr->sampleCount) ptr->sampleCount = (u32) ptr->size; else if (ptr->sampleCount > (u32) ptr->size) return GF_ISOM_INVALID_FILE; ptr->sample_info = (u8 *) gf_malloc(sizeof(u8)*ptr->sampleCount); gf_bs_read_data(bs, (char*)ptr->sample_info, ptr->sampleCount); ISOM_DECREASE_SIZE(ptr, ptr->sampleCount); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err sdtp_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_data(bs, (char*)ptr->sample_info, ptr->sampleCount); return GF_OK; } GF_Err sdtp_Size(GF_Box *s) { GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox *)s; ptr->size += ptr->sampleCount; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *pasp_New() { ISOM_DECL_BOX_ALLOC(GF_PixelAspectRatioBox, GF_ISOM_BOX_TYPE_PASP); return (GF_Box *)tmp; } void pasp_del(GF_Box *s) { GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err pasp_Read(GF_Box *s, GF_BitStream *bs) { GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)s; ptr->hSpacing = gf_bs_read_u32(bs); ptr->vSpacing = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err pasp_Write(GF_Box *s, GF_BitStream *bs) { GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox *)s; GF_Err e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->hSpacing); gf_bs_write_u32(bs, ptr->vSpacing); return GF_OK; } GF_Err pasp_Size(GF_Box *s) { s->size += 8; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *clap_New() { ISOM_DECL_BOX_ALLOC(GF_CleanAppertureBox, GF_ISOM_BOX_TYPE_CLAP); return (GF_Box *)tmp; } void clap_del(GF_Box *s) { GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err clap_Read(GF_Box *s, GF_BitStream *bs) { GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)s; ISOM_DECREASE_SIZE(ptr, 32); ptr->cleanApertureWidthN = gf_bs_read_u32(bs); ptr->cleanApertureWidthD = gf_bs_read_u32(bs); ptr->cleanApertureHeightN = gf_bs_read_u32(bs); ptr->cleanApertureHeightD = gf_bs_read_u32(bs); ptr->horizOffN = gf_bs_read_u32(bs); ptr->horizOffD = gf_bs_read_u32(bs); ptr->vertOffN = gf_bs_read_u32(bs); ptr->vertOffD = gf_bs_read_u32(bs); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err clap_Write(GF_Box *s, GF_BitStream *bs) { GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox *)s; GF_Err e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->cleanApertureWidthN); gf_bs_write_u32(bs, ptr->cleanApertureWidthD); gf_bs_write_u32(bs, ptr->cleanApertureHeightN); gf_bs_write_u32(bs, ptr->cleanApertureHeightD); gf_bs_write_u32(bs, ptr->horizOffN); gf_bs_write_u32(bs, ptr->horizOffD); gf_bs_write_u32(bs, ptr->vertOffN); gf_bs_write_u32(bs, ptr->vertOffD); return GF_OK; } GF_Err clap_Size(GF_Box *s) { s->size += 32; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *metx_New() { //type is overridden by the box constructor ISOM_DECL_BOX_ALLOC(GF_MetaDataSampleEntryBox, GF_ISOM_BOX_TYPE_METX); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); return (GF_Box *)tmp; } void metx_del(GF_Box *s) { GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)s; if (ptr == NULL) return; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s); if (ptr->content_encoding) gf_free(ptr->content_encoding); if (ptr->xml_namespace) gf_free(ptr->xml_namespace); if (ptr->xml_schema_loc) gf_free(ptr->xml_schema_loc); if (ptr->mime_type) gf_free(ptr->mime_type); if (ptr->config) gf_isom_box_del((GF_Box *)ptr->config); gf_free(ptr); } GF_Err metx_AddBox(GF_Box *s, GF_Box *a) { GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_SINF: gf_list_add(ptr->protections, a); break; case GF_ISOM_BOX_TYPE_TXTC: //we allow the config box on metx if (ptr->config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->config = (GF_TextConfigBox *)a; break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err metx_Read(GF_Box *s, GF_BitStream *bs) { u32 size, i; GF_Err e; char *str; GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)s; e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs); if (e) return e; size = (u32) ptr->size - 8; str = gf_malloc(sizeof(char)*size); i=0; while (size) { str[i] = gf_bs_read_u8(bs); size--; if (!str[i]) break; i++; } if (i) { if (ptr->type==GF_ISOM_BOX_TYPE_STPP) { ptr->xml_namespace = gf_strdup(str); } else { ptr->content_encoding = gf_strdup(str); } } i=0; while (size) { str[i] = gf_bs_read_u8(bs); size--; if (!str[i]) break; i++; } if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) { if (i) { if (ptr->type==GF_ISOM_BOX_TYPE_STPP) { ptr->xml_schema_loc = gf_strdup(str); } else { ptr->xml_namespace = gf_strdup(str); } } i=0; while (size) { str[i] = gf_bs_read_u8(bs); size--; if (!str[i]) break; i++; } if (i) { if (ptr->type==GF_ISOM_BOX_TYPE_STPP) { ptr->mime_type = gf_strdup(str); } else { ptr->xml_schema_loc = gf_strdup(str); } } } //mett, sbtt, stxt, stpp else { if (i) ptr->mime_type = gf_strdup(str); } ptr->size = size; gf_free(str); return gf_isom_box_array_read(s, bs, metx_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err metx_Write(GF_Box *s, GF_BitStream *bs) { GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s; GF_Err e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->reserved, 6); gf_bs_write_u16(bs, ptr->dataReferenceIndex); if (ptr->type!=GF_ISOM_BOX_TYPE_STPP) { if (ptr->content_encoding) gf_bs_write_data(bs, ptr->content_encoding, (u32) strlen(ptr->content_encoding)); gf_bs_write_u8(bs, 0); } if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) { if (ptr->xml_namespace) gf_bs_write_data(bs, ptr->xml_namespace, (u32) strlen(ptr->xml_namespace)); gf_bs_write_u8(bs, 0); if (ptr->xml_schema_loc) gf_bs_write_data(bs, ptr->xml_schema_loc, (u32) strlen(ptr->xml_schema_loc)); gf_bs_write_u8(bs, 0); if (ptr->type==GF_ISOM_BOX_TYPE_STPP) { if (ptr->mime_type) gf_bs_write_data(bs, ptr->mime_type, (u32) strlen(ptr->mime_type)); gf_bs_write_u8(bs, 0); } } //mett, sbtt, stxt else { if (ptr->mime_type) gf_bs_write_data(bs, ptr->mime_type, (u32) strlen(ptr->mime_type)); gf_bs_write_u8(bs, 0); if (ptr->config) { gf_isom_box_write((GF_Box *)ptr->config, bs); } } return gf_isom_box_array_write(s, ptr->protections, bs); } GF_Err metx_Size(GF_Box *s) { GF_Err e; GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s; ptr->size += 8; if (ptr->type!=GF_ISOM_BOX_TYPE_STPP) { if (ptr->content_encoding) ptr->size += strlen(ptr->content_encoding); ptr->size++; } if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) { if (ptr->xml_namespace) ptr->size += strlen(ptr->xml_namespace); ptr->size++; if (ptr->xml_schema_loc) ptr->size += strlen(ptr->xml_schema_loc); ptr->size++; if (ptr->type==GF_ISOM_BOX_TYPE_STPP) { if (ptr->mime_type) ptr->size += strlen(ptr->mime_type); ptr->size++; } } //mett, sbtt, stxt else { if (ptr->mime_type) ptr->size += strlen(ptr->mime_type); ptr->size++; if (ptr->config) { e = gf_isom_box_size((GF_Box *)ptr->config); if (e) return e; ptr->size += ptr->config->size; } } return gf_isom_box_array_size(s, ptr->protections); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ /* SimpleTextSampleEntry */ GF_Box *txtc_New() { ISOM_DECL_BOX_ALLOC(GF_TextConfigBox, GF_ISOM_BOX_TYPE_TXTC); return (GF_Box *)tmp; } void txtc_del(GF_Box *s) { GF_TextConfigBox *ptr = (GF_TextConfigBox*)s; if (ptr == NULL) return; if (ptr->config) gf_free(ptr->config); gf_free(ptr); } GF_Err txtc_Read(GF_Box *s, GF_BitStream *bs) { u32 size, i; char *str; GF_TextConfigBox *ptr = (GF_TextConfigBox*)s; size = (u32) ptr->size; str = (char *)gf_malloc(sizeof(char)*size); i=0; while (size) { str[i] = gf_bs_read_u8(bs); size--; if (!str[i]) break; i++; } if (i) ptr->config = gf_strdup(str); gf_free(str); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err txtc_Write(GF_Box *s, GF_BitStream *bs) { GF_TextConfigBox *ptr = (GF_TextConfigBox *)s; GF_Err e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->config) gf_bs_write_data(bs, ptr->config, (u32) strlen(ptr->config)); gf_bs_write_u8(bs, 0); return GF_OK; } GF_Err txtc_Size(GF_Box *s) { GF_TextConfigBox *ptr = (GF_TextConfigBox *)s; if (ptr->config) ptr->size += strlen(ptr->config); ptr->size++; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *dac3_New() { ISOM_DECL_BOX_ALLOC(GF_AC3ConfigBox, GF_ISOM_BOX_TYPE_DAC3); return (GF_Box *)tmp; } GF_Box *dec3_New() { ISOM_DECL_BOX_ALLOC(GF_AC3ConfigBox, GF_ISOM_BOX_TYPE_DAC3); tmp->cfg.is_ec3 = 1; return (GF_Box *)tmp; } void dac3_del(GF_Box *s) { GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s; gf_free(ptr); } GF_Err dac3_Read(GF_Box *s, GF_BitStream *bs) { GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s; if (ptr == NULL) return GF_BAD_PARAM; if (ptr->cfg.is_ec3) { u32 i; ptr->cfg.brcode = gf_bs_read_int(bs, 13); ptr->cfg.nb_streams = gf_bs_read_int(bs, 3) + 1; for (i=0; i<ptr->cfg.nb_streams; i++) { ptr->cfg.streams[i].fscod = gf_bs_read_int(bs, 2); ptr->cfg.streams[i].bsid = gf_bs_read_int(bs, 5); ptr->cfg.streams[i].bsmod = gf_bs_read_int(bs, 5); ptr->cfg.streams[i].acmod = gf_bs_read_int(bs, 3); ptr->cfg.streams[i].lfon = gf_bs_read_int(bs, 1); gf_bs_read_int(bs, 3); ptr->cfg.streams[i].nb_dep_sub = gf_bs_read_int(bs, 4); if (ptr->cfg.streams[i].nb_dep_sub) { ptr->cfg.streams[i].chan_loc = gf_bs_read_int(bs, 9); } else { gf_bs_read_int(bs, 1); } } } else { ptr->cfg.nb_streams = 1; ptr->cfg.streams[0].fscod = gf_bs_read_int(bs, 2); ptr->cfg.streams[0].bsid = gf_bs_read_int(bs, 5); ptr->cfg.streams[0].bsmod = gf_bs_read_int(bs, 3); ptr->cfg.streams[0].acmod = gf_bs_read_int(bs, 3); ptr->cfg.streams[0].lfon = gf_bs_read_int(bs, 1); ptr->cfg.brcode = gf_bs_read_int(bs, 5); gf_bs_read_int(bs, 5); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err dac3_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s; if (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DEC3; e = gf_isom_box_write_header(s, bs); if (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DAC3; if (e) return e; if (ptr->cfg.is_ec3) { u32 i; gf_bs_write_int(bs, ptr->cfg.brcode, 13); gf_bs_write_int(bs, ptr->cfg.nb_streams - 1, 3); for (i=0; i<ptr->cfg.nb_streams; i++) { gf_bs_write_int(bs, ptr->cfg.streams[i].fscod, 2); gf_bs_write_int(bs, ptr->cfg.streams[i].bsid, 5); gf_bs_write_int(bs, ptr->cfg.streams[i].bsmod, 5); gf_bs_write_int(bs, ptr->cfg.streams[i].acmod, 3); gf_bs_write_int(bs, ptr->cfg.streams[i].lfon, 1); gf_bs_write_int(bs, 0, 3); gf_bs_write_int(bs, ptr->cfg.streams[i].nb_dep_sub, 4); if (ptr->cfg.streams[i].nb_dep_sub) { gf_bs_write_int(bs, ptr->cfg.streams[i].chan_loc, 9); } else { gf_bs_write_int(bs, 0, 1); } } } else { gf_bs_write_int(bs, ptr->cfg.streams[0].fscod, 2); gf_bs_write_int(bs, ptr->cfg.streams[0].bsid, 5); gf_bs_write_int(bs, ptr->cfg.streams[0].bsmod, 3); gf_bs_write_int(bs, ptr->cfg.streams[0].acmod, 3); gf_bs_write_int(bs, ptr->cfg.streams[0].lfon, 1); gf_bs_write_int(bs, ptr->cfg.brcode, 5); gf_bs_write_int(bs, 0, 5); } return GF_OK; } GF_Err dac3_Size(GF_Box *s) { GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s; if (ptr->cfg.is_ec3) { u32 i; s->size += 2; for (i=0; i<ptr->cfg.nb_streams; i++) { s->size += 3; if (ptr->cfg.streams[i].nb_dep_sub) s->size += 1; } } else { s->size += 3; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void lsrc_del(GF_Box *s) { GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s; if (ptr == NULL) return; if (ptr->hdr) gf_free(ptr->hdr); gf_free(ptr); } GF_Err lsrc_Read(GF_Box *s, GF_BitStream *bs) { GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s; ptr->hdr_size = (u32) ptr->size; ptr->hdr = gf_malloc(sizeof(char)*ptr->hdr_size); gf_bs_read_data(bs, ptr->hdr, ptr->hdr_size); return GF_OK; } GF_Box *lsrc_New() { ISOM_DECL_BOX_ALLOC(GF_LASERConfigurationBox, GF_ISOM_BOX_TYPE_LSRC); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err lsrc_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->hdr, ptr->hdr_size); return GF_OK; } GF_Err lsrc_Size(GF_Box *s) { GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s; ptr->size += ptr->hdr_size; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void lsr1_del(GF_Box *s) { GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s; if (ptr == NULL) return; gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s); if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc); if (ptr->lsr_config) gf_isom_box_del((GF_Box *) ptr->lsr_config); if (ptr->descr) gf_isom_box_del((GF_Box *) ptr->descr); gf_free(ptr); } GF_Err lsr1_AddBox(GF_Box *s, GF_Box *a) { GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s; switch (a->type) { case GF_ISOM_BOX_TYPE_LSRC: if (ptr->lsr_config) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->lsr_config = (GF_LASERConfigurationBox *)a; break; case GF_ISOM_BOX_TYPE_M4DS: if (ptr->descr) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->descr = (GF_MPEG4ExtensionDescriptorsBox *)a; break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err lsr1_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox*)s; e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs); if (e) return e; ISOM_DECREASE_SIZE(ptr, 8); return gf_isom_box_array_read(s, bs, lsr1_AddBox); } GF_Box *lsr1_New() { ISOM_DECL_BOX_ALLOC(GF_LASeRSampleEntryBox, GF_ISOM_BOX_TYPE_LSR1); gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err lsr1_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_data(bs, ptr->reserved, 6); gf_bs_write_u16(bs, ptr->dataReferenceIndex); if (ptr->lsr_config) { e = gf_isom_box_write((GF_Box *)ptr->lsr_config, bs); if (e) return e; } if (ptr->descr) { e = gf_isom_box_write((GF_Box *)ptr->descr, bs); if (e) return e; } return e; } GF_Err lsr1_Size(GF_Box *s) { GF_Err e; GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s; s->size += 8; if (ptr->lsr_config) { e = gf_isom_box_size((GF_Box *)ptr->lsr_config); if (e) return e; ptr->size += ptr->lsr_config->size; } if (ptr->descr) { e = gf_isom_box_size((GF_Box *)ptr->descr); if (e) return e; ptr->size += ptr->descr->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void sidx_del(GF_Box *s) { GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox *) s; if (ptr == NULL) return; if (ptr->refs) gf_free(ptr->refs); gf_free(ptr); } GF_Err sidx_Read(GF_Box *s,GF_BitStream *bs) { u32 i; GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s; ptr->reference_ID = gf_bs_read_u32(bs); ptr->timescale = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); if (ptr->version==0) { ptr->earliest_presentation_time = gf_bs_read_u32(bs); ptr->first_offset = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); } else { ptr->earliest_presentation_time = gf_bs_read_u64(bs); ptr->first_offset = gf_bs_read_u64(bs); ISOM_DECREASE_SIZE(ptr, 16); } gf_bs_read_u16(bs); /* reserved */ ptr->nb_refs = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(ptr, 4); ptr->refs = gf_malloc(sizeof(GF_SIDXReference)*ptr->nb_refs); for (i=0; i<ptr->nb_refs; i++) { ptr->refs[i].reference_type = gf_bs_read_int(bs, 1); ptr->refs[i].reference_size = gf_bs_read_int(bs, 31); ptr->refs[i].subsegment_duration = gf_bs_read_u32(bs); ptr->refs[i].starts_with_SAP = gf_bs_read_int(bs, 1); ptr->refs[i].SAP_type = gf_bs_read_int(bs, 3); ptr->refs[i].SAP_delta_time = gf_bs_read_int(bs, 28); ISOM_DECREASE_SIZE(ptr, 12); } return GF_OK; } GF_Box *sidx_New() { ISOM_DECL_BOX_ALLOC(GF_SegmentIndexBox, GF_ISOM_BOX_TYPE_SIDX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err sidx_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->reference_ID); gf_bs_write_u32(bs, ptr->timescale); if (ptr->version==0) { gf_bs_write_u32(bs, (u32) ptr->earliest_presentation_time); gf_bs_write_u32(bs, (u32) ptr->first_offset); } else { gf_bs_write_u64(bs, ptr->earliest_presentation_time); gf_bs_write_u64(bs, ptr->first_offset); } gf_bs_write_u16(bs, 0); gf_bs_write_u16(bs, ptr->nb_refs); for (i=0; i<ptr->nb_refs; i++ ) { gf_bs_write_int(bs, ptr->refs[i].reference_type, 1); gf_bs_write_int(bs, ptr->refs[i].reference_size, 31); gf_bs_write_u32(bs, ptr->refs[i].subsegment_duration); gf_bs_write_int(bs, ptr->refs[i].starts_with_SAP, 1); gf_bs_write_int(bs, ptr->refs[i].SAP_type, 3); gf_bs_write_int(bs, ptr->refs[i].SAP_delta_time, 28); } return GF_OK; } GF_Err sidx_Size(GF_Box *s) { GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s; ptr->size += 12; if (ptr->version==0) { ptr->size += 8; } else { ptr->size += 16; } ptr->size += ptr->nb_refs * 12; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void ssix_del(GF_Box *s) { u32 i; GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox *)s; if (ptr == NULL) return; if (ptr->subsegments) { for (i = 0; i < ptr->subsegment_count; i++) { GF_Subsegment *subsegment = &ptr->subsegments[i]; if (subsegment->levels) gf_free(subsegment->levels); if (subsegment->range_sizes) gf_free(subsegment->range_sizes); } gf_free(ptr->subsegments); } gf_free(ptr); } GF_Err ssix_Read(GF_Box *s, GF_BitStream *bs) { u32 i,j; GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s; if (ptr->size < 4) return GF_BAD_PARAM; ptr->subsegment_count = gf_bs_read_u32(bs); ptr->size -= 4; ptr->subsegments = gf_malloc(ptr->subsegment_count*sizeof(GF_Subsegment)); for (i = 0; i < ptr->subsegment_count; i++) { GF_Subsegment *subseg = &ptr->subsegments[i]; if (ptr->size < 4) return GF_BAD_PARAM; subseg->range_count = gf_bs_read_u32(bs); ptr->size -= 4; if (ptr->size < subseg->range_count*4) return GF_BAD_PARAM; subseg->levels = gf_malloc(sizeof(u8)*subseg->range_count); subseg->range_sizes = gf_malloc(sizeof(u32)*subseg->range_count); for (j = 0; j < subseg->range_count; j++) { subseg->levels[j] = gf_bs_read_u8(bs); subseg->range_sizes[j] = gf_bs_read_u24(bs); ptr->size -= 4; } } return GF_OK; } GF_Box *ssix_New() { ISOM_DECL_BOX_ALLOC(GF_SubsegmentIndexBox, GF_ISOM_BOX_TYPE_SSIX); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err ssix_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i, j; GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->subsegment_count); for (i = 0; i<ptr->subsegment_count; i++) { gf_bs_write_u32(bs, ptr->subsegments[i].range_count); for (j = 0; j < ptr->subsegment_count; j++) { gf_bs_write_u8(bs, ptr->subsegments[i].levels[j]); gf_bs_write_u24(bs, ptr->subsegments[i].range_sizes[j]); } } return GF_OK; } GF_Err ssix_Size(GF_Box *s) { u32 i; GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s; ptr->size += 4; for (i = 0; i < ptr->subsegment_count; i++) { ptr->size += 4 + 4 * ptr->subsegments[i].range_count; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void leva_del(GF_Box *s) { GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox *)s; if (ptr == NULL) return; if (ptr->levels) gf_free(ptr->levels); gf_free(ptr); } GF_Err leva_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s; if (ptr->size < 4) return GF_BAD_PARAM; ptr->level_count = gf_bs_read_u8(bs); ptr->size -= 4; GF_SAFE_ALLOC_N(ptr->levels, ptr->level_count, GF_LevelAssignment); for (i = 0; i < ptr->level_count; i++) { GF_LevelAssignment *level = &ptr->levels[i]; u8 tmp; if (ptr->size < 5) return GF_BAD_PARAM; level->track_id = gf_bs_read_u32(bs); tmp = gf_bs_read_u8(bs); level->padding_flag = tmp >> 7; level->type = tmp & 0x7F; if (level->type == 0) { level->grouping_type = gf_bs_read_u32(bs); } else if (level->type == 1) { level->grouping_type = gf_bs_read_u32(bs); level->grouping_type_parameter = gf_bs_read_u32(bs); } else if (level->type == 4) { level->sub_track_id = gf_bs_read_u32(bs); } } return GF_OK; } GF_Box *leva_New() { ISOM_DECL_BOX_ALLOC(GF_LevelAssignmentBox, GF_ISOM_BOX_TYPE_LEVA); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err leva_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u8(bs, ptr->level_count); for (i = 0; i<ptr->level_count; i++) { gf_bs_write_u32(bs, ptr->levels[i].track_id); gf_bs_write_u8(bs, ptr->levels[i].padding_flag << 7 | (ptr->levels[i].type & 0x7F)); if (ptr->levels[i].type == 0) { gf_bs_write_u32(bs, ptr->levels[i].grouping_type); } else if (ptr->levels[i].type == 1) { gf_bs_write_u32(bs, ptr->levels[i].grouping_type); gf_bs_write_u32(bs, ptr->levels[i].grouping_type_parameter); } else if (ptr->levels[i].type == 4) { gf_bs_write_u32(bs, ptr->levels[i].sub_track_id); } } return GF_OK; } GF_Err leva_Size(GF_Box *s) { u32 i; GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s; ptr->size += 1; for (i = 0; i < ptr->level_count; i++) { ptr->size += 5; if (ptr->levels[i].type == 0 || ptr->levels[i].type == 4) { ptr->size += 4; } else if (ptr->levels[i].type == 1) { ptr->size += 8; } } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *pcrb_New() { ISOM_DECL_BOX_ALLOC(GF_PcrInfoBox, GF_ISOM_BOX_TYPE_PCRB); return (GF_Box *)tmp; } void pcrb_del(GF_Box *s) { GF_PcrInfoBox *ptr = (GF_PcrInfoBox *) s; if (ptr == NULL) return; if (ptr->pcr_values) gf_free(ptr->pcr_values); gf_free(ptr); } GF_Err pcrb_Read(GF_Box *s,GF_BitStream *bs) { u32 i; GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s; ptr->subsegment_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); ptr->pcr_values = gf_malloc(sizeof(u64)*ptr->subsegment_count); for (i=0; i<ptr->subsegment_count; i++) { u64 data1 = gf_bs_read_u32(bs); u64 data2 = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(ptr, 6); ptr->pcr_values[i] = (data1 << 10) | (data2 >> 6); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err pcrb_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->subsegment_count); for (i=0; i<ptr->subsegment_count; i++ ) { u32 data1 = (u32) (ptr->pcr_values[i] >> 10); u16 data2 = (u16) (ptr->pcr_values[i] << 6); gf_bs_write_u32(bs, data1); gf_bs_write_u16(bs, data2); } return GF_OK; } GF_Err pcrb_Size(GF_Box *s) { GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s; ptr->size += 4; ptr->size += ptr->subsegment_count * 6; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *subs_New() { ISOM_DECL_BOX_ALLOC(GF_SubSampleInformationBox, GF_ISOM_BOX_TYPE_SUBS); tmp->Samples = gf_list_new(); return (GF_Box *)tmp; } void subs_del(GF_Box *s) { GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *)s; if (ptr == NULL) return; while (gf_list_count(ptr->Samples)) { GF_SubSampleInfoEntry *pSamp; pSamp = (GF_SubSampleInfoEntry*)gf_list_get(ptr->Samples, 0); while (gf_list_count(pSamp->SubSamples)) { GF_SubSampleEntry *pSubSamp; pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, 0); gf_free(pSubSamp); gf_list_rem(pSamp->SubSamples, 0); } gf_list_del(pSamp->SubSamples); gf_free(pSamp); gf_list_rem(ptr->Samples, 0); } gf_list_del(ptr->Samples); gf_free(ptr); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err subs_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i, j, entry_count; u16 subsample_count; GF_SubSampleInfoEntry *pSamp; GF_SubSampleEntry *pSubSamp; GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; entry_count = gf_list_count(ptr->Samples); gf_bs_write_u32(bs, entry_count); for (i=0; i<entry_count; i++) { pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i); subsample_count = gf_list_count(pSamp->SubSamples); gf_bs_write_u32(bs, pSamp->sample_delta); gf_bs_write_u16(bs, subsample_count); for (j=0; j<subsample_count; j++) { pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, j); if (ptr->version == 1) { gf_bs_write_u32(bs, pSubSamp->subsample_size); } else { gf_bs_write_u16(bs, pSubSamp->subsample_size); } gf_bs_write_u8(bs, pSubSamp->subsample_priority); gf_bs_write_u8(bs, pSubSamp->discardable); gf_bs_write_u32(bs, pSubSamp->reserved); } } return e; } GF_Err subs_Size(GF_Box *s) { GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) s; GF_SubSampleInfoEntry *pSamp; u32 entry_count, i; u16 subsample_count; // add 4 byte for entry_count ptr->size += 4; entry_count = gf_list_count(ptr->Samples); for (i=0; i<entry_count; i++) { pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i); subsample_count = gf_list_count(pSamp->SubSamples); // 4 byte for sample_delta, 2 byte for subsample_count // and 6 + (4 or 2) bytes for each subsample ptr->size += 4 + 2 + subsample_count * (6 + (ptr->version==1 ? 4 : 2)); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Err subs_Read(GF_Box *s, GF_BitStream *bs) { GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *)s; u32 entry_count, i, j; u16 subsample_count; entry_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); for (i=0; i<entry_count; i++) { u32 subs_size=0; GF_SubSampleInfoEntry *pSamp = (GF_SubSampleInfoEntry*) gf_malloc(sizeof(GF_SubSampleInfoEntry)); if (!pSamp) return GF_OUT_OF_MEM; memset(pSamp, 0, sizeof(GF_SubSampleInfoEntry)); pSamp->SubSamples = gf_list_new(); pSamp->sample_delta = gf_bs_read_u32(bs); subsample_count = gf_bs_read_u16(bs); subs_size=6; for (j=0; j<subsample_count; j++) { GF_SubSampleEntry *pSubSamp = (GF_SubSampleEntry*) gf_malloc(sizeof(GF_SubSampleEntry)); if (!pSubSamp) return GF_OUT_OF_MEM; memset(pSubSamp, 0, sizeof(GF_SubSampleEntry)); if (ptr->version==1) { pSubSamp->subsample_size = gf_bs_read_u32(bs); subs_size+=4; } else { pSubSamp->subsample_size = gf_bs_read_u16(bs); subs_size+=2; } pSubSamp->subsample_priority = gf_bs_read_u8(bs); pSubSamp->discardable = gf_bs_read_u8(bs); pSubSamp->reserved = gf_bs_read_u32(bs); subs_size+=6; gf_list_add(pSamp->SubSamples, pSubSamp); } gf_list_add(ptr->Samples, pSamp); ISOM_DECREASE_SIZE(ptr, subs_size); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_FRAGMENTS GF_Box *tfdt_New() { ISOM_DECL_BOX_ALLOC(GF_TFBaseMediaDecodeTimeBox, GF_ISOM_BOX_TYPE_TFDT); return (GF_Box *)tmp; } void tfdt_del(GF_Box *s) { gf_free(s); } /*this is using chpl format according to some NeroRecode samples*/ GF_Err tfdt_Read(GF_Box *s,GF_BitStream *bs) { GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *)s; if (ptr->version==1) { ptr->baseMediaDecodeTime = gf_bs_read_u64(bs); ISOM_DECREASE_SIZE(ptr, 8); } else { ptr->baseMediaDecodeTime = (u32) gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err tfdt_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->version==1) { gf_bs_write_u64(bs, ptr->baseMediaDecodeTime); } else { gf_bs_write_u32(bs, (u32) ptr->baseMediaDecodeTime); } return GF_OK; } GF_Err tfdt_Size(GF_Box *s) { GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *)s; if (ptr->baseMediaDecodeTime<=0xFFFFFFFF) { ptr->version = 0; ptr->size += 4; } else { ptr->version = 1; ptr->size += 8; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/ GF_Box *rvcc_New() { ISOM_DECL_BOX_ALLOC(GF_RVCConfigurationBox, GF_ISOM_BOX_TYPE_RVCC); return (GF_Box *)tmp; } void rvcc_del(GF_Box *s) { gf_free(s); } GF_Err rvcc_Read(GF_Box *s,GF_BitStream *bs) { GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*)s; ptr->predefined_rvc_config = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(ptr, 2); if (!ptr->predefined_rvc_config) { ptr->rvc_meta_idx = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(ptr, 2); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err rvcc_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*) s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->predefined_rvc_config); if (!ptr->predefined_rvc_config) { gf_bs_write_u16(bs, ptr->rvc_meta_idx); } return GF_OK; } GF_Err rvcc_Size(GF_Box *s) { GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox *)s; ptr->size += 2; if (! ptr->predefined_rvc_config) ptr->size += 2; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *sbgp_New() { ISOM_DECL_BOX_ALLOC(GF_SampleGroupBox, GF_ISOM_BOX_TYPE_SBGP); return (GF_Box *)tmp; } void sbgp_del(GF_Box *a) { GF_SampleGroupBox *p = (GF_SampleGroupBox *)a; if (p->sample_entries) gf_free(p->sample_entries); gf_free(p); } GF_Err sbgp_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_SampleGroupBox *ptr = (GF_SampleGroupBox *)s; ptr->grouping_type = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->version==1) { ptr->grouping_type_parameter = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); } ptr->entry_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); ptr->sample_entries = gf_malloc(sizeof(GF_SampleGroupEntry)*ptr->entry_count); if (!ptr->sample_entries) return GF_IO_ERR; for (i=0; i<ptr->entry_count; i++) { ptr->sample_entries[i].sample_count = gf_bs_read_u32(bs); ptr->sample_entries[i].group_description_index = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err sbgp_Write(GF_Box *s, GF_BitStream *bs) { u32 i; GF_Err e; GF_SampleGroupBox *p = (GF_SampleGroupBox*)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, p->grouping_type); if (p->version==1) gf_bs_write_u32(bs, p->grouping_type_parameter); gf_bs_write_u32(bs, p->entry_count); for (i = 0; i<p->entry_count; i++ ) { gf_bs_write_u32(bs, p->sample_entries[i].sample_count); gf_bs_write_u32(bs, p->sample_entries[i].group_description_index); } return GF_OK; } GF_Err sbgp_Size(GF_Box *s) { GF_SampleGroupBox *p = (GF_SampleGroupBox*)s; p->size += 8; if (p->grouping_type_parameter) p->version=1; if (p->version==1) p->size += 4; p->size += 8*p->entry_count; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ static void *sgpd_parse_entry(u32 grouping_type, GF_BitStream *bs, u32 entry_size, u32 *total_bytes) { Bool null_size_ok = GF_FALSE; GF_DefaultSampleGroupDescriptionEntry *ptr; switch (grouping_type) { case GF_ISOM_SAMPLE_GROUP_ROLL: case GF_ISOM_SAMPLE_GROUP_PROL: { GF_RollRecoveryEntry *ptr; GF_SAFEALLOC(ptr, GF_RollRecoveryEntry); if (!ptr) return NULL; ptr->roll_distance = gf_bs_read_int(bs, 16); *total_bytes = 2; return ptr; } case GF_ISOM_SAMPLE_GROUP_RAP: { GF_VisualRandomAccessEntry *ptr; GF_SAFEALLOC(ptr, GF_VisualRandomAccessEntry); if (!ptr) return NULL; ptr->num_leading_samples_known = gf_bs_read_int(bs, 1); ptr->num_leading_samples = gf_bs_read_int(bs, 7); *total_bytes = 1; return ptr; } case GF_ISOM_SAMPLE_GROUP_SAP: { GF_SAPEntry *ptr; GF_SAFEALLOC(ptr, GF_SAPEntry); if (!ptr) return NULL; ptr->dependent_flag = gf_bs_read_int(bs, 1); gf_bs_read_int(bs, 3); ptr->SAP_type = gf_bs_read_int(bs, 4); *total_bytes = 1; return ptr; } case GF_ISOM_SAMPLE_GROUP_SYNC: { GF_SYNCEntry *ptr; GF_SAFEALLOC(ptr, GF_SYNCEntry); if (!ptr) return NULL; gf_bs_read_int(bs, 2); ptr->NALU_type = gf_bs_read_int(bs, 6); *total_bytes = 1; return ptr; } case GF_ISOM_SAMPLE_GROUP_TELE: { GF_TemporalLevelEntry *ptr; GF_SAFEALLOC(ptr, GF_TemporalLevelEntry); if (!ptr) return NULL; ptr->level_independently_decodable = gf_bs_read_int(bs, 1); gf_bs_read_int(bs, 7); *total_bytes = 1; return ptr; } case GF_ISOM_SAMPLE_GROUP_SEIG: { GF_CENCSampleEncryptionGroupEntry *ptr; GF_SAFEALLOC(ptr, GF_CENCSampleEncryptionGroupEntry); if (!ptr) return NULL; gf_bs_read_u8(bs); //reserved ptr->crypt_byte_block = gf_bs_read_int(bs, 4); ptr->skip_byte_block = gf_bs_read_int(bs, 4); ptr->IsProtected = gf_bs_read_u8(bs); ptr->Per_Sample_IV_size = gf_bs_read_u8(bs); gf_bs_read_data(bs, (char *)ptr->KID, 16); *total_bytes = 20; if ((ptr->IsProtected == 1) && !ptr->Per_Sample_IV_size) { ptr->constant_IV_size = gf_bs_read_u8(bs); assert((ptr->constant_IV_size == 8) || (ptr->constant_IV_size == 16)); gf_bs_read_data(bs, (char *)ptr->constant_IV, ptr->constant_IV_size); *total_bytes += 1 + ptr->constant_IV_size; } if (!entry_size) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] seig sample group does not indicate entry size, deprecated in spec\n")); } return ptr; } case GF_ISOM_SAMPLE_GROUP_OINF: { GF_OperatingPointsInformation *ptr = gf_isom_oinf_new_entry(); u32 s = (u32) gf_bs_get_position(bs); gf_isom_oinf_read_entry(ptr, bs); *total_bytes = (u32) gf_bs_get_position(bs) - s; if (!entry_size) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] oinf sample group does not indicate entry size, deprecated in spec\n")); } return ptr; } case GF_ISOM_SAMPLE_GROUP_LINF: { GF_LHVCLayerInformation *ptr = gf_isom_linf_new_entry(); u32 s = (u32) gf_bs_get_position(bs); gf_isom_linf_read_entry(ptr, bs); *total_bytes = (u32) gf_bs_get_position(bs) - s; if (!entry_size) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] linf sample group does not indicate entry size, deprecated in spec\n")); } return ptr; } case GF_ISOM_SAMPLE_GROUP_TRIF: if (! entry_size) { u32 flags = gf_bs_peek_bits(bs, 24, 0); if (flags & 0x10000) entry_size=3; else { if (flags & 0x80000) entry_size=7; else entry_size=11; //have dependency list if (flags & 0x200000) { u32 nb_entries = gf_bs_peek_bits(bs, 16, entry_size); entry_size += 2 + 2*nb_entries; } } GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] trif sample group does not indicate entry size, deprecated in spec\n")); } break; case GF_ISOM_SAMPLE_GROUP_NALM: if (! entry_size) { u64 start = gf_bs_get_position(bs); Bool rle, large_size; u32 entry_count; gf_bs_read_int(bs, 6); large_size = gf_bs_read_int(bs, 1); rle = gf_bs_read_int(bs, 1); entry_count = gf_bs_read_int(bs, large_size ? 16 : 8); gf_bs_seek(bs, start); entry_size = 1 + large_size ? 2 : 1; entry_size += entry_count * 2; if (rle) entry_size += entry_count * (large_size ? 2 : 1); GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] nalm sample group does not indicate entry size, deprecated in spec\n")); } break; case GF_ISOM_SAMPLE_GROUP_TSAS: case GF_ISOM_SAMPLE_GROUP_STSA: null_size_ok = GF_TRUE; break; //TODO, add support for these ones ? case GF_ISOM_SAMPLE_GROUP_TSCL: entry_size = 20; break; case GF_ISOM_SAMPLE_GROUP_LBLI: entry_size = 2; break; default: break; } if (!entry_size && !null_size_ok) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] %s sample group does not indicate entry size and is not implemented, cannot parse!\n", gf_4cc_to_str( grouping_type) )); return NULL; } GF_SAFEALLOC(ptr, GF_DefaultSampleGroupDescriptionEntry); if (!ptr) return NULL; if (entry_size) { ptr->length = entry_size; ptr->data = (u8 *) gf_malloc(sizeof(u8)*ptr->length); gf_bs_read_data(bs, (char *) ptr->data, ptr->length); *total_bytes = entry_size; } return ptr; } static void sgpd_del_entry(u32 grouping_type, void *entry) { switch (grouping_type) { case GF_ISOM_SAMPLE_GROUP_SYNC: case GF_ISOM_SAMPLE_GROUP_ROLL: case GF_ISOM_SAMPLE_GROUP_PROL: case GF_ISOM_SAMPLE_GROUP_RAP: case GF_ISOM_SAMPLE_GROUP_SEIG: case GF_ISOM_SAMPLE_GROUP_TELE: case GF_ISOM_SAMPLE_GROUP_SAP: gf_free(entry); return; case GF_ISOM_SAMPLE_GROUP_OINF: gf_isom_oinf_del_entry(entry); return; case GF_ISOM_SAMPLE_GROUP_LINF: gf_isom_linf_del_entry(entry); return; default: { GF_DefaultSampleGroupDescriptionEntry *ptr = (GF_DefaultSampleGroupDescriptionEntry *)entry; if (ptr->data) gf_free(ptr->data); gf_free(ptr); } } } void sgpd_write_entry(u32 grouping_type, void *entry, GF_BitStream *bs) { switch (grouping_type) { case GF_ISOM_SAMPLE_GROUP_ROLL: case GF_ISOM_SAMPLE_GROUP_PROL: gf_bs_write_int(bs, ((GF_RollRecoveryEntry*)entry)->roll_distance, 16); return; case GF_ISOM_SAMPLE_GROUP_RAP: gf_bs_write_int(bs, ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known, 1); gf_bs_write_int(bs, ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples, 7); return; case GF_ISOM_SAMPLE_GROUP_SAP: gf_bs_write_int(bs, ((GF_SAPEntry*)entry)->dependent_flag, 1); gf_bs_write_int(bs, 0, 3); gf_bs_write_int(bs, ((GF_SAPEntry*)entry)->SAP_type, 4); return; case GF_ISOM_SAMPLE_GROUP_SYNC: gf_bs_write_int(bs, 0, 2); gf_bs_write_int(bs, ((GF_SYNCEntry*)entry)->NALU_type, 6); return; case GF_ISOM_SAMPLE_GROUP_TELE: gf_bs_write_int(bs, ((GF_TemporalLevelEntry*)entry)->level_independently_decodable, 1); gf_bs_write_int(bs, 0, 7); return; case GF_ISOM_SAMPLE_GROUP_SEIG: gf_bs_write_u8(bs, 0x0); gf_bs_write_int(bs, ((GF_CENCSampleEncryptionGroupEntry*)entry)->crypt_byte_block, 4); gf_bs_write_int(bs, ((GF_CENCSampleEncryptionGroupEntry*)entry)->skip_byte_block, 4); gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected); gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size); gf_bs_write_data(bs, (char *)((GF_CENCSampleEncryptionGroupEntry *)entry)->KID, 16); if ((((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size) { gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size); gf_bs_write_data(bs, (char *)((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size); } return; case GF_ISOM_SAMPLE_GROUP_OINF: gf_isom_oinf_write_entry(entry, bs); return; case GF_ISOM_SAMPLE_GROUP_LINF: gf_isom_linf_write_entry(entry, bs); return; default: { GF_DefaultSampleGroupDescriptionEntry *ptr = (GF_DefaultSampleGroupDescriptionEntry *)entry; if (ptr->length) gf_bs_write_data(bs, (char *) ptr->data, ptr->length); } } } #ifndef GPAC_DISABLE_ISOM_WRITE static u32 sgpd_size_entry(u32 grouping_type, void *entry) { switch (grouping_type) { case GF_ISOM_SAMPLE_GROUP_ROLL: case GF_ISOM_SAMPLE_GROUP_PROL: return 2; case GF_ISOM_SAMPLE_GROUP_TELE: case GF_ISOM_SAMPLE_GROUP_RAP: case GF_ISOM_SAMPLE_GROUP_SAP: case GF_ISOM_SAMPLE_GROUP_SYNC: return 1; case GF_ISOM_SAMPLE_GROUP_TSCL: return 20; case GF_ISOM_SAMPLE_GROUP_LBLI: return 2; case GF_ISOM_SAMPLE_GROUP_TSAS: case GF_ISOM_SAMPLE_GROUP_STSA: return 0; case GF_ISOM_SAMPLE_GROUP_SEIG: return ((((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size) ? 21 + ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size : 20; case GF_ISOM_SAMPLE_GROUP_OINF: return gf_isom_oinf_size_entry(entry); case GF_ISOM_SAMPLE_GROUP_LINF: return gf_isom_linf_size_entry(entry); default: return ((GF_DefaultSampleGroupDescriptionEntry *)entry)->length; } } #endif GF_Box *sgpd_New() { ISOM_DECL_BOX_ALLOC(GF_SampleGroupDescriptionBox, GF_ISOM_BOX_TYPE_SGPD); /*version 0 is deprecated, use v1 by default*/ tmp->version = 1; tmp->group_descriptions = gf_list_new(); return (GF_Box *)tmp; } void sgpd_del(GF_Box *a) { GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)a; while (gf_list_count(p->group_descriptions)) { void *ptr = gf_list_last(p->group_descriptions); sgpd_del_entry(p->grouping_type, ptr); gf_list_rem_last(p->group_descriptions); } gf_list_del(p->group_descriptions); gf_free(p); } GF_Err sgpd_Read(GF_Box *s, GF_BitStream *bs) { u32 entry_count; GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s; p->grouping_type = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); if (p->version>=1) { p->default_length = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); } if (p->version>=2) { p->default_description_index = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); } entry_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); if (entry_count>p->size) return GF_ISOM_INVALID_FILE; while (entry_count) { void *ptr; u32 parsed_bytes=0; u32 size = p->default_length; if ((p->version>=1) && !size) { size = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(p, 4); } ptr = sgpd_parse_entry(p->grouping_type, bs, size, &parsed_bytes); //don't return an error, just stop parsing so that we skip over the sgpd box if (!ptr) return GF_OK; ISOM_DECREASE_SIZE(p, parsed_bytes); gf_list_add(p->group_descriptions, ptr); entry_count--; } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err sgpd_Write(GF_Box *s, GF_BitStream *bs) { u32 i; GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s; GF_Err e; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, p->grouping_type); if (p->version>=1) gf_bs_write_u32(bs, p->default_length); if (p->version>=2) gf_bs_write_u32(bs, p->default_description_index); gf_bs_write_u32(bs, gf_list_count(p->group_descriptions) ); for (i=0; i<gf_list_count(p->group_descriptions); i++) { void *ptr = gf_list_get(p->group_descriptions, i); if ((p->version >= 1) && !p->default_length) { u32 size = sgpd_size_entry(p->grouping_type, ptr); gf_bs_write_u32(bs, size); } sgpd_write_entry(p->grouping_type, ptr, bs); } return GF_OK; } GF_Err sgpd_Size(GF_Box *s) { u32 i; GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s; p->size += 8; //we force all sample groups to version 1, v0 being deprecated p->version=1; p->size += 4; if (p->version>=2) p->size += 4; p->default_length = 0; for (i=0; i<gf_list_count(p->group_descriptions); i++) { void *ptr = gf_list_get(p->group_descriptions, i); u32 size = sgpd_size_entry(p->grouping_type, ptr); p->size += size; if (!p->default_length) { p->default_length = size; } else if (p->default_length != size) { p->default_length = 0; } } if (p->version>=1) { if (!p->default_length) p->size += gf_list_count(p->group_descriptions)*4; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void saiz_del(GF_Box *s) { GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*)s; if (ptr == NULL) return; if (ptr->sample_info_size) gf_free(ptr->sample_info_size); gf_free(ptr); } GF_Err saiz_Read(GF_Box *s, GF_BitStream *bs) { GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*)s; if (ptr->flags & 1) { ptr->aux_info_type = gf_bs_read_u32(bs); ptr->aux_info_type_parameter = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); } ptr->default_sample_info_size = gf_bs_read_u8(bs); ptr->sample_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 5); if (ptr->default_sample_info_size == 0) { ptr->sample_info_size = gf_malloc(sizeof(u8)*ptr->sample_count); gf_bs_read_data(bs, (char *) ptr->sample_info_size, ptr->sample_count); ISOM_DECREASE_SIZE(ptr, ptr->sample_count); } return GF_OK; } GF_Box *saiz_New() { ISOM_DECL_BOX_ALLOC(GF_SampleAuxiliaryInfoSizeBox, GF_ISOM_BOX_TYPE_SAIZ); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err saiz_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->flags & 1) { gf_bs_write_u32(bs, ptr->aux_info_type); gf_bs_write_u32(bs, ptr->aux_info_type_parameter); } gf_bs_write_u8(bs, ptr->default_sample_info_size); gf_bs_write_u32(bs, ptr->sample_count); if (!ptr->default_sample_info_size) { gf_bs_write_data(bs, (char *) ptr->sample_info_size, ptr->sample_count); } return GF_OK; } GF_Err saiz_Size(GF_Box *s) { GF_SampleAuxiliaryInfoSizeBox *ptr = (GF_SampleAuxiliaryInfoSizeBox*)s; if (ptr->aux_info_type || ptr->aux_info_type_parameter) { ptr->flags |= 1; } if (ptr->flags & 1) ptr->size += 8; ptr->size += 5; if (ptr->default_sample_info_size==0) ptr->size += ptr->sample_count; return GF_OK; } #endif //GPAC_DISABLE_ISOM_WRITE void saio_del(GF_Box *s) { GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*)s; if (ptr == NULL) return; if (ptr->offsets) gf_free(ptr->offsets); if (ptr->offsets_large) gf_free(ptr->offsets_large); gf_free(ptr); } GF_Err saio_Read(GF_Box *s, GF_BitStream *bs) { GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox *)s; if (ptr->flags & 1) { ptr->aux_info_type = gf_bs_read_u32(bs); ptr->aux_info_type_parameter = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 8); } ptr->entry_count = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); if (ptr->entry_count) { u32 i; if (ptr->version==0) { ptr->offsets = gf_malloc(sizeof(u32)*ptr->entry_count); for (i=0; i<ptr->entry_count; i++) ptr->offsets[i] = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4*ptr->entry_count); } else { ptr->offsets_large = gf_malloc(sizeof(u64)*ptr->entry_count); for (i=0; i<ptr->entry_count; i++) ptr->offsets_large[i] = gf_bs_read_u64(bs); ISOM_DECREASE_SIZE(ptr, 8*ptr->entry_count); } } return GF_OK; } GF_Box *saio_New() { ISOM_DECL_BOX_ALLOC(GF_SampleAuxiliaryInfoOffsetBox, GF_ISOM_BOX_TYPE_SAIO); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err saio_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; if (ptr->flags & 1) { gf_bs_write_u32(bs, ptr->aux_info_type); gf_bs_write_u32(bs, ptr->aux_info_type_parameter); } gf_bs_write_u32(bs, ptr->entry_count); if (ptr->entry_count) { u32 i; //store position in bitstream before writing data - offsets can be NULL if a single offset is rewritten later on (cf senc_write) ptr->offset_first_offset_field = gf_bs_get_position(bs); if (ptr->version==0) { if (!ptr->offsets) { gf_bs_write_u32(bs, 0); } else { for (i=0; i<ptr->entry_count; i++) gf_bs_write_u32(bs, ptr->offsets[i]); } } else { if (!ptr->offsets_large) { gf_bs_write_u64(bs, 0); } else { for (i=0; i<ptr->entry_count; i++) gf_bs_write_u64(bs, ptr->offsets_large[i]); } } } return GF_OK; } GF_Err saio_Size(GF_Box *s) { GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*)s; if (ptr->aux_info_type || ptr->aux_info_type_parameter) { ptr->flags |= 1; } if (ptr->offsets_large) { ptr->version = 1; } if (ptr->flags & 1) ptr->size += 8; ptr->size += 4; //a little optim here: in cenc, the saio always points to a single data block, only one entry is needed switch (ptr->aux_info_type) { case GF_ISOM_CENC_SCHEME: case GF_ISOM_CBC_SCHEME: case GF_ISOM_CENS_SCHEME: case GF_ISOM_CBCS_SCHEME: if (ptr->offsets_large) gf_free(ptr->offsets_large); if (ptr->offsets) gf_free(ptr->offsets); ptr->offsets_large = NULL; ptr->offsets = NULL; ptr->entry_count = 1; break; } ptr->size += ((ptr->version==1) ? 8 : 4) * ptr->entry_count; return GF_OK; } #endif //GPAC_DISABLE_ISOM_WRITE void prft_del(GF_Box *s) { gf_free(s); } GF_Err prft_Read(GF_Box *s,GF_BitStream *bs) { GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) s; ptr->refTrackID = gf_bs_read_u32(bs); ptr->ntp = gf_bs_read_u64(bs); if (ptr->version==0) { ptr->timestamp = gf_bs_read_u32(bs); } else { ptr->timestamp = gf_bs_read_u64(bs); } return GF_OK; } GF_Box *prft_New() { ISOM_DECL_BOX_ALLOC(GF_ProducerReferenceTimeBox, GF_ISOM_BOX_TYPE_PRFT); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err prft_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->refTrackID); gf_bs_write_u64(bs, ptr->ntp); if (ptr->version==0) { gf_bs_write_u32(bs, (u32) ptr->timestamp); } else { gf_bs_write_u64(bs, ptr->timestamp); } return GF_OK; } GF_Err prft_Size(GF_Box *s) { GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox*)s; ptr->size += 4+8+ (ptr->version ? 8 : 4); return GF_OK; } #endif //GPAC_DISABLE_ISOM_WRITE GF_Box *trgr_New() { ISOM_DECL_BOX_ALLOC(GF_TrackGroupBox, GF_ISOM_BOX_TYPE_TRGR); tmp->groups = gf_list_new(); if (!tmp->groups) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } void trgr_del(GF_Box *s) { GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s; if (ptr == NULL) return; gf_isom_box_array_del(ptr->groups); gf_free(ptr); } GF_Err trgr_AddBox(GF_Box *s, GF_Box *a) { GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s; return gf_list_add(ptr->groups, a); } GF_Err trgr_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read_ex(s, bs, trgr_AddBox, s->type); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trgr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackGroupBox *ptr = (GF_TrackGroupBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; return gf_isom_box_array_write(s, ptr->groups, bs); } GF_Err trgr_Size(GF_Box *s) { GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s; return gf_isom_box_array_size(s, ptr->groups); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *trgt_New() { ISOM_DECL_BOX_ALLOC(GF_TrackGroupTypeBox, GF_ISOM_BOX_TYPE_TRGT); return (GF_Box *)tmp; } void trgt_del(GF_Box *s) { GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *)s; if (ptr == NULL) return; gf_free(ptr); } GF_Err trgt_Read(GF_Box *s, GF_BitStream *bs) { GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *)s; ptr->track_group_id = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, 4); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trgt_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *) s; if (!s) return GF_BAD_PARAM; s->type = ptr->group_type; e = gf_isom_full_box_write(s, bs); s->type = GF_ISOM_BOX_TYPE_TRGT; if (e) return e; gf_bs_write_u32(bs, ptr->track_group_id); return GF_OK; } GF_Err trgt_Size(GF_Box *s) { GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s; ptr->size+= 4; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *stvi_New() { ISOM_DECL_BOX_ALLOC(GF_StereoVideoBox, GF_ISOM_BOX_TYPE_STVI); return (GF_Box *)tmp; } void stvi_del(GF_Box *s) { GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s; if (ptr == NULL) return; if (ptr->stereo_indication_type) gf_free(ptr->stereo_indication_type); gf_free(ptr); } GF_Err stvi_Read(GF_Box *s, GF_BitStream *bs) { GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s; ISOM_DECREASE_SIZE(ptr, 12); gf_bs_read_int(bs, 30); ptr->single_view_allowed = gf_bs_read_int(bs, 2); ptr->stereo_scheme = gf_bs_read_u32(bs); ptr->sit_len = gf_bs_read_u32(bs); ISOM_DECREASE_SIZE(ptr, ptr->sit_len); ptr->stereo_indication_type = gf_malloc(sizeof(char)*ptr->sit_len); gf_bs_read_data(bs, ptr->stereo_indication_type, ptr->sit_len); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err stvi_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_StereoVideoBox *ptr = (GF_StereoVideoBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, 0, 30); gf_bs_write_int(bs, ptr->single_view_allowed, 2); gf_bs_write_u32(bs, ptr->stereo_scheme); gf_bs_write_u32(bs, ptr->sit_len); gf_bs_write_data(bs, ptr->stereo_indication_type, ptr->sit_len); return GF_OK; } GF_Err stvi_Size(GF_Box *s) { GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s; ptr->size+= 12 + ptr->sit_len; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *fiin_New() { ISOM_DECL_BOX_ALLOC(FDItemInformationBox, GF_ISOM_BOX_TYPE_FIIN); return (GF_Box *)tmp; } void fiin_del(GF_Box *s) { FDItemInformationBox *ptr = (FDItemInformationBox *)s; if (ptr == NULL) return; if (ptr->partition_entries) gf_isom_box_array_del(ptr->partition_entries); if (ptr->session_info) gf_isom_box_del((GF_Box*)ptr->session_info); if (ptr->group_id_to_name) gf_isom_box_del((GF_Box*)ptr->group_id_to_name); gf_free(ptr); } GF_Err fiin_AddBox(GF_Box *s, GF_Box *a) { FDItemInformationBox *ptr = (FDItemInformationBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_PAEN: if (!ptr->partition_entries) ptr->partition_entries = gf_list_new(); return gf_list_add(ptr->partition_entries, a); case GF_ISOM_BOX_TYPE_SEGR: if (ptr->session_info) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->session_info = (FDSessionGroupBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_GITN: if (ptr->group_id_to_name) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->group_id_to_name = (GroupIdToNameBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err fiin_Read(GF_Box *s, GF_BitStream *bs) { FDItemInformationBox *ptr = (FDItemInformationBox *)s; ISOM_DECREASE_SIZE(ptr, 2); gf_bs_read_u16(bs); return gf_isom_box_array_read(s, bs, fiin_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err fiin_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; FDItemInformationBox *ptr = (FDItemInformationBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, gf_list_count(ptr->partition_entries) ); e = gf_isom_box_array_write(s, ptr->partition_entries, bs); if (e) return e; if (ptr->session_info) gf_isom_box_write((GF_Box*)ptr->session_info, bs); if (ptr->group_id_to_name) gf_isom_box_write((GF_Box*)ptr->group_id_to_name, bs); return GF_OK; } GF_Err fiin_Size(GF_Box *s) { GF_Err e; FDItemInformationBox *ptr = (FDItemInformationBox *)s; ptr->size+= 2; if (ptr->partition_entries) { e = gf_isom_box_array_size(s, ptr->partition_entries); if (e) return e; } if (ptr->session_info) { e = gf_isom_box_size((GF_Box *)ptr->session_info); if (e) return e; ptr->size += ptr->session_info->size; } if (ptr->group_id_to_name) { e = gf_isom_box_size((GF_Box *) ptr->group_id_to_name); if (e) return e; ptr->size += ptr->group_id_to_name->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *paen_New() { ISOM_DECL_BOX_ALLOC(FDPartitionEntryBox, GF_ISOM_BOX_TYPE_PAEN); return (GF_Box *)tmp; } void paen_del(GF_Box *s) { FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s; if (ptr == NULL) return; if (ptr->blocks_and_symbols) gf_isom_box_del((GF_Box*)ptr->blocks_and_symbols); if (ptr->FEC_symbol_locations) gf_isom_box_del((GF_Box*)ptr->FEC_symbol_locations); if (ptr->File_symbol_locations) gf_isom_box_del((GF_Box*)ptr->File_symbol_locations); gf_free(ptr); } GF_Err paen_AddBox(GF_Box *s, GF_Box *a) { FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_FPAR: if (ptr->blocks_and_symbols) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->blocks_and_symbols = (FilePartitionBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_FECR: if (ptr->FEC_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->FEC_symbol_locations = (FECReservoirBox *)a; return GF_OK; case GF_ISOM_BOX_TYPE_FIRE: if (ptr->File_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->File_symbol_locations = (FileReservoirBox *)a; return GF_OK; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err paen_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, fiin_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err paen_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; FDPartitionEntryBox *ptr = (FDPartitionEntryBox *) s; if (!s) return GF_BAD_PARAM; if (ptr->blocks_and_symbols) { e = gf_isom_box_write((GF_Box *)ptr->blocks_and_symbols, bs); if (e) return e; } if (ptr->FEC_symbol_locations) { e = gf_isom_box_write((GF_Box *)ptr->FEC_symbol_locations, bs); if (e) return e; } if (ptr->File_symbol_locations) { e = gf_isom_box_write((GF_Box *)ptr->File_symbol_locations, bs); if (e) return e; } return GF_OK; } GF_Err paen_Size(GF_Box *s) { GF_Err e; FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s; if (ptr->blocks_and_symbols) { e = gf_isom_box_size((GF_Box *)ptr->blocks_and_symbols); if (e) return e; ptr->size += ptr->blocks_and_symbols->size; } if (ptr->FEC_symbol_locations) { e = gf_isom_box_size((GF_Box *) ptr->FEC_symbol_locations); if (e) return e; ptr->size += ptr->FEC_symbol_locations->size; } if (ptr->File_symbol_locations) { e = gf_isom_box_size((GF_Box *) ptr->File_symbol_locations); if (e) return e; ptr->size += ptr->File_symbol_locations->size; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *fpar_New() { ISOM_DECL_BOX_ALLOC(FilePartitionBox, GF_ISOM_BOX_TYPE_FPAR); return (GF_Box *)tmp; } void fpar_del(GF_Box *s) { FilePartitionBox *ptr = (FilePartitionBox *)s; if (ptr == NULL) return; if (ptr->scheme_specific_info) gf_free(ptr->scheme_specific_info); if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err gf_isom_read_null_terminated_string(GF_Box *s, GF_BitStream *bs, u64 size, char **out_str) { u32 len=10; u32 i=0; *out_str = gf_malloc(sizeof(char)*len); while (1) { ISOM_DECREASE_SIZE(s, 1 ); (*out_str)[i] = gf_bs_read_u8(bs); if (!(*out_str)[i]) break; i++; if (i==len) { len += 10; *out_str = gf_realloc(*out_str, sizeof(char)*len); } if (gf_bs_available(bs) == 0) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] missing null character in null terminated string\n")); (*out_str)[i] = 0; return GF_OK; } if (i >= size) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] string bigger than container, probably missing null character\n")); (*out_str)[i] = 0; return GF_OK; } } return GF_OK; } GF_Err fpar_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_Err e; FilePartitionBox *ptr = (FilePartitionBox *)s; ISOM_DECREASE_SIZE(ptr, ((ptr->version ? 4 : 2) + 12) ); ptr->itemID = gf_bs_read_int(bs, ptr->version ? 32 : 16); ptr->packet_payload_size = gf_bs_read_u16(bs); gf_bs_read_u8(bs); ptr->FEC_encoding_ID = gf_bs_read_u8(bs); ptr->FEC_instance_ID = gf_bs_read_u16(bs); ptr->max_source_block_length = gf_bs_read_u16(bs); ptr->encoding_symbol_length = gf_bs_read_u16(bs); ptr->max_number_of_encoding_symbols = gf_bs_read_u16(bs); e = gf_isom_read_null_terminated_string(s, bs, ptr->size, &ptr->scheme_specific_info); if (e) return e; ISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) ); ptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16); ISOM_DECREASE_SIZE(ptr, ptr->nb_entries * 6 ); GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FilePartitionEntry); for (i=0;i < ptr->nb_entries; i++) { ptr->entries[i].block_count = gf_bs_read_u16(bs); ptr->entries[i].block_size = gf_bs_read_u32(bs); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err fpar_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; FilePartitionBox *ptr = (FilePartitionBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->itemID, ptr->version ? 32 : 16); gf_bs_write_u16(bs, ptr->packet_payload_size); gf_bs_write_u8(bs, 0); gf_bs_write_u8(bs, ptr->FEC_encoding_ID); gf_bs_write_u16(bs, ptr->FEC_instance_ID); gf_bs_write_u16(bs, ptr->max_source_block_length); gf_bs_write_u16(bs, ptr->encoding_symbol_length); gf_bs_write_u16(bs, ptr->max_number_of_encoding_symbols); if (ptr->scheme_specific_info) { gf_bs_write_data(bs, ptr->scheme_specific_info, (u32)strlen(ptr->scheme_specific_info) ); } //null terminated string gf_bs_write_u8(bs, 0); gf_bs_write_int(bs, ptr->nb_entries, ptr->version ? 32 : 16); for (i=0;i < ptr->nb_entries; i++) { gf_bs_write_u16(bs, ptr->entries[i].block_count); gf_bs_write_u32(bs, ptr->entries[i].block_size); } return GF_OK; } GF_Err fpar_Size(GF_Box *s) { FilePartitionBox *ptr = (FilePartitionBox *)s; ptr->size+= 13 + ptr->version ? 8 : 4; if (ptr->scheme_specific_info) ptr->size += strlen(ptr->scheme_specific_info); ptr->size+= ptr->nb_entries * 6; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *fecr_New() { ISOM_DECL_BOX_ALLOC(FECReservoirBox, GF_ISOM_BOX_TYPE_FECR); return (GF_Box *)tmp; } void fecr_del(GF_Box *s) { FECReservoirBox *ptr = (FECReservoirBox *)s; if (ptr == NULL) return; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err fecr_Read(GF_Box *s, GF_BitStream *bs) { u32 i; FECReservoirBox *ptr = (FECReservoirBox *)s; ISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) ); ptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16); ISOM_DECREASE_SIZE(ptr, ptr->nb_entries * (ptr->version ? 8 : 6) ); GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FECReservoirEntry); for (i=0; i<ptr->nb_entries; i++) { ptr->entries[i].item_id = gf_bs_read_int(bs, ptr->version ? 32 : 16); ptr->entries[i].symbol_count = gf_bs_read_u32(bs); } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err fecr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; FECReservoirBox *ptr = (FECReservoirBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->nb_entries, ptr->version ? 32 : 16); for (i=0; i<ptr->nb_entries; i++) { gf_bs_write_int(bs, ptr->entries[i].item_id, ptr->version ? 32 : 16); gf_bs_write_u32(bs, ptr->entries[i].symbol_count); } return GF_OK; } GF_Err fecr_Size(GF_Box *s) { FECReservoirBox *ptr = (FECReservoirBox *)s; ptr->size += (ptr->version ? 4 : 2) + ptr->nb_entries * (ptr->version ? 8 : 6); return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *segr_New() { ISOM_DECL_BOX_ALLOC(FDSessionGroupBox, GF_ISOM_BOX_TYPE_SEGR); return (GF_Box *)tmp; } void segr_del(GF_Box *s) { u32 i; FDSessionGroupBox *ptr = (FDSessionGroupBox *)s; if (ptr == NULL) return; for (i=0; i<ptr->num_session_groups; i++) { if (ptr->session_groups[i].group_ids) gf_free(ptr->session_groups[i].group_ids); if (ptr->session_groups[i].channels) gf_free(ptr->session_groups[i].channels); } if (ptr->session_groups) gf_free(ptr->session_groups); gf_free(ptr); } GF_Err segr_Read(GF_Box *s, GF_BitStream *bs) { u32 i, k; FDSessionGroupBox *ptr = (FDSessionGroupBox *)s; ISOM_DECREASE_SIZE(ptr, 2); ptr->num_session_groups = gf_bs_read_u16(bs); if (ptr->num_session_groups*3>ptr->size) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in segr\n", ptr->num_session_groups)); return GF_ISOM_INVALID_FILE; } GF_SAFE_ALLOC_N(ptr->session_groups, ptr->num_session_groups, SessionGroupEntry); for (i=0; i<ptr->num_session_groups; i++) { ptr->session_groups[i].nb_groups = gf_bs_read_u8(bs); ISOM_DECREASE_SIZE(ptr, 1); GF_SAFE_ALLOC_N(ptr->session_groups[i].group_ids, ptr->session_groups[i].nb_groups, u32); for (k=0; k<ptr->session_groups[i].nb_groups; k++) { ISOM_DECREASE_SIZE(ptr, 4); ptr->session_groups[i].group_ids[k] = gf_bs_read_u32(bs); } ptr->session_groups[i].nb_channels = gf_bs_read_u16(bs); GF_SAFE_ALLOC_N(ptr->session_groups[i].channels, ptr->session_groups[i].nb_channels, u32); for (k=0; k<ptr->session_groups[i].nb_channels; k++) { ISOM_DECREASE_SIZE(ptr, 4); ptr->session_groups[i].channels[k] = gf_bs_read_u32(bs); } } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err segr_Write(GF_Box *s, GF_BitStream *bs) { u32 i, k; FDSessionGroupBox *ptr = (FDSessionGroupBox *) s; if (!s) return GF_BAD_PARAM; gf_bs_write_u16(bs, ptr->num_session_groups); for (i=0; i<ptr->num_session_groups; i++) { gf_bs_write_u8(bs, ptr->session_groups[i].nb_groups); for (k=0; k<ptr->session_groups[i].nb_groups; k++) { gf_bs_write_u32(bs, ptr->session_groups[i].group_ids[k]); } gf_bs_write_u16(bs, ptr->session_groups[i].nb_channels); for (k=0; k<ptr->session_groups[i].nb_channels; k++) { gf_bs_write_u32(bs, ptr->session_groups[i].channels[k]); } } return GF_OK; } GF_Err segr_Size(GF_Box *s) { u32 i; FDSessionGroupBox *ptr = (FDSessionGroupBox *)s; ptr->size += 2; for (i=0; i<ptr->num_session_groups; i++) { ptr->size += 1 + 4*ptr->session_groups[i].nb_groups; ptr->size += 2 + 4*ptr->session_groups[i].nb_channels; } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *gitn_New() { ISOM_DECL_BOX_ALLOC(GroupIdToNameBox, GF_ISOM_BOX_TYPE_GITN); return (GF_Box *)tmp; } void gitn_del(GF_Box *s) { u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *)s; if (ptr == NULL) return; for (i=0; i<ptr->nb_entries; i++) { if (ptr->entries[i].name) gf_free(ptr->entries[i].name); } if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err gitn_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_Err e; GroupIdToNameBox *ptr = (GroupIdToNameBox *)s; ISOM_DECREASE_SIZE(ptr, 2); ptr->nb_entries = gf_bs_read_u16(bs); GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, GroupIdNameEntry); for (i=0; i<ptr->nb_entries; i++) { ISOM_DECREASE_SIZE(ptr, 4); ptr->entries[i].group_id = gf_bs_read_u32(bs); e = gf_isom_read_null_terminated_string(s, bs, ptr->size, &ptr->entries[i].name); if (e) return e; } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err gitn_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->entries[i].group_id); if (ptr->entries[i].name) gf_bs_write_data(bs, ptr->entries[i].name, (u32)strlen(ptr->entries[i].name) ); gf_bs_write_u8(bs, 0); } return GF_OK; } GF_Err gitn_Size(GF_Box *s) { u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *)s; ptr->size += 2; for (i=0; i<ptr->nb_entries; i++) { ptr->size += 5; if (ptr->entries[i].name) ptr->size += strlen(ptr->entries[i].name); } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #ifndef GPAC_DISABLE_ISOM_HINTING GF_Box *fdpa_New() { ISOM_DECL_BOX_ALLOC(GF_FDpacketBox, GF_ISOM_BOX_TYPE_FDPA); return (GF_Box *)tmp; } void fdpa_del(GF_Box *s) { u32 i; GF_FDpacketBox *ptr = (GF_FDpacketBox *)s; if (ptr == NULL) return; if (ptr->headers) { for (i=0; i<ptr->header_ext_count; i++) { if (ptr->headers[i].data) gf_free(ptr->headers[i].data); } gf_free(ptr->headers); } gf_free(ptr); } GF_Err fdpa_Read(GF_Box *s, GF_BitStream *bs) { u32 i; GF_FDpacketBox *ptr = (GF_FDpacketBox *)s; ISOM_DECREASE_SIZE(ptr, 3); ptr->info.sender_current_time_present = gf_bs_read_int(bs, 1); ptr->info.expected_residual_time_present = gf_bs_read_int(bs, 1); ptr->info.session_close_bit = gf_bs_read_int(bs, 1); ptr->info.object_close_bit = gf_bs_read_int(bs, 1); gf_bs_read_int(bs, 4); ptr->info.transport_object_identifier = gf_bs_read_u16(bs); ISOM_DECREASE_SIZE(ptr, 2); ptr->header_ext_count = gf_bs_read_u16(bs); if (ptr->header_ext_count*2>ptr->size) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in fdpa\n", ptr->header_ext_count)); return GF_ISOM_INVALID_FILE; } GF_SAFE_ALLOC_N(ptr->headers, ptr->header_ext_count, GF_LCTheaderExtension); for (i=0; i<ptr->header_ext_count; i++) { ptr->headers[i].header_extension_type = gf_bs_read_u8(bs); ISOM_DECREASE_SIZE(ptr, 1); if (ptr->headers[i].header_extension_type > 127) { gf_bs_read_data(bs, (char *) ptr->headers[i].content, 3); } else { ISOM_DECREASE_SIZE(ptr, 1); ptr->headers[i].data_length = gf_bs_read_u8(bs); if (ptr->headers[i].data_length) { ptr->headers[i].data_length = 4*ptr->headers[i].data_length - 2; ptr->headers[i].data = gf_malloc(sizeof(char) * ptr->headers[i].data_length); gf_bs_read_data(bs, ptr->headers[i].data, ptr->headers[i].data_length); } } } return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err fdpa_Write(GF_Box *s, GF_BitStream *bs) { u32 i; GF_FDpacketBox *ptr = (GF_FDpacketBox *) s; if (!s) return GF_BAD_PARAM; gf_bs_write_int(bs, ptr->info.sender_current_time_present, 1); gf_bs_write_int(bs, ptr->info.expected_residual_time_present, 1); gf_bs_write_int(bs, ptr->info.session_close_bit, 1); gf_bs_write_int(bs, ptr->info.object_close_bit, 1); gf_bs_write_int(bs, 0, 4); ptr->info.transport_object_identifier = gf_bs_read_u16(bs); gf_bs_write_u16(bs, ptr->header_ext_count); for (i=0; i<ptr->header_ext_count; i++) { gf_bs_write_u8(bs, ptr->headers[i].header_extension_type); if (ptr->headers[i].header_extension_type > 127) { gf_bs_write_data(bs, (const char *) ptr->headers[i].content, 3); } else { gf_bs_write_u8(bs, ptr->headers[i].data_length ? (ptr->headers[i].data_length+2)/4 : 0); if (ptr->headers[i].data_length) { gf_bs_write_data(bs, ptr->headers[i].data, ptr->headers[i].data_length); } } } return GF_OK; } GF_Err fdpa_Size(GF_Box *s) { u32 i; GF_FDpacketBox *ptr = (GF_FDpacketBox *)s; ptr->size += 5; for (i=0; i<ptr->header_ext_count; i++) { ptr->size += 1; if (ptr->headers[i].header_extension_type > 127) { ptr->size += 3; } else { ptr->size += 1 + ptr->headers[i].data_length; } } return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *extr_New() { ISOM_DECL_BOX_ALLOC(GF_ExtraDataBox, GF_ISOM_BOX_TYPE_EXTR); return (GF_Box *)tmp; } void extr_del(GF_Box *s) { GF_ExtraDataBox *ptr = (GF_ExtraDataBox *)s; if (ptr == NULL) return; if (ptr->feci) gf_isom_box_del((GF_Box*)ptr->feci); if (ptr->data) gf_free(ptr->data); gf_free(ptr); } GF_Err extr_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_ExtraDataBox *ptr = (GF_ExtraDataBox *)s; e = gf_isom_box_parse((GF_Box**) &ptr->feci, bs); if (e) return e; if (ptr->feci->size>ptr->size) return GF_ISOM_INVALID_MEDIA; ptr->data_length = (u32) (ptr->size - ptr->feci->size); ptr->data = gf_malloc(sizeof(char)*ptr->data_length); gf_bs_read_data(bs, ptr->data, ptr->data_length); return GF_OK; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err extr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) s; if (!s) return GF_BAD_PARAM; if (ptr->feci) { e = gf_isom_box_write((GF_Box *)ptr->feci, bs); if (e) return e; } gf_bs_write_data(bs, ptr->data, ptr->data_length); return GF_OK; } GF_Err extr_Size(GF_Box *s) { GF_Err e; GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) s; if (ptr->feci) { e = gf_isom_box_size((GF_Box *)ptr->feci); if (e) return e; ptr->size += ptr->feci->size; } ptr->size += ptr->data_length; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ GF_Box *fdsa_New() { ISOM_DECL_BOX_ALLOC(GF_HintSample, GF_ISOM_BOX_TYPE_FDSA); if (!tmp) return NULL; tmp->packetTable = gf_list_new(); tmp->hint_subtype = GF_ISOM_BOX_TYPE_FDP_STSD; return (GF_Box*)tmp; } void fdsa_del(GF_Box *s) { GF_HintSample *ptr = (GF_HintSample *)s; gf_isom_box_array_del(ptr->packetTable); if (ptr->extra_data) gf_isom_box_del((GF_Box*)ptr->extra_data); gf_free(ptr); } GF_Err fdsa_AddBox(GF_Box *s, GF_Box *a) { GF_HintSample *ptr = (GF_HintSample *)s; switch(a->type) { case GF_ISOM_BOX_TYPE_FDPA: gf_list_add(ptr->packetTable, a); break; case GF_ISOM_BOX_TYPE_EXTR: if (ptr->extra_data) ERROR_ON_DUPLICATED_BOX(a, ptr) ptr->extra_data = (GF_ExtraDataBox*)a; break; default: return gf_isom_box_add_default(s, a); } return GF_OK; } GF_Err fdsa_Read(GF_Box *s, GF_BitStream *bs) { return gf_isom_box_array_read(s, bs, fdsa_AddBox); } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err fdsa_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_HintSample *ptr = (GF_HintSample *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_array_write(s, ptr->packetTable, bs); if (e) return e; if (ptr->extra_data) { e = gf_isom_box_write((GF_Box *)ptr->extra_data, bs); if (e) return e; } return GF_OK; } GF_Err fdsa_Size(GF_Box *s) { GF_HintSample *ptr = (GF_HintSample*)s; GF_Err e; if (ptr->extra_data) { e = gf_isom_box_size((GF_Box *)ptr->extra_data); if (e) return e; ptr->size += ptr->extra_data->size; } return gf_isom_box_array_size(s, ptr->packetTable); } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM_HINTING*/ void trik_del(GF_Box *s) { GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s; if (ptr == NULL) return; if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } GF_Err trik_Read(GF_Box *s,GF_BitStream *bs) { u32 i; GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s; ptr->entry_count = (u32) ptr->size; ptr->entries = (GF_TrickPlayBoxEntry *) gf_malloc(ptr->entry_count * sizeof(GF_TrickPlayBoxEntry) ); if (ptr->entries == NULL) return GF_OUT_OF_MEM; for (i=0; i< ptr->entry_count; i++) { ptr->entries[i].pic_type = gf_bs_read_int(bs, 2); ptr->entries[i].dependency_level = gf_bs_read_int(bs, 6); } return GF_OK; } GF_Box *trik_New() { ISOM_DECL_BOX_ALLOC(GF_TrickPlayBox, GF_ISOM_BOX_TYPE_TRIK); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err trik_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; for (i=0; i < ptr->entry_count; i++ ) { gf_bs_write_int(bs, ptr->entries[i].pic_type, 2); gf_bs_write_int(bs, ptr->entries[i].dependency_level, 6); } return GF_OK; } GF_Err trik_Size(GF_Box *s) { GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s; ptr->size += 8 * ptr->entry_count; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void bloc_del(GF_Box *s) { gf_free(s); } GF_Err bloc_Read(GF_Box *s,GF_BitStream *bs) { GF_BaseLocationBox *ptr = (GF_BaseLocationBox *) s; ISOM_DECREASE_SIZE(s, 256) gf_bs_read_data(bs, (char *) ptr->baseLocation, 256); ISOM_DECREASE_SIZE(s, 256) gf_bs_read_data(bs, (char *) ptr->basePurlLocation, 256); ISOM_DECREASE_SIZE(s, 512) gf_bs_skip_bytes(bs, 512); return GF_OK; } GF_Box *bloc_New() { ISOM_DECL_BOX_ALLOC(GF_BaseLocationBox, GF_ISOM_BOX_TYPE_TRIK); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err bloc_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_BaseLocationBox *ptr = (GF_BaseLocationBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_data(bs, (const char *) ptr->baseLocation, 256); gf_bs_write_data(bs, (const char *) ptr->basePurlLocation, 256); for (i=0; i < 64; i++ ) { gf_bs_write_u64(bs, 0); } return GF_OK; } GF_Err bloc_Size(GF_Box *s) { s->size += 1024; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ void ainf_del(GF_Box *s) { GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s; if (ptr->APID) gf_free(ptr->APID); gf_free(s); } GF_Err ainf_Read(GF_Box *s,GF_BitStream *bs) { GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s; ISOM_DECREASE_SIZE(s, 4) ptr->profile_version = gf_bs_read_u32(bs); return gf_isom_read_null_terminated_string(s, bs, s->size, &ptr->APID); } GF_Box *ainf_New() { ISOM_DECL_BOX_ALLOC(GF_AssetInformationBox, GF_ISOM_BOX_TYPE_AINF); return (GF_Box *)tmp; } #ifndef GPAC_DISABLE_ISOM_WRITE GF_Err ainf_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->profile_version); gf_bs_write_data(bs, ptr->APID, (u32) strlen(ptr->APID) + 1); return GF_OK; } GF_Err ainf_Size(GF_Box *s) { GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s; s->size += 4 + strlen(ptr->APID) + 1; return GF_OK; } #endif /*GPAC_DISABLE_ISOM_WRITE*/ #endif /*GPAC_DISABLE_ISOM*/
./CrossVul/dataset_final_sorted/CWE-125/c/bad_210_1
crossvul-cpp_data_bad_264_0
/* * Copyright: (c) 2000 United States Government as represented by the * Secretary of the Navy. 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. * 3. The names of the authors may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: AFS RX printer */ /* * This code unmangles RX packets. RX is the mutant form of RPC that AFS * uses to communicate between clients and servers. * * In this code, I mainly concern myself with decoding the AFS calls, not * with the guts of RX, per se. * * Bah. If I never look at rx_packet.h again, it will be too soon. * * Ken Hornstein <kenh@cmf.nrl.navy.mil> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #define FS_RX_PORT 7000 #define CB_RX_PORT 7001 #define PROT_RX_PORT 7002 #define VLDB_RX_PORT 7003 #define KAUTH_RX_PORT 7004 #define VOL_RX_PORT 7005 #define ERROR_RX_PORT 7006 /* Doesn't seem to be used */ #define BOS_RX_PORT 7007 #define AFSNAMEMAX 256 #define AFSOPAQUEMAX 1024 #define PRNAMEMAX 64 #define VLNAMEMAX 65 #define KANAMEMAX 64 #define BOSNAMEMAX 256 #define PRSFS_READ 1 /* Read files */ #define PRSFS_WRITE 2 /* Write files */ #define PRSFS_INSERT 4 /* Insert files into a directory */ #define PRSFS_LOOKUP 8 /* Lookup files into a directory */ #define PRSFS_DELETE 16 /* Delete files */ #define PRSFS_LOCK 32 /* Lock files */ #define PRSFS_ADMINISTER 64 /* Change ACL's */ struct rx_header { nd_uint32_t epoch; nd_uint32_t cid; nd_uint32_t callNumber; nd_uint32_t seq; nd_uint32_t serial; nd_uint8_t type; #define RX_PACKET_TYPE_DATA 1 #define RX_PACKET_TYPE_ACK 2 #define RX_PACKET_TYPE_BUSY 3 #define RX_PACKET_TYPE_ABORT 4 #define RX_PACKET_TYPE_ACKALL 5 #define RX_PACKET_TYPE_CHALLENGE 6 #define RX_PACKET_TYPE_RESPONSE 7 #define RX_PACKET_TYPE_DEBUG 8 #define RX_PACKET_TYPE_PARAMS 9 #define RX_PACKET_TYPE_VERSION 13 nd_uint8_t flags; #define RX_CLIENT_INITIATED 1 #define RX_REQUEST_ACK 2 #define RX_LAST_PACKET 4 #define RX_MORE_PACKETS 8 #define RX_FREE_PACKET 16 #define RX_SLOW_START_OK 32 #define RX_JUMBO_PACKET 32 nd_uint8_t userStatus; nd_uint8_t securityIndex; nd_uint16_t spare; /* How clever: even though the AFS */ nd_uint16_t serviceId; /* header files indicate that the */ }; /* serviceId is first, it's really */ /* encoded _after_ the spare field */ /* I wasted a day figuring that out! */ #define NUM_RX_FLAGS 7 #define RX_MAXACKS 255 struct rx_ackPacket { uint16_t bufferSpace; /* Number of packet buffers available */ uint16_t maxSkew; /* Max diff between ack'd packet and */ /* highest packet received */ uint32_t firstPacket; /* The first packet in ack list */ uint32_t previousPacket; /* Previous packet recv'd (obsolete) */ uint32_t serial; /* # of packet that prompted the ack */ uint8_t reason; /* Reason for acknowledgement */ uint8_t nAcks; /* Number of acknowledgements */ uint8_t acks[RX_MAXACKS]; /* Up to RX_MAXACKS acknowledgements */ }; /* * Values for the acks array */ #define RX_ACK_TYPE_NACK 0 /* Don't have this packet */ #define RX_ACK_TYPE_ACK 1 /* I have this packet */ static const struct tok rx_types[] = { { RX_PACKET_TYPE_DATA, "data" }, { RX_PACKET_TYPE_ACK, "ack" }, { RX_PACKET_TYPE_BUSY, "busy" }, { RX_PACKET_TYPE_ABORT, "abort" }, { RX_PACKET_TYPE_ACKALL, "ackall" }, { RX_PACKET_TYPE_CHALLENGE, "challenge" }, { RX_PACKET_TYPE_RESPONSE, "response" }, { RX_PACKET_TYPE_DEBUG, "debug" }, { RX_PACKET_TYPE_PARAMS, "params" }, { RX_PACKET_TYPE_VERSION, "version" }, { 0, NULL }, }; static const struct double_tok { int flag; /* Rx flag */ int packetType; /* Packet type */ const char *s; /* Flag string */ } rx_flags[] = { { RX_CLIENT_INITIATED, 0, "client-init" }, { RX_REQUEST_ACK, 0, "req-ack" }, { RX_LAST_PACKET, 0, "last-pckt" }, { RX_MORE_PACKETS, 0, "more-pckts" }, { RX_FREE_PACKET, 0, "free-pckt" }, { RX_SLOW_START_OK, RX_PACKET_TYPE_ACK, "slow-start" }, { RX_JUMBO_PACKET, RX_PACKET_TYPE_DATA, "jumbogram" } }; static const struct tok fs_req[] = { { 130, "fetch-data" }, { 131, "fetch-acl" }, { 132, "fetch-status" }, { 133, "store-data" }, { 134, "store-acl" }, { 135, "store-status" }, { 136, "remove-file" }, { 137, "create-file" }, { 138, "rename" }, { 139, "symlink" }, { 140, "link" }, { 141, "makedir" }, { 142, "rmdir" }, { 143, "oldsetlock" }, { 144, "oldextlock" }, { 145, "oldrellock" }, { 146, "get-stats" }, { 147, "give-cbs" }, { 148, "get-vlinfo" }, { 149, "get-vlstats" }, { 150, "set-vlstats" }, { 151, "get-rootvl" }, { 152, "check-token" }, { 153, "get-time" }, { 154, "nget-vlinfo" }, { 155, "bulk-stat" }, { 156, "setlock" }, { 157, "extlock" }, { 158, "rellock" }, { 159, "xstat-ver" }, { 160, "get-xstat" }, { 161, "dfs-lookup" }, { 162, "dfs-flushcps" }, { 163, "dfs-symlink" }, { 220, "residency" }, { 65536, "inline-bulk-status" }, { 65537, "fetch-data-64" }, { 65538, "store-data-64" }, { 65539, "give-up-all-cbs" }, { 65540, "get-caps" }, { 65541, "cb-rx-conn-addr" }, { 0, NULL }, }; static const struct tok cb_req[] = { { 204, "callback" }, { 205, "initcb" }, { 206, "probe" }, { 207, "getlock" }, { 208, "getce" }, { 209, "xstatver" }, { 210, "getxstat" }, { 211, "initcb2" }, { 212, "whoareyou" }, { 213, "initcb3" }, { 214, "probeuuid" }, { 215, "getsrvprefs" }, { 216, "getcellservdb" }, { 217, "getlocalcell" }, { 218, "getcacheconf" }, { 65536, "getce64" }, { 65537, "getcellbynum" }, { 65538, "tellmeaboutyourself" }, { 0, NULL }, }; static const struct tok pt_req[] = { { 500, "new-user" }, { 501, "where-is-it" }, { 502, "dump-entry" }, { 503, "add-to-group" }, { 504, "name-to-id" }, { 505, "id-to-name" }, { 506, "delete" }, { 507, "remove-from-group" }, { 508, "get-cps" }, { 509, "new-entry" }, { 510, "list-max" }, { 511, "set-max" }, { 512, "list-entry" }, { 513, "change-entry" }, { 514, "list-elements" }, { 515, "same-mbr-of" }, { 516, "set-fld-sentry" }, { 517, "list-owned" }, { 518, "get-cps2" }, { 519, "get-host-cps" }, { 520, "update-entry" }, { 521, "list-entries" }, { 530, "list-super-groups" }, { 0, NULL }, }; static const struct tok vldb_req[] = { { 501, "create-entry" }, { 502, "delete-entry" }, { 503, "get-entry-by-id" }, { 504, "get-entry-by-name" }, { 505, "get-new-volume-id" }, { 506, "replace-entry" }, { 507, "update-entry" }, { 508, "setlock" }, { 509, "releaselock" }, { 510, "list-entry" }, { 511, "list-attrib" }, { 512, "linked-list" }, { 513, "get-stats" }, { 514, "probe" }, { 515, "get-addrs" }, { 516, "change-addr" }, { 517, "create-entry-n" }, { 518, "get-entry-by-id-n" }, { 519, "get-entry-by-name-n" }, { 520, "replace-entry-n" }, { 521, "list-entry-n" }, { 522, "list-attrib-n" }, { 523, "linked-list-n" }, { 524, "update-entry-by-name" }, { 525, "create-entry-u" }, { 526, "get-entry-by-id-u" }, { 527, "get-entry-by-name-u" }, { 528, "replace-entry-u" }, { 529, "list-entry-u" }, { 530, "list-attrib-u" }, { 531, "linked-list-u" }, { 532, "regaddr" }, { 533, "get-addrs-u" }, { 534, "list-attrib-n2" }, { 0, NULL }, }; static const struct tok kauth_req[] = { { 1, "auth-old" }, { 21, "authenticate" }, { 22, "authenticate-v2" }, { 2, "change-pw" }, { 3, "get-ticket-old" }, { 23, "get-ticket" }, { 4, "set-pw" }, { 5, "set-fields" }, { 6, "create-user" }, { 7, "delete-user" }, { 8, "get-entry" }, { 9, "list-entry" }, { 10, "get-stats" }, { 11, "debug" }, { 12, "get-pw" }, { 13, "get-random-key" }, { 14, "unlock" }, { 15, "lock-status" }, { 0, NULL }, }; static const struct tok vol_req[] = { { 100, "create-volume" }, { 101, "delete-volume" }, { 102, "restore" }, { 103, "forward" }, { 104, "end-trans" }, { 105, "clone" }, { 106, "set-flags" }, { 107, "get-flags" }, { 108, "trans-create" }, { 109, "dump" }, { 110, "get-nth-volume" }, { 111, "set-forwarding" }, { 112, "get-name" }, { 113, "get-status" }, { 114, "sig-restore" }, { 115, "list-partitions" }, { 116, "list-volumes" }, { 117, "set-id-types" }, { 118, "monitor" }, { 119, "partition-info" }, { 120, "reclone" }, { 121, "list-one-volume" }, { 122, "nuke" }, { 123, "set-date" }, { 124, "x-list-volumes" }, { 125, "x-list-one-volume" }, { 126, "set-info" }, { 127, "x-list-partitions" }, { 128, "forward-multiple" }, { 65536, "convert-ro" }, { 65537, "get-size" }, { 65538, "dump-v2" }, { 0, NULL }, }; static const struct tok bos_req[] = { { 80, "create-bnode" }, { 81, "delete-bnode" }, { 82, "set-status" }, { 83, "get-status" }, { 84, "enumerate-instance" }, { 85, "get-instance-info" }, { 86, "get-instance-parm" }, { 87, "add-superuser" }, { 88, "delete-superuser" }, { 89, "list-superusers" }, { 90, "list-keys" }, { 91, "add-key" }, { 92, "delete-key" }, { 93, "set-cell-name" }, { 94, "get-cell-name" }, { 95, "get-cell-host" }, { 96, "add-cell-host" }, { 97, "delete-cell-host" }, { 98, "set-t-status" }, { 99, "shutdown-all" }, { 100, "restart-all" }, { 101, "startup-all" }, { 102, "set-noauth-flag" }, { 103, "re-bozo" }, { 104, "restart" }, { 105, "start-bozo-install" }, { 106, "uninstall" }, { 107, "get-dates" }, { 108, "exec" }, { 109, "prune" }, { 110, "set-restart-time" }, { 111, "get-restart-time" }, { 112, "start-bozo-log" }, { 113, "wait-all" }, { 114, "get-instance-strings" }, { 115, "get-restricted" }, { 116, "set-restricted" }, { 0, NULL }, }; static const struct tok ubik_req[] = { { 10000, "vote-beacon" }, { 10001, "vote-debug-old" }, { 10002, "vote-sdebug-old" }, { 10003, "vote-getsyncsite" }, { 10004, "vote-debug" }, { 10005, "vote-sdebug" }, { 10006, "vote-xdebug" }, { 10007, "vote-xsdebug" }, { 20000, "disk-begin" }, { 20001, "disk-commit" }, { 20002, "disk-lock" }, { 20003, "disk-write" }, { 20004, "disk-getversion" }, { 20005, "disk-getfile" }, { 20006, "disk-sendfile" }, { 20007, "disk-abort" }, { 20008, "disk-releaselocks" }, { 20009, "disk-truncate" }, { 20010, "disk-probe" }, { 20011, "disk-writev" }, { 20012, "disk-interfaceaddr" }, { 20013, "disk-setversion" }, { 0, NULL }, }; #define VOTE_LOW 10000 #define VOTE_HIGH 10007 #define DISK_LOW 20000 #define DISK_HIGH 20013 static const struct tok cb_types[] = { { 1, "exclusive" }, { 2, "shared" }, { 3, "dropped" }, { 0, NULL }, }; static const struct tok ubik_lock_types[] = { { 1, "read" }, { 2, "write" }, { 3, "wait" }, { 0, NULL }, }; static const char *voltype[] = { "read-write", "read-only", "backup" }; static const struct tok afs_fs_errors[] = { { 101, "salvage volume" }, { 102, "no such vnode" }, { 103, "no such volume" }, { 104, "volume exist" }, { 105, "no service" }, { 106, "volume offline" }, { 107, "voline online" }, { 108, "diskfull" }, { 109, "diskquota exceeded" }, { 110, "volume busy" }, { 111, "volume moved" }, { 112, "AFS IO error" }, { 0xffffff9c, "restarting fileserver" }, /* -100, sic! */ { 0, NULL } }; /* * Reasons for acknowledging a packet */ static const struct tok rx_ack_reasons[] = { { 1, "ack requested" }, { 2, "duplicate packet" }, { 3, "out of sequence" }, { 4, "exceeds window" }, { 5, "no buffer space" }, { 6, "ping" }, { 7, "ping response" }, { 8, "delay" }, { 9, "idle" }, { 0, NULL }, }; /* * Cache entries we keep around so we can figure out the RX opcode * numbers for replies. This allows us to make sense of RX reply packets. */ struct rx_cache_entry { uint32_t callnum; /* Call number (net order) */ struct in_addr client; /* client IP address (net order) */ struct in_addr server; /* server IP address (net order) */ int dport; /* server port (host order) */ u_short serviceId; /* Service identifier (net order) */ uint32_t opcode; /* RX opcode (host order) */ }; #define RX_CACHE_SIZE 64 static struct rx_cache_entry rx_cache[RX_CACHE_SIZE]; static int rx_cache_next = 0; static int rx_cache_hint = 0; static void rx_cache_insert(netdissect_options *, const u_char *, const struct ip *, int); static int rx_cache_find(const struct rx_header *, const struct ip *, int, int32_t *); static void fs_print(netdissect_options *, const u_char *, int); static void fs_reply_print(netdissect_options *, const u_char *, int, int32_t); static void acl_print(netdissect_options *, u_char *, int, u_char *); static void cb_print(netdissect_options *, const u_char *, int); static void cb_reply_print(netdissect_options *, const u_char *, int, int32_t); static void prot_print(netdissect_options *, const u_char *, int); static void prot_reply_print(netdissect_options *, const u_char *, int, int32_t); static void vldb_print(netdissect_options *, const u_char *, int); static void vldb_reply_print(netdissect_options *, const u_char *, int, int32_t); static void kauth_print(netdissect_options *, const u_char *, int); static void kauth_reply_print(netdissect_options *, const u_char *, int, int32_t); static void vol_print(netdissect_options *, const u_char *, int); static void vol_reply_print(netdissect_options *, const u_char *, int, int32_t); static void bos_print(netdissect_options *, const u_char *, int); static void bos_reply_print(netdissect_options *, const u_char *, int, int32_t); static void ubik_print(netdissect_options *, const u_char *); static void ubik_reply_print(netdissect_options *, const u_char *, int, int32_t); static void rx_ack_print(netdissect_options *, const u_char *, int); static int is_ubik(uint32_t); /* * Handle the rx-level packet. See if we know what port it's going to so * we can peek at the afs call inside */ void rx_print(netdissect_options *ndo, register const u_char *bp, int length, int sport, int dport, const u_char *bp2) { register const struct rx_header *rxh; int i; int32_t opcode; if (ndo->ndo_snapend - bp < (int)sizeof (struct rx_header)) { ND_PRINT((ndo, " [|rx] (%d)", length)); return; } rxh = (const struct rx_header *) bp; ND_PRINT((ndo, " rx %s", tok2str(rx_types, "type %d", rxh->type))); if (ndo->ndo_vflag) { int firstflag = 0; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, " cid %08x call# %d", (int) EXTRACT_32BITS(&rxh->cid), (int) EXTRACT_32BITS(&rxh->callNumber))); ND_PRINT((ndo, " seq %d ser %d", (int) EXTRACT_32BITS(&rxh->seq), (int) EXTRACT_32BITS(&rxh->serial))); if (ndo->ndo_vflag > 2) ND_PRINT((ndo, " secindex %d serviceid %hu", (int) rxh->securityIndex, EXTRACT_16BITS(&rxh->serviceId))); if (ndo->ndo_vflag > 1) for (i = 0; i < NUM_RX_FLAGS; i++) { if (rxh->flags & rx_flags[i].flag && (!rx_flags[i].packetType || rxh->type == rx_flags[i].packetType)) { if (!firstflag) { firstflag = 1; ND_PRINT((ndo, " ")); } else { ND_PRINT((ndo, ",")); } ND_PRINT((ndo, "<%s>", rx_flags[i].s)); } } } /* * Try to handle AFS calls that we know about. Check the destination * port and make sure it's a data packet. Also, make sure the * seq number is 1 (because otherwise it's a continuation packet, * and we can't interpret that). Also, seems that reply packets * do not have the client-init flag set, so we check for that * as well. */ if (rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1 && rxh->flags & RX_CLIENT_INITIATED) { /* * Insert this call into the call cache table, so we * have a chance to print out replies */ rx_cache_insert(ndo, bp, (const struct ip *) bp2, dport); switch (dport) { case FS_RX_PORT: /* AFS file service */ fs_print(ndo, bp, length); break; case CB_RX_PORT: /* AFS callback service */ cb_print(ndo, bp, length); break; case PROT_RX_PORT: /* AFS protection service */ prot_print(ndo, bp, length); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_print(ndo, bp, length); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_print(ndo, bp, length); break; case VOL_RX_PORT: /* AFS Volume service */ vol_print(ndo, bp, length); break; case BOS_RX_PORT: /* AFS BOS service */ bos_print(ndo, bp, length); break; default: ; } /* * If it's a reply (client-init is _not_ set, but seq is one) * then look it up in the cache. If we find it, call the reply * printing functions Note that we handle abort packets here, * because printing out the return code can be useful at times. */ } else if (((rxh->type == RX_PACKET_TYPE_DATA && EXTRACT_32BITS(&rxh->seq) == 1) || rxh->type == RX_PACKET_TYPE_ABORT) && (rxh->flags & RX_CLIENT_INITIATED) == 0 && rx_cache_find(rxh, (const struct ip *) bp2, sport, &opcode)) { switch (sport) { case FS_RX_PORT: /* AFS file service */ fs_reply_print(ndo, bp, length, opcode); break; case CB_RX_PORT: /* AFS callback service */ cb_reply_print(ndo, bp, length, opcode); break; case PROT_RX_PORT: /* AFS PT service */ prot_reply_print(ndo, bp, length, opcode); break; case VLDB_RX_PORT: /* AFS VLDB service */ vldb_reply_print(ndo, bp, length, opcode); break; case KAUTH_RX_PORT: /* AFS Kerberos auth service */ kauth_reply_print(ndo, bp, length, opcode); break; case VOL_RX_PORT: /* AFS Volume service */ vol_reply_print(ndo, bp, length, opcode); break; case BOS_RX_PORT: /* AFS BOS service */ bos_reply_print(ndo, bp, length, opcode); break; default: ; } /* * If it's an RX ack packet, then use the appropriate ack decoding * function (there isn't any service-specific information in the * ack packet, so we can use one for all AFS services) */ } else if (rxh->type == RX_PACKET_TYPE_ACK) rx_ack_print(ndo, bp, length); ND_PRINT((ndo, " (%d)", length)); } /* * Insert an entry into the cache. Taken from print-nfs.c */ static void rx_cache_insert(netdissect_options *ndo, const u_char *bp, const struct ip *ip, int dport) { struct rx_cache_entry *rxent; const struct rx_header *rxh = (const struct rx_header *) bp; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) return; rxent = &rx_cache[rx_cache_next]; if (++rx_cache_next >= RX_CACHE_SIZE) rx_cache_next = 0; rxent->callnum = EXTRACT_32BITS(&rxh->callNumber); UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t)); UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t)); rxent->dport = dport; rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId); rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header)); } /* * Lookup an entry in the cache. Also taken from print-nfs.c * * Note that because this is a reply, we're looking at the _source_ * port. */ static int rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport, int32_t *opcode) { int i; struct rx_cache_entry *rxent; uint32_t clip; uint32_t sip; UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t)); UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t)); /* Start the search where we last left off */ i = rx_cache_hint; do { rxent = &rx_cache[i]; if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) && rxent->client.s_addr == clip && rxent->server.s_addr == sip && rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) && rxent->dport == sport) { /* We got a match! */ rx_cache_hint = i; *opcode = rxent->opcode; return(1); } if (++i >= RX_CACHE_SIZE) i = 0; } while (i != rx_cache_hint); /* Our search failed */ return(0); } /* * These extrememly grody macros handle the printing of various AFS stuff. */ #define FIDOUT() { unsigned long n1, n2, n3; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \ n1 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n2 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n3 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " fid %d/%d/%d", (int) n1, (int) n2, (int) n3)); \ } #define STROUT(MAX) { unsigned int _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = EXTRACT_32BITS(bp); \ if (_i > (MAX)) \ goto trunc; \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " \"")); \ if (fn_printn(ndo, bp, _i, ndo->ndo_snapend)) \ goto trunc; \ ND_PRINT((ndo, "\"")); \ bp += ((_i + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t); \ } #define INTOUT() { int _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = (int) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %d", _i)); \ } #define UINTOUT() { unsigned long _i; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _i = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %lu", _i)); \ } #define UINT64OUT() { uint64_t _i; \ ND_TCHECK2(bp[0], sizeof(uint64_t)); \ _i = EXTRACT_64BITS(bp); \ bp += sizeof(uint64_t); \ ND_PRINT((ndo, " %" PRIu64, _i)); \ } #define DATEOUT() { time_t _t; struct tm *tm; char str[256]; \ ND_TCHECK2(bp[0], sizeof(int32_t)); \ _t = (time_t) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ tm = localtime(&_t); \ strftime(str, 256, "%Y/%m/%d %H:%M:%S", tm); \ ND_PRINT((ndo, " %s", str)); \ } #define STOREATTROUT() { unsigned long mask, _i; \ ND_TCHECK2(bp[0], (sizeof(int32_t)*6)); \ mask = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask) ND_PRINT((ndo, " StoreStatus")); \ if (mask & 1) { ND_PRINT((ndo, " date")); DATEOUT(); } \ else bp += sizeof(int32_t); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 2) ND_PRINT((ndo, " owner %lu", _i)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 4) ND_PRINT((ndo, " group %lu", _i)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 8) ND_PRINT((ndo, " mode %lo", _i & 07777)); \ _i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); \ if (mask & 16) ND_PRINT((ndo, " segsize %lu", _i)); \ /* undocumented in 3.3 docu */ \ if (mask & 1024) ND_PRINT((ndo, " fsync")); \ } #define UBIK_VERSIONOUT() {int32_t epoch; int32_t counter; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 2); \ epoch = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ counter = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " %d.%d", epoch, counter)); \ } #define AFSUUIDOUT() {uint32_t temp; int _i; \ ND_TCHECK2(bp[0], 11*sizeof(uint32_t)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, " %08x", temp)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%04x", temp)); \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%04x", temp)); \ for (_i = 0; _i < 8; _i++) { \ temp = EXTRACT_32BITS(bp); \ bp += sizeof(uint32_t); \ ND_PRINT((ndo, "%02x", (unsigned char) temp)); \ } \ } /* * This is the sickest one of all */ #define VECOUT(MAX) { u_char *sp; \ u_char s[AFSNAMEMAX]; \ int k; \ if ((MAX) + 1 > sizeof(s)) \ goto trunc; \ ND_TCHECK2(bp[0], (MAX) * sizeof(int32_t)); \ sp = s; \ for (k = 0; k < (MAX); k++) { \ *sp++ = (u_char) EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ } \ s[(MAX)] = '\0'; \ ND_PRINT((ndo, " \"")); \ fn_print(ndo, s, NULL); \ ND_PRINT((ndo, "\"")); \ } #define DESTSERVEROUT() { unsigned long n1, n2, n3; \ ND_TCHECK2(bp[0], sizeof(int32_t) * 3); \ n1 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n2 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ n3 = EXTRACT_32BITS(bp); \ bp += sizeof(int32_t); \ ND_PRINT((ndo, " server %d:%d:%d", (int) n1, (int) n2, (int) n3)); \ } /* * Handle calls to the AFS file service (fs) */ static void fs_print(netdissect_options *ndo, register const u_char *bp, int length) { int fs_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afsint.xg */ fs_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " fs call %s", tok2str(fs_req, "op#%d", fs_op))); /* * Print out arguments to some of the AFS calls. This stuff is * all from afsint.xg */ bp += sizeof(struct rx_header) + 4; /* * Sigh. This is gross. Ritchie forgive me. */ switch (fs_op) { case 130: /* Fetch data */ FIDOUT(); ND_PRINT((ndo, " offset")); UINTOUT(); ND_PRINT((ndo, " length")); UINTOUT(); break; case 131: /* Fetch ACL */ case 132: /* Fetch Status */ case 143: /* Old set lock */ case 144: /* Old extend lock */ case 145: /* Old release lock */ case 156: /* Set lock */ case 157: /* Extend lock */ case 158: /* Release lock */ FIDOUT(); break; case 135: /* Store status */ FIDOUT(); STOREATTROUT(); break; case 133: /* Store data */ FIDOUT(); STOREATTROUT(); ND_PRINT((ndo, " offset")); UINTOUT(); ND_PRINT((ndo, " length")); UINTOUT(); ND_PRINT((ndo, " flen")); UINTOUT(); break; case 134: /* Store ACL */ { char a[AFSOPAQUEMAX+1]; FIDOUT(); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); i = min(AFSOPAQUEMAX, i); strncpy(a, (const char *) bp, i); a[i] = '\0'; acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i); break; } case 137: /* Create file */ case 141: /* MakeDir */ FIDOUT(); STROUT(AFSNAMEMAX); STOREATTROUT(); break; case 136: /* Remove file */ case 142: /* Remove directory */ FIDOUT(); STROUT(AFSNAMEMAX); break; case 138: /* Rename file */ ND_PRINT((ndo, " old")); FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " new")); FIDOUT(); STROUT(AFSNAMEMAX); break; case 139: /* Symlink */ FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " link to")); STROUT(AFSNAMEMAX); break; case 140: /* Link */ FIDOUT(); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " link to")); FIDOUT(); break; case 148: /* Get volume info */ STROUT(AFSNAMEMAX); break; case 149: /* Get volume stats */ case 150: /* Set volume stats */ ND_PRINT((ndo, " volid")); UINTOUT(); break; case 154: /* New get volume info */ ND_PRINT((ndo, " volname")); STROUT(AFSNAMEMAX); break; case 155: /* Bulk stat */ case 65536: /* Inline bulk stat */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { FIDOUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); break; } case 65537: /* Fetch data 64 */ FIDOUT(); ND_PRINT((ndo, " offset")); UINT64OUT(); ND_PRINT((ndo, " length")); UINT64OUT(); break; case 65538: /* Store data 64 */ FIDOUT(); STOREATTROUT(); ND_PRINT((ndo, " offset")); UINT64OUT(); ND_PRINT((ndo, " length")); UINT64OUT(); ND_PRINT((ndo, " flen")); UINT64OUT(); break; case 65541: /* CallBack rx conn address */ ND_PRINT((ndo, " addr")); UINTOUT(); default: ; } return; trunc: ND_PRINT((ndo, " [|fs]")); } /* * Handle replies to the AFS file service */ static void fs_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { unsigned long i; const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afsint.xg */ ND_PRINT((ndo, " fs reply %s", tok2str(fs_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) { switch (opcode) { case 131: /* Fetch ACL */ { char a[AFSOPAQUEMAX+1]; ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); i = min(AFSOPAQUEMAX, i); strncpy(a, (const char *) bp, i); a[i] = '\0'; acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i); break; } case 137: /* Create file */ case 141: /* MakeDir */ ND_PRINT((ndo, " new")); FIDOUT(); break; case 151: /* Get root volume */ ND_PRINT((ndo, " root volume")); STROUT(AFSNAMEMAX); break; case 153: /* Get time */ DATEOUT(); break; default: ; } } else if (rxh->type == RX_PACKET_TYPE_ABORT) { /* * Otherwise, just print out the return code */ ND_TCHECK2(bp[0], sizeof(int32_t)); i = (int) EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " error %s", tok2str(afs_fs_errors, "#%d", i))); } else { ND_PRINT((ndo, " strange fs reply of type %d", rxh->type)); } return; trunc: ND_PRINT((ndo, " [|fs]")); } /* * Print out an AFS ACL string. An AFS ACL is a string that has the * following format: * * <positive> <negative> * <uid1> <aclbits1> * .... * * "positive" and "negative" are integers which contain the number of * positive and negative ACL's in the string. The uid/aclbits pair are * ASCII strings containing the UID/PTS record and and a ascii number * representing a logical OR of all the ACL permission bits */ static void acl_print(netdissect_options *ndo, u_char *s, int maxsize, u_char *end) { int pos, neg, acl; int n, i; char *user; char fmt[1024]; if ((user = (char *)malloc(maxsize)) == NULL) return; if (sscanf((char *) s, "%d %d\n%n", &pos, &neg, &n) != 2) goto finish; s += n; if (s > end) goto finish; /* * This wacky order preserves the order used by the "fs" command */ #define ACLOUT(acl) \ ND_PRINT((ndo, "%s%s%s%s%s%s%s", \ acl & PRSFS_READ ? "r" : "", \ acl & PRSFS_LOOKUP ? "l" : "", \ acl & PRSFS_INSERT ? "i" : "", \ acl & PRSFS_DELETE ? "d" : "", \ acl & PRSFS_WRITE ? "w" : "", \ acl & PRSFS_LOCK ? "k" : "", \ acl & PRSFS_ADMINISTER ? "a" : "")); for (i = 0; i < pos; i++) { snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1); if (sscanf((char *) s, fmt, user, &acl, &n) != 2) goto finish; s += n; ND_PRINT((ndo, " +{")); fn_print(ndo, (u_char *)user, NULL); ND_PRINT((ndo, " ")); ACLOUT(acl); ND_PRINT((ndo, "}")); if (s > end) goto finish; } for (i = 0; i < neg; i++) { snprintf(fmt, sizeof(fmt), "%%%ds %%d\n%%n", maxsize - 1); if (sscanf((char *) s, fmt, user, &acl, &n) != 2) goto finish; s += n; ND_PRINT((ndo, " -{")); fn_print(ndo, (u_char *)user, NULL); ND_PRINT((ndo, " ")); ACLOUT(acl); ND_PRINT((ndo, "}")); if (s > end) goto finish; } finish: free(user); return; } #undef ACLOUT /* * Handle calls to the AFS callback service */ static void cb_print(netdissect_options *ndo, register const u_char *bp, int length) { int cb_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ cb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " cb call %s", tok2str(cb_req, "op#%d", cb_op))); bp += sizeof(struct rx_header) + 4; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ switch (cb_op) { case 204: /* Callback */ { unsigned long j, t; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { FIDOUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); ND_TCHECK_32BITS(bp); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (j != 0) ND_PRINT((ndo, ";")); for (i = 0; i < j; i++) { ND_PRINT((ndo, " ver")); INTOUT(); ND_PRINT((ndo, " expires")); DATEOUT(); ND_TCHECK2(bp[0], 4); t = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(cb_types, "type %d", t); } break; } case 214: { ND_PRINT((ndo, " afsuuid")); AFSUUIDOUT(); break; } default: ; } return; trunc: ND_PRINT((ndo, " [|cb]")); } /* * Handle replies to the AFS Callback Service */ static void cb_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from fsint/afscbint.xg */ ND_PRINT((ndo, " cb reply %s", tok2str(cb_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 213: /* InitCallBackState3 */ AFSUUIDOUT(); break; default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|cb]")); } /* * Handle calls to the AFS protection database server */ static void prot_print(netdissect_options *ndo, register const u_char *bp, int length) { unsigned long i; int pt_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from ptserver/ptint.xg */ pt_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " pt")); if (is_ubik(pt_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(pt_req, "op#%d", pt_op))); /* * Decode some of the arguments to the PT calls */ bp += sizeof(struct rx_header) + 4; switch (pt_op) { case 500: /* I New User */ STROUT(PRNAMEMAX); ND_PRINT((ndo, " id")); INTOUT(); ND_PRINT((ndo, " oldid")); INTOUT(); break; case 501: /* Where is it */ case 506: /* Delete */ case 508: /* Get CPS */ case 512: /* List entry */ case 514: /* List elements */ case 517: /* List owned */ case 518: /* Get CPS2 */ case 519: /* Get host CPS */ case 530: /* List super groups */ ND_PRINT((ndo, " id")); INTOUT(); break; case 502: /* Dump entry */ ND_PRINT((ndo, " pos")); INTOUT(); break; case 503: /* Add to group */ case 507: /* Remove from group */ case 515: /* Is a member of? */ ND_PRINT((ndo, " uid")); INTOUT(); ND_PRINT((ndo, " gid")); INTOUT(); break; case 504: /* Name to ID */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); /* * Who designed this chicken-shit protocol? * * Each character is stored as a 32-bit * integer! */ for (i = 0; i < j; i++) { VECOUT(PRNAMEMAX); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 505: /* Id to name */ { unsigned long j; ND_PRINT((ndo, " ids:")); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (j = 0; j < i; j++) INTOUT(); if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 509: /* New entry */ STROUT(PRNAMEMAX); ND_PRINT((ndo, " flag")); INTOUT(); ND_PRINT((ndo, " oid")); INTOUT(); break; case 511: /* Set max */ ND_PRINT((ndo, " id")); INTOUT(); ND_PRINT((ndo, " gflag")); INTOUT(); break; case 513: /* Change entry */ ND_PRINT((ndo, " id")); INTOUT(); STROUT(PRNAMEMAX); ND_PRINT((ndo, " oldid")); INTOUT(); ND_PRINT((ndo, " newid")); INTOUT(); break; case 520: /* Update entry */ ND_PRINT((ndo, " id")); INTOUT(); STROUT(PRNAMEMAX); break; default: ; } return; trunc: ND_PRINT((ndo, " [|pt]")); } /* * Handle replies to the AFS protection service */ static void prot_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; unsigned long i; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ptserver/ptint.xg. Check to see if it's a * Ubik call, however. */ ND_PRINT((ndo, " pt")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(pt_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 504: /* Name to ID */ { unsigned long j; ND_PRINT((ndo, " ids:")); ND_TCHECK2(bp[0], 4); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (j = 0; j < i; j++) INTOUT(); if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 505: /* ID to name */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); /* * Who designed this chicken-shit protocol? * * Each character is stored as a 32-bit * integer! */ for (i = 0; i < j; i++) { VECOUT(PRNAMEMAX); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 508: /* Get CPS */ case 514: /* List elements */ case 517: /* List owned */ case 518: /* Get CPS2 */ case 519: /* Get host CPS */ { unsigned long j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { INTOUT(); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 510: /* List max */ ND_PRINT((ndo, " maxuid")); INTOUT(); ND_PRINT((ndo, " maxgid")); INTOUT(); break; default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|pt]")); } /* * Handle calls to the AFS volume location database service */ static void vldb_print(netdissect_options *ndo, register const u_char *bp, int length) { int vldb_op; unsigned long i; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from vlserver/vldbint.xg */ vldb_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " vldb")); if (is_ubik(vldb_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(vldb_req, "op#%d", vldb_op))); /* * Decode some of the arguments to the VLDB calls */ bp += sizeof(struct rx_header) + 4; switch (vldb_op) { case 501: /* Create new volume */ case 517: /* Create entry N */ VECOUT(VLNAMEMAX); break; case 502: /* Delete entry */ case 503: /* Get entry by ID */ case 507: /* Update entry */ case 508: /* Set lock */ case 509: /* Release lock */ case 518: /* Get entry by ID N */ ND_PRINT((ndo, " volid")); INTOUT(); ND_TCHECK2(bp[0], sizeof(int32_t)); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (i <= 2) ND_PRINT((ndo, " type %s", voltype[i])); break; case 504: /* Get entry by name */ case 519: /* Get entry by name N */ case 524: /* Update entry by name */ case 527: /* Get entry by name U */ STROUT(VLNAMEMAX); break; case 505: /* Get new vol id */ ND_PRINT((ndo, " bump")); INTOUT(); break; case 506: /* Replace entry */ case 520: /* Replace entry N */ ND_PRINT((ndo, " volid")); INTOUT(); ND_TCHECK2(bp[0], sizeof(int32_t)); i = EXTRACT_32BITS(bp); bp += sizeof(int32_t); if (i <= 2) ND_PRINT((ndo, " type %s", voltype[i])); VECOUT(VLNAMEMAX); break; case 510: /* List entry */ case 521: /* List entry N */ ND_PRINT((ndo, " index")); INTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|vldb]")); } /* * Handle replies to the AFS volume location database service */ static void vldb_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; unsigned long i; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from vlserver/vldbint.xg. Check to see if it's a * Ubik call, however. */ ND_PRINT((ndo, " vldb")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(vldb_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 510: /* List entry */ ND_PRINT((ndo, " count")); INTOUT(); ND_PRINT((ndo, " nextindex")); INTOUT(); /*FALLTHROUGH*/ case 503: /* Get entry by id */ case 504: /* Get entry by name */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_TCHECK2(bp[0], sizeof(int32_t)); bp += sizeof(int32_t); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 8; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); if (i < nservers) ND_PRINT((ndo, " %s", intoa(((const struct in_addr *) bp)->s_addr))); bp += sizeof(int32_t); } ND_PRINT((ndo, " partitions")); for (i = 0; i < 8; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 8 * sizeof(int32_t)); bp += 8 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } break; case 505: /* Get new volume ID */ ND_PRINT((ndo, " newvol")); UINTOUT(); break; case 521: /* List entry */ case 529: /* List entry U */ ND_PRINT((ndo, " count")); INTOUT(); ND_PRINT((ndo, " nextindex")); INTOUT(); /*FALLTHROUGH*/ case 518: /* Get entry by ID N */ case 519: /* Get entry by name N */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); if (i < nservers) ND_PRINT((ndo, " %s", intoa(((const struct in_addr *) bp)->s_addr))); bp += sizeof(int32_t); } ND_PRINT((ndo, " partitions")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 13 * sizeof(int32_t)); bp += 13 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } break; case 526: /* Get entry by ID U */ case 527: /* Get entry by name U */ { unsigned long nservers, j; VECOUT(VLNAMEMAX); ND_PRINT((ndo, " numservers")); ND_TCHECK2(bp[0], sizeof(int32_t)); nservers = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " %lu", nservers)); ND_PRINT((ndo, " servers")); for (i = 0; i < 13; i++) { if (i < nservers) { ND_PRINT((ndo, " afsuuid")); AFSUUIDOUT(); } else { ND_TCHECK2(bp[0], 44); bp += 44; } } ND_TCHECK2(bp[0], 4 * 13); bp += 4 * 13; ND_PRINT((ndo, " partitions")); for (i = 0; i < 13; i++) { ND_TCHECK2(bp[0], sizeof(int32_t)); j = EXTRACT_32BITS(bp); if (i < nservers && j <= 26) ND_PRINT((ndo, " %c", 'a' + (int)j)); else if (i < nservers) ND_PRINT((ndo, " %lu", j)); bp += sizeof(int32_t); } ND_TCHECK2(bp[0], 13 * sizeof(int32_t)); bp += 13 * sizeof(int32_t); ND_PRINT((ndo, " rwvol")); UINTOUT(); ND_PRINT((ndo, " rovol")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); } default: ; } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|vldb]")); } /* * Handle calls to the AFS Kerberos Authentication service */ static void kauth_print(netdissect_options *ndo, register const u_char *bp, int length) { int kauth_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from kauth/kauth.rg */ kauth_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " kauth")); if (is_ubik(kauth_op)) { ubik_print(ndo, bp); return; } ND_PRINT((ndo, " call %s", tok2str(kauth_req, "op#%d", kauth_op))); /* * Decode some of the arguments to the KA calls */ bp += sizeof(struct rx_header) + 4; switch (kauth_op) { case 1: /* Authenticate old */ case 21: /* Authenticate */ case 22: /* Authenticate-V2 */ case 2: /* Change PW */ case 5: /* Set fields */ case 6: /* Create user */ case 7: /* Delete user */ case 8: /* Get entry */ case 14: /* Unlock */ case 15: /* Lock status */ ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); break; case 3: /* GetTicket-old */ case 23: /* GetTicket */ { int i; ND_PRINT((ndo, " kvno")); INTOUT(); ND_PRINT((ndo, " domain")); STROUT(KANAMEMAX); ND_TCHECK2(bp[0], sizeof(int32_t)); i = (int) EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_TCHECK2(bp[0], i); bp += i; ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); break; } case 4: /* Set Password */ ND_PRINT((ndo, " principal")); STROUT(KANAMEMAX); STROUT(KANAMEMAX); ND_PRINT((ndo, " kvno")); INTOUT(); break; case 12: /* Get password */ ND_PRINT((ndo, " name")); STROUT(KANAMEMAX); break; default: ; } return; trunc: ND_PRINT((ndo, " [|kauth]")); } /* * Handle replies to the AFS Kerberos Authentication Service */ static void kauth_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from kauth/kauth.rg */ ND_PRINT((ndo, " kauth")); if (is_ubik(opcode)) { ubik_reply_print(ndo, bp, length, opcode); return; } ND_PRINT((ndo, " reply %s", tok2str(kauth_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) /* Well, no, not really. Leave this for later */ ; else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|kauth]")); } /* * Handle calls to the AFS Volume location service */ static void vol_print(netdissect_options *ndo, register const u_char *bp, int length) { int vol_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ vol_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " vol call %s", tok2str(vol_req, "op#%d", vol_op))); bp += sizeof(struct rx_header) + 4; switch (vol_op) { case 100: /* Create volume */ ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " parent")); UINTOUT(); break; case 101: /* Delete volume */ case 107: /* Get flags */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 102: /* Restore */ ND_PRINT((ndo, " totrans")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 103: /* Forward */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); DESTSERVEROUT(); ND_PRINT((ndo, " desttrans")); INTOUT(); break; case 104: /* End trans */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 105: /* Clone */ ND_PRINT((ndo, " trans")); UINTOUT(); ND_PRINT((ndo, " purgevol")); UINTOUT(); ND_PRINT((ndo, " newtype")); UINTOUT(); ND_PRINT((ndo, " newname")); STROUT(AFSNAMEMAX); break; case 106: /* Set flags */ ND_PRINT((ndo, " trans")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 108: /* Trans create */ ND_PRINT((ndo, " vol")); UINTOUT(); ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 109: /* Dump */ case 655537: /* Get size */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); break; case 110: /* Get n-th volume */ ND_PRINT((ndo, " index")); UINTOUT(); break; case 111: /* Set forwarding */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " newsite")); UINTOUT(); break; case 112: /* Get name */ case 113: /* Get status */ ND_PRINT((ndo, " tid")); break; case 114: /* Signal restore */ ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " pid")); UINTOUT(); ND_PRINT((ndo, " cloneid")); UINTOUT(); break; case 116: /* List volumes */ ND_PRINT((ndo, " partition")); UINTOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; case 117: /* Set id types */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " pid")); UINTOUT(); ND_PRINT((ndo, " clone")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); break; case 119: /* Partition info */ ND_PRINT((ndo, " name")); STROUT(AFSNAMEMAX); break; case 120: /* Reclone */ ND_PRINT((ndo, " tid")); UINTOUT(); break; case 121: /* List one volume */ case 122: /* Nuke volume */ case 124: /* Extended List volumes */ case 125: /* Extended List one volume */ case 65536: /* Convert RO to RW volume */ ND_PRINT((ndo, " partid")); UINTOUT(); ND_PRINT((ndo, " volid")); UINTOUT(); break; case 123: /* Set date */ ND_PRINT((ndo, " tid")); UINTOUT(); ND_PRINT((ndo, " date")); DATEOUT(); break; case 126: /* Set info */ ND_PRINT((ndo, " tid")); UINTOUT(); break; case 128: /* Forward multiple */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); { unsigned long i, j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { DESTSERVEROUT(); if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; case 65538: /* Dump version 2 */ ND_PRINT((ndo, " fromtrans")); UINTOUT(); ND_PRINT((ndo, " fromdate")); DATEOUT(); ND_PRINT((ndo, " flags")); UINTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|vol]")); } /* * Handle replies to the AFS Volume Service */ static void vol_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ ND_PRINT((ndo, " vol reply %s", tok2str(vol_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) { switch (opcode) { case 100: /* Create volume */ ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " trans")); UINTOUT(); break; case 104: /* End transaction */ UINTOUT(); break; case 105: /* Clone */ ND_PRINT((ndo, " newvol")); UINTOUT(); break; case 107: /* Get flags */ UINTOUT(); break; case 108: /* Transaction create */ ND_PRINT((ndo, " trans")); UINTOUT(); break; case 110: /* Get n-th volume */ ND_PRINT((ndo, " volume")); UINTOUT(); ND_PRINT((ndo, " partition")); UINTOUT(); break; case 112: /* Get name */ STROUT(AFSNAMEMAX); break; case 113: /* Get status */ ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " nextuniq")); UINTOUT(); ND_PRINT((ndo, " type")); UINTOUT(); ND_PRINT((ndo, " parentid")); UINTOUT(); ND_PRINT((ndo, " clone")); UINTOUT(); ND_PRINT((ndo, " backup")); UINTOUT(); ND_PRINT((ndo, " restore")); UINTOUT(); ND_PRINT((ndo, " maxquota")); UINTOUT(); ND_PRINT((ndo, " minquota")); UINTOUT(); ND_PRINT((ndo, " owner")); UINTOUT(); ND_PRINT((ndo, " create")); DATEOUT(); ND_PRINT((ndo, " access")); DATEOUT(); ND_PRINT((ndo, " update")); DATEOUT(); ND_PRINT((ndo, " expire")); DATEOUT(); ND_PRINT((ndo, " backup")); DATEOUT(); ND_PRINT((ndo, " copy")); DATEOUT(); break; case 115: /* Old list partitions */ break; case 116: /* List volumes */ case 121: /* List one volume */ { unsigned long i, j; ND_TCHECK2(bp[0], 4); j = EXTRACT_32BITS(bp); bp += sizeof(int32_t); for (i = 0; i < j; i++) { ND_PRINT((ndo, " name")); VECOUT(32); ND_PRINT((ndo, " volid")); UINTOUT(); ND_PRINT((ndo, " type")); bp += sizeof(int32_t) * 21; if (i != j - 1) ND_PRINT((ndo, ",")); } if (j == 0) ND_PRINT((ndo, " <none!>")); } break; default: ; } } else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|vol]")); } /* * Handle calls to the AFS BOS service */ static void bos_print(netdissect_options *ndo, register const u_char *bp, int length) { int bos_op; if (length <= (int)sizeof(struct rx_header)) return; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) { goto trunc; } /* * Print out the afs call we're invoking. The table used here was * gleaned from bozo/bosint.xg */ bos_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " bos call %s", tok2str(bos_req, "op#%d", bos_op))); /* * Decode some of the arguments to the BOS calls */ bp += sizeof(struct rx_header) + 4; switch (bos_op) { case 80: /* Create B node */ ND_PRINT((ndo, " type")); STROUT(BOSNAMEMAX); ND_PRINT((ndo, " instance")); STROUT(BOSNAMEMAX); break; case 81: /* Delete B node */ case 83: /* Get status */ case 85: /* Get instance info */ case 87: /* Add super user */ case 88: /* Delete super user */ case 93: /* Set cell name */ case 96: /* Add cell host */ case 97: /* Delete cell host */ case 104: /* Restart */ case 106: /* Uninstall */ case 108: /* Exec */ case 112: /* Getlog */ case 114: /* Get instance strings */ STROUT(BOSNAMEMAX); break; case 82: /* Set status */ case 98: /* Set T status */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " status")); INTOUT(); break; case 86: /* Get instance parm */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " num")); INTOUT(); break; case 84: /* Enumerate instance */ case 89: /* List super users */ case 90: /* List keys */ case 91: /* Add key */ case 92: /* Delete key */ case 95: /* Get cell host */ INTOUT(); break; case 105: /* Install */ STROUT(BOSNAMEMAX); ND_PRINT((ndo, " size")); INTOUT(); ND_PRINT((ndo, " flags")); INTOUT(); ND_PRINT((ndo, " date")); INTOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|bos]")); } /* * Handle replies to the AFS BOS Service */ static void bos_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length <= (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the afs call we're invoking. The table used here was * gleaned from volser/volint.xg */ ND_PRINT((ndo, " bos reply %s", tok2str(bos_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, interpret the response. */ if (rxh->type == RX_PACKET_TYPE_DATA) /* Well, no, not really. Leave this for later */ ; else { /* * Otherwise, just print out the return code */ ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|bos]")); } /* * Check to see if this is a Ubik opcode. */ static int is_ubik(uint32_t opcode) { if ((opcode >= VOTE_LOW && opcode <= VOTE_HIGH) || (opcode >= DISK_LOW && opcode <= DISK_HIGH)) return(1); else return(0); } /* * Handle Ubik opcodes to any one of the replicated database services */ static void ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ /* Every function that calls this function first makes a bounds check * for (sizeof(rx_header) + 4) bytes, so long as it remains this way * the line below will not over-read. */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no")); ND_PRINT((ndo, " votestart")); DATEOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, " site")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_TCHECK_32BITS(bp); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, "type %d", temp); break; case 20003: /* Write */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, " file")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " oldversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " newversion")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|ubik]")); } /* * Handle Ubik replies to any one of the replicated database services */ static void ubik_reply_print(netdissect_options *ndo, register const u_char *bp, int length, int32_t opcode) { const struct rx_header *rxh; if (length < (int)sizeof(struct rx_header)) return; rxh = (const struct rx_header *) bp; /* * Print out the ubik call we're invoking. This table was gleaned * from ubik/ubik_int.xg */ ND_PRINT((ndo, " ubik reply %s", tok2str(ubik_req, "op#%d", opcode))); bp += sizeof(struct rx_header); /* * If it was a data packet, print out the arguments to the Ubik calls */ if (rxh->type == RX_PACKET_TYPE_DATA) switch (opcode) { case 10000: /* Beacon */ ND_PRINT((ndo, " vote no")); break; case 20004: /* Get version */ ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; default: ; } /* * Otherwise, print out "yes" it it was a beacon packet (because * that's how yes votes are returned, go figure), otherwise * just print out the error code. */ else switch (opcode) { case 10000: /* Beacon */ ND_PRINT((ndo, " vote yes until")); DATEOUT(); break; default: ND_PRINT((ndo, " errcode")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|ubik]")); } /* * Handle RX ACK packets. */ static void rx_ack_print(netdissect_options *ndo, register const u_char *bp, int length) { const struct rx_ackPacket *rxa; int i, start, last; uint32_t firstPacket; if (length < (int)sizeof(struct rx_header)) return; bp += sizeof(struct rx_header); /* * This may seem a little odd .... the rx_ackPacket structure * contains an array of individual packet acknowledgements * (used for selective ack/nack), but since it's variable in size, * we don't want to truncate based on the size of the whole * rx_ackPacket structure. */ ND_TCHECK2(bp[0], sizeof(struct rx_ackPacket) - RX_MAXACKS); rxa = (const struct rx_ackPacket *) bp; bp += (sizeof(struct rx_ackPacket) - RX_MAXACKS); /* * Print out a few useful things from the ack packet structure */ if (ndo->ndo_vflag > 2) ND_PRINT((ndo, " bufspace %d maxskew %d", (int) EXTRACT_16BITS(&rxa->bufferSpace), (int) EXTRACT_16BITS(&rxa->maxSkew))); firstPacket = EXTRACT_32BITS(&rxa->firstPacket); ND_PRINT((ndo, " first %d serial %d reason %s", firstPacket, EXTRACT_32BITS(&rxa->serial), tok2str(rx_ack_reasons, "#%d", (int) rxa->reason))); /* * Okay, now we print out the ack array. The way _this_ works * is that we start at "first", and step through the ack array. * If we have a contiguous range of acks/nacks, try to * collapse them into a range. * * If you're really clever, you might have noticed that this * doesn't seem quite correct. Specifically, due to structure * padding, sizeof(struct rx_ackPacket) - RX_MAXACKS won't actually * yield the start of the ack array (because RX_MAXACKS is 255 * and the structure will likely get padded to a 2 or 4 byte * boundary). However, this is the way it's implemented inside * of AFS - the start of the extra fields are at * sizeof(struct rx_ackPacket) - RX_MAXACKS + nAcks, which _isn't_ * the exact start of the ack array. Sigh. That's why we aren't * using bp, but instead use rxa->acks[]. But nAcks gets added * to bp after this, so bp ends up at the right spot. Go figure. */ if (rxa->nAcks != 0) { ND_TCHECK2(bp[0], rxa->nAcks); /* * Sigh, this is gross, but it seems to work to collapse * ranges correctly. */ for (i = 0, start = last = -2; i < rxa->nAcks; i++) if (rxa->acks[i] == RX_ACK_TYPE_ACK) { /* * I figured this deserved _some_ explanation. * First, print "acked" and the packet seq * number if this is the first time we've * seen an acked packet. */ if (last == -2) { ND_PRINT((ndo, " acked %d", firstPacket + i)); start = i; } /* * Otherwise, if there is a skip in * the range (such as an nacked packet in * the middle of some acked packets), * then print the current packet number * seperated from the last number by * a comma. */ else if (last != i - 1) { ND_PRINT((ndo, ",%d", firstPacket + i)); start = i; } /* * We always set last to the value of * the last ack we saw. Conversely, start * is set to the value of the first ack * we saw in a range. */ last = i; /* * Okay, this bit a code gets executed when * we hit a nack ... in _this_ case we * want to print out the range of packets * that were acked, so we need to print * the _previous_ packet number seperated * from the first by a dash (-). Since we * already printed the first packet above, * just print the final packet. Don't * do this if there will be a single-length * range. */ } else if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); /* * So, what's going on here? We ran off the end of the * ack list, and if we got a range we need to finish it up. * So we need to determine if the last packet in the list * was an ack (if so, then last will be set to it) and * we need to see if the last range didn't start with the * last packet (because if it _did_, then that would mean * that the packet number has already been printed and * we don't need to print it again). */ if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); /* * Same as above, just without comments */ for (i = 0, start = last = -2; i < rxa->nAcks; i++) if (rxa->acks[i] == RX_ACK_TYPE_NACK) { if (last == -2) { ND_PRINT((ndo, " nacked %d", firstPacket + i)); start = i; } else if (last != i - 1) { ND_PRINT((ndo, ",%d", firstPacket + i)); start = i; } last = i; } else if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); if (last == i - 1 && start != last) ND_PRINT((ndo, "-%d", firstPacket + i - 1)); bp += rxa->nAcks; } /* * These are optional fields; depending on your version of AFS, * you may or may not see them */ #define TRUNCRET(n) if (ndo->ndo_snapend - bp + 1 <= n) return; if (ndo->ndo_vflag > 1) { TRUNCRET(4); ND_PRINT((ndo, " ifmtu")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " maxmtu")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " rwind")); INTOUT(); TRUNCRET(4); ND_PRINT((ndo, " maxpackets")); INTOUT(); } return; trunc: ND_PRINT((ndo, " [|ack]")); } #undef TRUNCRET
./CrossVul/dataset_final_sorted/CWE-125/c/bad_264_0
crossvul-cpp_data_bad_2685_0
/* * Copyright (C) 2000, Richard Sharpe * * This software may be distributed either under the terms of the * BSD-style license that accompanies tcpdump or under the GNU GPL * version 2 or later. * * print-beep.c * */ /* \summary: Blocks Extensible Exchange Protocol (BEEP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" /* Check for a string but not go beyond length * Return TRUE on match, FALSE otherwise * * Looks at the first few chars up to tl1 ... */ static int l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2) { if (tl1 > l2) return 0; return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0); } void beep_print(netdissect_options *ndo, const u_char *bp, u_int length) { if (l_strnstart("MSG", 4, (const char *)bp, length)) /* A REQuest */ ND_PRINT((ndo, " BEEP MSG")); else if (l_strnstart("RPY ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP RPY")); else if (l_strnstart("ERR ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ERR")); else if (l_strnstart("ANS ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ANS")); else if (l_strnstart("NUL ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP NUL")); else if (l_strnstart("SEQ ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP SEQ")); else if (l_strnstart("END", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP END")); else ND_PRINT((ndo, " BEEP (payload or undecoded)")); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2685_0
crossvul-cpp_data_good_615_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // riff.c // This module is a helper to the WavPack command-line programs to support WAV files // (both MS standard and rf64 varients). #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" #pragma pack(push,4) typedef struct { char ckID [4]; uint64_t chunkSize64; } CS64Chunk; typedef struct { uint64_t riffSize64, dataSize64, sampleCount64; uint32_t tableLength; } DS64Chunk; typedef struct { char ckID [4]; uint32_t ckSize; char junk [28]; } JunkChunk; #pragma pack(pop) #define CS64ChunkFormat "4D" #define DS64ChunkFormat "DDDL" #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); 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 (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1, table_length = 0; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; CS64Chunk cs64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); total_riff_bytes += table_length * sizeof (CS64Chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; ds64_chunk.tableLength = table_length; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } // this "table" is just a dummy placeholder for testing (normally not written) if (table_length) { strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID)); cs64_chunk.chunkSize64 = 12345678; WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); } // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } // again, this is normally not written except for testing while (table_length--) if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_615_0
crossvul-cpp_data_good_2730_0
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) * IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com> * DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net> */ /* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "af.h" #include "oui.h" #define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9) #define LLDP_EXTRACT_LEN(x) ((x)&0x01ff) /* * TLV type codes */ #define LLDP_END_TLV 0 #define LLDP_CHASSIS_ID_TLV 1 #define LLDP_PORT_ID_TLV 2 #define LLDP_TTL_TLV 3 #define LLDP_PORT_DESCR_TLV 4 #define LLDP_SYSTEM_NAME_TLV 5 #define LLDP_SYSTEM_DESCR_TLV 6 #define LLDP_SYSTEM_CAP_TLV 7 #define LLDP_MGMT_ADDR_TLV 8 #define LLDP_PRIVATE_TLV 127 static const struct tok lldp_tlv_values[] = { { LLDP_END_TLV, "End" }, { LLDP_CHASSIS_ID_TLV, "Chassis ID" }, { LLDP_PORT_ID_TLV, "Port ID" }, { LLDP_TTL_TLV, "Time to Live" }, { LLDP_PORT_DESCR_TLV, "Port Description" }, { LLDP_SYSTEM_NAME_TLV, "System Name" }, { LLDP_SYSTEM_DESCR_TLV, "System Description" }, { LLDP_SYSTEM_CAP_TLV, "System Capabilities" }, { LLDP_MGMT_ADDR_TLV, "Management Address" }, { LLDP_PRIVATE_TLV, "Organization specific" }, { 0, NULL} }; /* * Chassis ID subtypes */ #define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1 #define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2 #define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3 #define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4 #define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5 #define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6 #define LLDP_CHASSIS_LOCAL_SUBTYPE 7 static const struct tok lldp_chassis_subtype_values[] = { { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"}, { LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"}, { LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"}, { LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * Port ID subtypes */ #define LLDP_PORT_INTF_ALIAS_SUBTYPE 1 #define LLDP_PORT_PORT_COMP_SUBTYPE 2 #define LLDP_PORT_MAC_ADDR_SUBTYPE 3 #define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4 #define LLDP_PORT_INTF_NAME_SUBTYPE 5 #define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6 #define LLDP_PORT_LOCAL_SUBTYPE 7 static const struct tok lldp_port_subtype_values[] = { { LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"}, { LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"}, { LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"}, { LLDP_PORT_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * System Capabilities */ #define LLDP_CAP_OTHER (1 << 0) #define LLDP_CAP_REPEATER (1 << 1) #define LLDP_CAP_BRIDGE (1 << 2) #define LLDP_CAP_WLAN_AP (1 << 3) #define LLDP_CAP_ROUTER (1 << 4) #define LLDP_CAP_PHONE (1 << 5) #define LLDP_CAP_DOCSIS (1 << 6) #define LLDP_CAP_STATION_ONLY (1 << 7) static const struct tok lldp_cap_values[] = { { LLDP_CAP_OTHER, "Other"}, { LLDP_CAP_REPEATER, "Repeater"}, { LLDP_CAP_BRIDGE, "Bridge"}, { LLDP_CAP_WLAN_AP, "WLAN AP"}, { LLDP_CAP_ROUTER, "Router"}, { LLDP_CAP_PHONE, "Telephone"}, { LLDP_CAP_DOCSIS, "Docsis"}, { LLDP_CAP_STATION_ONLY, "Station Only"}, { 0, NULL} }; #define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2 #define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12 #define LLDP_PRIVATE_8021_SUBTYPE_EVB 13 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14 static const struct tok lldp_8021_subtype_values[] = { { LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"}, { LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"}, { LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"}, { LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"}, { LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"}, { LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"}, { 0, NULL} }; #define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1) #define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2) static const struct tok lldp_8021_port_protocol_id_values[] = { { LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"}, { LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1 #define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2 #define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3 #define LLDP_PRIVATE_8023_SUBTYPE_MTU 4 static const struct tok lldp_8023_subtype_values[] = { { LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"}, { LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"}, { LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"}, { LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"}, { 0, NULL} }; #define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1 #define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2 #define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3 #define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11 static const struct tok lldp_tia_subtype_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" }, { LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" }, { LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" }, { LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" }, { 0, NULL} }; #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1 #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2 static const struct tok lldp_tia_location_altitude_type_values[] = { { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"}, { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"}, { 0, NULL} }; /* ANSI/TIA-1057 - Annex B */ #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6 static const struct tok lldp_tia_location_lci_catype_values[] = { { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"}, { 0, NULL} }; static const struct tok lldp_tia_location_lci_what_values[] = { { 0, "location of DHCP server"}, { 1, "location of the network element believed to be closest to the client"}, { 2, "location of the client"}, { 0, NULL} }; /* * From RFC 3636 - dot3MauType */ #define LLDP_MAU_TYPE_UNKNOWN 0 #define LLDP_MAU_TYPE_AUI 1 #define LLDP_MAU_TYPE_10BASE_5 2 #define LLDP_MAU_TYPE_FOIRL 3 #define LLDP_MAU_TYPE_10BASE_2 4 #define LLDP_MAU_TYPE_10BASE_T 5 #define LLDP_MAU_TYPE_10BASE_FP 6 #define LLDP_MAU_TYPE_10BASE_FB 7 #define LLDP_MAU_TYPE_10BASE_FL 8 #define LLDP_MAU_TYPE_10BROAD36 9 #define LLDP_MAU_TYPE_10BASE_T_HD 10 #define LLDP_MAU_TYPE_10BASE_T_FD 11 #define LLDP_MAU_TYPE_10BASE_FL_HD 12 #define LLDP_MAU_TYPE_10BASE_FL_FD 13 #define LLDP_MAU_TYPE_100BASE_T4 14 #define LLDP_MAU_TYPE_100BASE_TX_HD 15 #define LLDP_MAU_TYPE_100BASE_TX_FD 16 #define LLDP_MAU_TYPE_100BASE_FX_HD 17 #define LLDP_MAU_TYPE_100BASE_FX_FD 18 #define LLDP_MAU_TYPE_100BASE_T2_HD 19 #define LLDP_MAU_TYPE_100BASE_T2_FD 20 #define LLDP_MAU_TYPE_1000BASE_X_HD 21 #define LLDP_MAU_TYPE_1000BASE_X_FD 22 #define LLDP_MAU_TYPE_1000BASE_LX_HD 23 #define LLDP_MAU_TYPE_1000BASE_LX_FD 24 #define LLDP_MAU_TYPE_1000BASE_SX_HD 25 #define LLDP_MAU_TYPE_1000BASE_SX_FD 26 #define LLDP_MAU_TYPE_1000BASE_CX_HD 27 #define LLDP_MAU_TYPE_1000BASE_CX_FD 28 #define LLDP_MAU_TYPE_1000BASE_T_HD 29 #define LLDP_MAU_TYPE_1000BASE_T_FD 30 #define LLDP_MAU_TYPE_10GBASE_X 31 #define LLDP_MAU_TYPE_10GBASE_LX4 32 #define LLDP_MAU_TYPE_10GBASE_R 33 #define LLDP_MAU_TYPE_10GBASE_ER 34 #define LLDP_MAU_TYPE_10GBASE_LR 35 #define LLDP_MAU_TYPE_10GBASE_SR 36 #define LLDP_MAU_TYPE_10GBASE_W 37 #define LLDP_MAU_TYPE_10GBASE_EW 38 #define LLDP_MAU_TYPE_10GBASE_LW 39 #define LLDP_MAU_TYPE_10GBASE_SW 40 static const struct tok lldp_mau_types_values[] = { { LLDP_MAU_TYPE_UNKNOWN, "Unknown"}, { LLDP_MAU_TYPE_AUI, "AUI"}, { LLDP_MAU_TYPE_10BASE_5, "10BASE_5"}, { LLDP_MAU_TYPE_FOIRL, "FOIRL"}, { LLDP_MAU_TYPE_10BASE_2, "10BASE2"}, { LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"}, { LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"}, { LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"}, { LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"}, { LLDP_MAU_TYPE_10BROAD36, "10BROAD36"}, { LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"}, { LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"}, { LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"}, { LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"}, { LLDP_MAU_TYPE_100BASE_T4, "100BASET4"}, { LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"}, { LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"}, { LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"}, { LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"}, { LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"}, { LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"}, { LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"}, { LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"}, { LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"}, { LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"}, { LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"}, { LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"}, { LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"}, { LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"}, { LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"}, { LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"}, { LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"}, { LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"}, { LLDP_MAU_TYPE_10GBASE_R, "10GBASER"}, { LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"}, { LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"}, { LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"}, { LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"}, { LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"}, { LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"}, { LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"}, { 0, NULL} }; #define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0) #define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1) static const struct tok lldp_8023_autonegotiation_values[] = { { LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"}, { LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_TIA_CAPABILITY_MED (1 << 0) #define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1) #define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4) #define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5) static const struct tok lldp_tia_capabilities_values[] = { { LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"}, { LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"}, { LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"}, { LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"}, { 0, NULL} }; #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3 #define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4 static const struct tok lldp_tia_device_type_values[] = { { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"}, { LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"}, { 0, NULL} }; #define LLDP_TIA_APPLICATION_TYPE_VOICE 1 #define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4 #define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6 #define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8 static const struct tok lldp_tia_application_type_values[] = { { LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"}, { LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"}, { LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"}, { 0, NULL} }; #define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5) #define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6) #define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7) static const struct tok lldp_tia_network_policy_bits_values[] = { { LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"}, { LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"}, { LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"}, { 0, NULL} }; #define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1) #define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6) #define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f) #define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1 #define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2 #define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3 static const struct tok lldp_tia_location_data_format_values[] = { { LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"}, { 0, NULL} }; #define LLDP_TIA_LOCATION_DATUM_WGS_84 1 #define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2 #define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3 static const struct tok lldp_tia_location_datum_type_values[] = { { LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"}, { 0, NULL} }; #define LLDP_TIA_POWER_SOURCE_PSE 1 #define LLDP_TIA_POWER_SOURCE_LOCAL 2 #define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3 static const struct tok lldp_tia_power_source_values[] = { { LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"}, { LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"}, { LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"}, { 0, NULL} }; #define LLDP_TIA_POWER_PRIORITY_CRITICAL 1 #define LLDP_TIA_POWER_PRIORITY_HIGH 2 #define LLDP_TIA_POWER_PRIORITY_LOW 3 static const struct tok lldp_tia_power_priority_values[] = { { LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"}, { LLDP_TIA_POWER_PRIORITY_HIGH, "high"}, { LLDP_TIA_POWER_PRIORITY_LOW, "low"}, { 0, NULL} }; #define LLDP_TIA_POWER_VAL_MAX 1024 static const struct tok lldp_tia_inventory_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" }, { 0, NULL} }; /* * From RFC 3636 - ifMauAutoNegCapAdvertisedBits */ #define LLDP_MAU_PMD_OTHER (1 << 15) #define LLDP_MAU_PMD_10BASE_T (1 << 14) #define LLDP_MAU_PMD_10BASE_T_FD (1 << 13) #define LLDP_MAU_PMD_100BASE_T4 (1 << 12) #define LLDP_MAU_PMD_100BASE_TX (1 << 11) #define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10) #define LLDP_MAU_PMD_100BASE_T2 (1 << 9) #define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8) #define LLDP_MAU_PMD_FDXPAUSE (1 << 7) #define LLDP_MAU_PMD_FDXAPAUSE (1 << 6) #define LLDP_MAU_PMD_FDXSPAUSE (1 << 5) #define LLDP_MAU_PMD_FDXBPAUSE (1 << 4) #define LLDP_MAU_PMD_1000BASE_X (1 << 3) #define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2) #define LLDP_MAU_PMD_1000BASE_T (1 << 1) #define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0) static const struct tok lldp_pmd_capability_values[] = { { LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"}, { LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"}, { LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"}, { LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"}, { LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"}, { LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"}, { LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"}, { LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"}, { LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"}, { LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"}, { LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"}, { LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"}, { LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"}, { 0, NULL} }; #define LLDP_MDI_PORT_CLASS (1 << 0) #define LLDP_MDI_POWER_SUPPORT (1 << 1) #define LLDP_MDI_POWER_STATE (1 << 2) #define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3) static const struct tok lldp_mdi_values[] = { { LLDP_MDI_PORT_CLASS, "PSE"}, { LLDP_MDI_POWER_SUPPORT, "supported"}, { LLDP_MDI_POWER_STATE, "enabled"}, { LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"}, { 0, NULL} }; #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1 #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2 static const struct tok lldp_mdi_power_pairs_values[] = { { LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"}, { LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"}, { 0, NULL} }; #define LLDP_MDI_POWER_CLASS0 1 #define LLDP_MDI_POWER_CLASS1 2 #define LLDP_MDI_POWER_CLASS2 3 #define LLDP_MDI_POWER_CLASS3 4 #define LLDP_MDI_POWER_CLASS4 5 static const struct tok lldp_mdi_power_class_values[] = { { LLDP_MDI_POWER_CLASS0, "class0"}, { LLDP_MDI_POWER_CLASS1, "class1"}, { LLDP_MDI_POWER_CLASS2, "class2"}, { LLDP_MDI_POWER_CLASS3, "class3"}, { LLDP_MDI_POWER_CLASS4, "class4"}, { 0, NULL} }; #define LLDP_AGGREGATION_CAPABILTIY (1 << 0) #define LLDP_AGGREGATION_STATUS (1 << 1) static const struct tok lldp_aggregation_values[] = { { LLDP_AGGREGATION_CAPABILTIY, "supported"}, { LLDP_AGGREGATION_STATUS, "enabled"}, { 0, NULL} }; /* * DCBX protocol subtypes. */ #define LLDP_DCBX_SUBTYPE_1 1 #define LLDP_DCBX_SUBTYPE_2 2 static const struct tok lldp_dcbx_subtype_values[] = { { LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" }, { LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" }, { 0, NULL} }; #define LLDP_DCBX_CONTROL_TLV 1 #define LLDP_DCBX_PRIORITY_GROUPS_TLV 2 #define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3 #define LLDP_DCBX_APPLICATION_TLV 4 /* * Interface numbering subtypes. */ #define LLDP_INTF_NUMB_IFX_SUBTYPE 2 #define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3 static const struct tok lldp_intf_numb_subtype_values[] = { { LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" }, { LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" }, { 0, NULL} }; #define LLDP_INTF_NUM_LEN 5 #define LLDP_EVB_MODE_NOT_SUPPORTED 0 #define LLDP_EVB_MODE_EVB_BRIDGE 1 #define LLDP_EVB_MODE_EVB_STATION 2 #define LLDP_EVB_MODE_RESERVED 3 static const struct tok lldp_evb_mode_values[]={ { LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"}, { LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"}, { LLDP_EVB_MODE_EVB_STATION, "EVB Staion"}, { LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"}, { 0, NULL}, }; #define NO_OF_BITS 8 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5 #define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8 #define LLDP_IANA_SUBTYPE_MUDURL 1 static const struct tok lldp_iana_subtype_values[] = { { LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" }, { 0, NULL } }; static void print_ets_priority_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t Priority Assignment Table")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4, ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f)); } static void print_tc_bandwidth_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TC Bandwidth Table")); ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } static void print_tsa_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TSA Assignment Table")); ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } /* * Print IEEE 802.1 private extensions. (802.1AB annex E) */ static int lldp_private_8021_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; u_int sublen; u_int tval; u_int i; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8021_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t port vlan id (PVID): %u", EXTRACT_16BITS(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)", EXTRACT_16BITS(tptr+5), bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)), *(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4))); if (tlv_len < 7) { return hexdump; } sublen = *(tptr+6); if (tlv_len < 7+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t vlan name: ")); safeputs(ndo, tptr + 7, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY: if (tlv_len < 5) { return hexdump; } sublen = *(tptr+4); if (tlv_len < 5+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t protocol identity: ")); safeputs(ndo, tptr + 5, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d", tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07)); /*Print Priority Assignment Table*/ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table*/ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); /*Print Priority Assignment Table */ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table */ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ", tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f))); ND_PRINT((ndo, "\n\t PFC Enable")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){ return hexdump; } /* Length of Application Priority Table */ sublen=tlv_len-5; if(sublen%3!=0){ return hexdump; } i=0; ND_PRINT((ndo, "\n\t Application Priority Table")); while(i<sublen) { tval=*(tptr+i+5); ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u", tval >> 5, (tval >> 3) & 0x03, (tval & 0x07), EXTRACT_16BITS(tptr + i + 5))); i=i+3; } break; case LLDP_PRIVATE_8021_SUBTYPE_EVB: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){ return hexdump; } ND_PRINT((ndo, "\n\t EVB Bridge Status")); tval=*(tptr+4); ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d", tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01)); ND_PRINT((ndo, "\n\t EVB Station Status")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d", tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03)); tval=*(tptr+6); ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f)); tval=*(tptr+7); ND_PRINT((ndo, "EVB Mode: %s [%d]", tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6)); ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f)); tval=*(tptr+8); ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f)); break; case LLDP_PRIVATE_8021_SUBTYPE_CDCP: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ", tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01)); ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff)); sublen=tlv_len-8; if(sublen%3!=0) { return hexdump; } i=0; while(i<sublen) { tval=EXTRACT_24BITS(tptr+i+8); ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d", tval >> 12, tval & 0x000fff)); i=i+3; } break; default: hexdump = TRUE; break; } return hexdump; } /* * Print IEEE 802.3 private extensions. (802.3bc) */ static int lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } /* * Extract 34bits of latitude/longitude coordinates. */ static uint64_t lldp_extract_latlon(const u_char *tptr) { uint64_t latlon; latlon = *tptr & 0x3; latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1); return latlon; } /* objects defined in IANA subtype 00 00 5e * (right now there is only one) */ static int lldp_private_iana_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 8) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_iana_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_IANA_SUBTYPE_MUDURL: ND_PRINT((ndo, "\n\t MUD-URL=")); (void)fn_printn(ndo, tptr+4, tlv_len-4, NULL); break; default: hexdump=TRUE; } return hexdump; } /* * Print private TIA extensions. */ static int lldp_private_tia_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; uint8_t location_format; uint16_t power_val; u_int lci_len; uint8_t ca_type, ca_len; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_tia_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)", bittok2str(lldp_tia_capabilities_values, "none", EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4))); ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)", tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)), *(tptr + 6))); break; case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY: if (tlv_len < 8) { return hexdump; } ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)", tok2str(lldp_tia_application_type_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, ", Flags [%s]", bittok2str( lldp_tia_network_policy_bits_values, "none", *(tptr + 5)))); ND_PRINT((ndo, "\n\t Vlan id %u", LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5)))); ND_PRINT((ndo, ", L2 priority %u", LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6)))); ND_PRINT((ndo, ", DSCP value %u", LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6)))); break; case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID: if (tlv_len < 5) { return hexdump; } location_format = *(tptr+4); ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)", tok2str(lldp_tia_location_data_format_values, "unknown", location_format), location_format)); switch (location_format) { case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED: if (tlv_len < 21) { return hexdump; } ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64, (*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5))); ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64, (*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10))); ND_PRINT((ndo, "\n\t Altitude type %s (%u)", tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)), (*(tptr + 15) >> 4))); ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x", (EXTRACT_16BITS(tptr+15)>>6)&0x3f, ((EXTRACT_32BITS(tptr + 16) & 0x3fffffff)))); ND_PRINT((ndo, "\n\t Datum %s (0x%02x)", tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)), *(tptr + 20))); break; case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS: if (tlv_len < 6) { return hexdump; } lci_len = *(tptr+5); if (lci_len < 3) { return hexdump; } if (tlv_len < 7+lci_len) { return hexdump; } ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ", lci_len, tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)), *(tptr + 6))); /* Country code */ safeputs(ndo, tptr + 7, 2); lci_len = lci_len-3; tptr = tptr + 9; /* Decode each civic address element */ while (lci_len > 0) { if (lci_len < 2) { return hexdump; } ca_type = *(tptr); ca_len = *(tptr+1); tptr += 2; lci_len -= 2; ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ", tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type), ca_type, ca_len)); /* basic sanity check */ if ( ca_type == 0 || ca_len == 0) { return hexdump; } if (lci_len < ca_len) { return hexdump; } safeputs(ndo, tptr, ca_len); tptr += ca_len; lci_len -= ca_len; } break; case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN: ND_PRINT((ndo, "\n\t ECS ELIN id ")); safeputs(ndo, tptr + 5, tlv_len - 5); break; default: ND_PRINT((ndo, "\n\t Location ID ")); print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5); } break; case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Power type [%s]", (*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device")); ND_PRINT((ndo, ", Power source [%s]", tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4))); ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)", tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f), *(tptr + 4) & 0x0f)); power_val = EXTRACT_16BITS(tptr+5); if (power_val < LLDP_TIA_POWER_VAL_MAX) { ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10)); } else { ND_PRINT((ndo, ", Power %u (Reserved)", power_val)); } break; case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID: ND_PRINT((ndo, "\n\t %s ", tok2str(lldp_tia_inventory_values, "unknown", subtype))); safeputs(ndo, tptr + 4, tlv_len - 4); break; default: hexdump = TRUE; break; } return hexdump; } /* * Print DCBX Protocol fields (V 1.01). */ static int lldp_private_dcbx_print(netdissect_options *ndo, const u_char *pptr, u_int len) { int subtype, hexdump = FALSE; uint8_t tval; uint16_t tlv; uint32_t i, pgval, uval; u_int tlen, tlv_type, tlv_len; const u_char *tptr, *mptr; if (len < 4) { return hexdump; } subtype = *(pptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_dcbx_subtype_values, "unknown", subtype), subtype)); /* by passing old version */ if (subtype == LLDP_DCBX_SUBTYPE_1) return TRUE; tptr = pptr + 4; tlen = len - 4; while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); /* loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } /* decode every tlv */ switch (tlv_type) { case LLDP_DCBX_CONTROL_TLV: if (tlv_len < 10) { goto trunc; } ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)", LLDP_DCBX_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2))); ND_PRINT((ndo, "\n\t Acknowledgement Number: %d", EXTRACT_32BITS(tptr + 6))); break; case LLDP_DCBX_PRIORITY_GROUPS_TLV: if (tlv_len < 17) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); ND_PRINT((ndo, "\n\t Priority Allocation")); /* * Array of 8 4-bit priority group ID values; we fetch all * 32 bits and extract each nibble. */ pgval = EXTRACT_32BITS(tptr+4); for (i = 0; i <= 7; i++) { ND_PRINT((ndo, "\n\t PgId_%d: %d", i, (pgval >> (28 - 4 * i)) & 0xF)); } ND_PRINT((ndo, "\n\t Priority Group Allocation")); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i))); ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8))); break; case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV: if (tlv_len < 6) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Flow Control")); ND_PRINT((ndo, " (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = *(tptr+4); ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4))); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Priority Bit %d: %s", i, (tval & (1 << i)) ? "Enabled" : "Disabled")); ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5))); break; case LLDP_DCBX_APPLICATION_TLV: if (tlv_len < 4) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)", LLDP_DCBX_APPLICATION_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = tlv_len - 4; mptr = tptr + 4; while (tval >= 6) { ND_PRINT((ndo, "\n\t Application Value")); ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x", EXTRACT_16BITS(mptr))); uval = EXTRACT_24BITS(mptr+2); ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s", (uval >> 22), (uval >> 22) ? "Socket Number" : "L2 EtherType")); ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff)); ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5))); tval = tval - 6; mptr = mptr + 6; } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } trunc: return hexdump; } static char * lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len) { uint8_t af; static char buf[BUFSIZE]; const char * (*pfunc)(netdissect_options *, const u_char *); if (len < 1) return NULL; len--; af = *tptr; switch (af) { case AFNUM_INET: if (len < 4) return NULL; /* This cannot be assigned to ipaddr_string(), which is a macro. */ pfunc = getname; break; case AFNUM_INET6: if (len < 16) return NULL; /* This cannot be assigned to ip6addr_string(), which is a macro. */ pfunc = getname6; break; case AFNUM_802: if (len < 6) return NULL; pfunc = etheraddr_string; break; default: pfunc = NULL; break; } if (!pfunc) { snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !", tok2str(af_values, "Unknown", af), af); } else { snprintf(buf, sizeof(buf), "AFI %s (%u): %s", tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1)); } return buf; } static int lldp_mgmt_addr_tlv_print(netdissect_options *ndo, const u_char *pptr, u_int len) { uint8_t mgmt_addr_len, intf_num_subtype, oid_len; const u_char *tptr; u_int tlen; char *mgmt_addr; tlen = len; tptr = pptr; if (tlen < 1) { return 0; } mgmt_addr_len = *tptr++; tlen--; if (tlen < mgmt_addr_len) { return 0; } mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len); if (mgmt_addr == NULL) { return 0; } ND_PRINT((ndo, "\n\t Management Address length %u, %s", mgmt_addr_len, mgmt_addr)); tptr += mgmt_addr_len; tlen -= mgmt_addr_len; if (tlen < LLDP_INTF_NUM_LEN) { return 0; } intf_num_subtype = *tptr; ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u", tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype), intf_num_subtype, EXTRACT_32BITS(tptr + 1))); tptr += LLDP_INTF_NUM_LEN; tlen -= LLDP_INTF_NUM_LEN; /* * The OID is optional. */ if (tlen) { oid_len = *tptr; if (tlen < 1U + oid_len) { return 0; } if (oid_len) { ND_PRINT((ndo, "\n\t OID length %u", oid_len)); safeputs(ndo, tptr + 1, oid_len); } } return 1; } void lldp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { uint8_t subtype; uint16_t tlv, cap, ena_cap; u_int oui, tlen, hexdump, tlv_type, tlv_len; const u_char *tptr; char *network_addr; tptr = pptr; tlen = len; ND_PRINT((ndo, "LLDP, length %u", len)); while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t%s TLV (%u), length %u", tok2str(lldp_tlv_values, "Unknown", tlv_type), tlv_type, tlv_len)); } /* infinite loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } switch (tlv_type) { case LLDP_CHASSIS_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_chassis_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_CHASSIS_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_CHASSIS_LOCAL_SUBTYPE: case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE: case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE: case LLDP_CHASSIS_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_PORT_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_port_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_PORT_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_PORT_LOCAL_SUBTYPE: case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE: case LLDP_PORT_INTF_ALIAS_SUBTYPE: case LLDP_PORT_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_PORT_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_TTL_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr))); } break; case LLDP_PORT_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_NAME_TLV: /* * The system name is also print in non-verbose mode * similar to the CDP printer. */ ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); break; case LLDP_SYSTEM_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_CAP_TLV: if (ndo->ndo_vflag) { /* * XXX - IEEE Std 802.1AB-2009 says the first octet * if a chassis ID subtype, with the system * capabilities and enabled capabilities following * it. */ if (tlv_len < 4) { goto trunc; } cap = EXTRACT_16BITS(tptr); ena_cap = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", cap), cap)); ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", ena_cap), ena_cap)); } break; case LLDP_MGMT_ADDR_TLV: if (ndo->ndo_vflag) { if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) { goto trunc; } } break; case LLDP_PRIVATE_TLV: if (ndo->ndo_vflag) { if (tlv_len < 3) { goto trunc; } oui = EXTRACT_24BITS(tptr); ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui)); switch (oui) { case OUI_IEEE_8021_PRIVATE: hexdump = lldp_private_8021_print(ndo, tptr, tlv_len); break; case OUI_IEEE_8023_PRIVATE: hexdump = lldp_private_8023_print(ndo, tptr, tlv_len); break; case OUI_IANA: hexdump = lldp_private_iana_print(ndo, tptr, tlv_len); break; case OUI_TIA: hexdump = lldp_private_tia_print(ndo, tptr, tlv_len); break; case OUI_DCBX: hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len); break; default: hexdump = TRUE; break; } } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } return; trunc: ND_PRINT((ndo, "\n\t[|LLDP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2730_0
crossvul-cpp_data_good_706_0
/*- * Copyright (c) 2011 Michihiro NAKAJIMA * 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 AUTHOR(S) ``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 AUTHOR(S) 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 "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_BZLIB_H #include <bzlib.h> #endif #ifdef HAVE_LZMA_H #include <lzma.h> #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #include "archive.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" #include "archive_endian.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #define _7ZIP_SIGNATURE "7z\xBC\xAF\x27\x1C" #define SFX_MIN_ADDR 0x27000 #define SFX_MAX_ADDR 0x60000 /* * Codec ID */ #define _7Z_COPY 0 #define _7Z_LZMA 0x030101 #define _7Z_LZMA2 0x21 #define _7Z_DEFLATE 0x040108 #define _7Z_BZ2 0x040202 #define _7Z_PPMD 0x030401 #define _7Z_DELTA 0x03 #define _7Z_CRYPTO_MAIN_ZIP 0x06F10101 /* Main Zip crypto algo */ #define _7Z_CRYPTO_RAR_29 0x06F10303 /* Rar29 AES-128 + (modified SHA-1) */ #define _7Z_CRYPTO_AES_256_SHA_256 0x06F10701 /* AES-256 + SHA-256 */ #define _7Z_X86 0x03030103 #define _7Z_X86_BCJ2 0x0303011B #define _7Z_POWERPC 0x03030205 #define _7Z_IA64 0x03030401 #define _7Z_ARM 0x03030501 #define _7Z_ARMTHUMB 0x03030701 #define _7Z_SPARC 0x03030805 /* * 7-Zip header property IDs. */ #define kEnd 0x00 #define kHeader 0x01 #define kArchiveProperties 0x02 #define kAdditionalStreamsInfo 0x03 #define kMainStreamsInfo 0x04 #define kFilesInfo 0x05 #define kPackInfo 0x06 #define kUnPackInfo 0x07 #define kSubStreamsInfo 0x08 #define kSize 0x09 #define kCRC 0x0A #define kFolder 0x0B #define kCodersUnPackSize 0x0C #define kNumUnPackStream 0x0D #define kEmptyStream 0x0E #define kEmptyFile 0x0F #define kAnti 0x10 #define kName 0x11 #define kCTime 0x12 #define kATime 0x13 #define kMTime 0x14 #define kAttributes 0x15 #define kEncodedHeader 0x17 #define kDummy 0x19 struct _7z_digests { unsigned char *defineds; uint32_t *digests; }; struct _7z_folder { uint64_t numCoders; struct _7z_coder { unsigned long codec; uint64_t numInStreams; uint64_t numOutStreams; uint64_t propertiesSize; unsigned char *properties; } *coders; uint64_t numBindPairs; struct { uint64_t inIndex; uint64_t outIndex; } *bindPairs; uint64_t numPackedStreams; uint64_t *packedStreams; uint64_t numInStreams; uint64_t numOutStreams; uint64_t *unPackSize; unsigned char digest_defined; uint32_t digest; uint64_t numUnpackStreams; uint32_t packIndex; /* Unoperated bytes. */ uint64_t skipped_bytes; }; struct _7z_coders_info { uint64_t numFolders; struct _7z_folder *folders; uint64_t dataStreamIndex; }; struct _7z_pack_info { uint64_t pos; uint64_t numPackStreams; uint64_t *sizes; struct _7z_digests digest; /* Calculated from pos and numPackStreams. */ uint64_t *positions; }; struct _7z_substream_info { size_t unpack_streams; uint64_t *unpackSizes; unsigned char *digestsDefined; uint32_t *digests; }; struct _7z_stream_info { struct _7z_pack_info pi; struct _7z_coders_info ci; struct _7z_substream_info ss; }; struct _7z_header_info { uint64_t dataIndex; unsigned char *emptyStreamBools; unsigned char *emptyFileBools; unsigned char *antiBools; unsigned char *attrBools; }; struct _7zip_entry { size_t name_len; unsigned char *utf16name; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) const wchar_t *wname; #endif uint32_t folderIndex; uint32_t ssIndex; unsigned flg; #define MTIME_IS_SET (1<<0) #define ATIME_IS_SET (1<<1) #define CTIME_IS_SET (1<<2) #define CRC32_IS_SET (1<<3) #define HAS_STREAM (1<<4) time_t mtime; time_t atime; time_t ctime; long mtime_ns; long atime_ns; long ctime_ns; uint32_t mode; uint32_t attr; }; struct _7zip { /* Structural information about the archive. */ struct _7z_stream_info si; int header_is_being_read; int header_is_encoded; uint64_t header_bytes_remaining; unsigned long header_crc32; /* Header offset to check that reading points of the file contents * will not exceed the header. */ uint64_t header_offset; /* Base offset of the archive file for a seek in case reading SFX. */ uint64_t seek_base; /* List of entries */ size_t entries_remaining; uint64_t numFiles; struct _7zip_entry *entries; struct _7zip_entry *entry; unsigned char *entry_names; /* entry_bytes_remaining is the number of bytes we expect. */ int64_t entry_offset; uint64_t entry_bytes_remaining; /* Running CRC32 of the decompressed data */ unsigned long entry_crc32; /* Flags to mark progress of decompression. */ char end_of_entry; /* Uncompressed buffer control. */ #define UBUFF_SIZE (64 * 1024) unsigned char *uncompressed_buffer; unsigned char *uncompressed_buffer_pointer; size_t uncompressed_buffer_size; size_t uncompressed_buffer_bytes_remaining; /* Offset of the compressed data. */ int64_t stream_offset; /* * Decompressing control data. */ unsigned folder_index; uint64_t folder_outbytes_remaining; unsigned pack_stream_index; unsigned pack_stream_remaining; uint64_t pack_stream_inbytes_remaining; size_t pack_stream_bytes_unconsumed; /* The codec information of a folder. */ unsigned long codec; unsigned long codec2; /* * Decompressor controllers. */ /* Decoding LZMA1 and LZMA2 data. */ #ifdef HAVE_LZMA_H lzma_stream lzstream; int lzstream_valid; #endif /* Decoding bzip2 data. */ #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) bz_stream bzstream; int bzstream_valid; #endif /* Decoding deflate data. */ #ifdef HAVE_ZLIB_H z_stream stream; int stream_valid; #endif /* Decoding PPMd data. */ int ppmd7_stat; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; struct { const unsigned char *next_in; int64_t avail_in; int64_t total_in; unsigned char *next_out; int64_t avail_out; int64_t total_out; int overconsumed; } ppstream; int ppmd7_valid; /* Decoding BCJ and BCJ2 data. */ uint32_t bcj_state; size_t odd_bcj_size; unsigned char odd_bcj[4]; /* Decoding BCJ data. */ size_t bcj_prevPosT; uint32_t bcj_prevMask; uint32_t bcj_ip; /* Decoding BCJ2 data. */ size_t main_stream_bytes_remaining; unsigned char *sub_stream_buff[3]; size_t sub_stream_size[3]; size_t sub_stream_bytes_remaining[3]; unsigned char *tmp_stream_buff; size_t tmp_stream_buff_size; size_t tmp_stream_bytes_avail; size_t tmp_stream_bytes_remaining; #ifdef _LZMA_PROB32 #define CProb uint32_t #else #define CProb uint16_t #endif CProb bcj2_p[256 + 2]; uint8_t bcj2_prevByte; uint32_t bcj2_range; uint32_t bcj2_code; uint64_t bcj2_outPos; /* Filename character-set conversion data. */ struct archive_string_conv *sconv; char format_name[64]; /* Custom value that is non-zero if this archive contains encrypted entries. */ int has_encrypted_entries; }; /* Maximum entry size. This limitation prevents reading intentional * corrupted 7-zip files on assuming there are not so many entries in * the files. */ #define UMAX_ENTRY ARCHIVE_LITERAL_ULL(100000000) static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *); static int archive_read_support_format_7zip_capabilities(struct archive_read *a); static int archive_read_format_7zip_bid(struct archive_read *, int); static int archive_read_format_7zip_cleanup(struct archive_read *); static int archive_read_format_7zip_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_7zip_read_data_skip(struct archive_read *); static int archive_read_format_7zip_read_header(struct archive_read *, struct archive_entry *); static int check_7zip_header_in_sfx(const char *); static unsigned long decode_codec_id(const unsigned char *, size_t); static int decode_encoded_header_info(struct archive_read *, struct _7z_stream_info *); static int decompress(struct archive_read *, struct _7zip *, void *, size_t *, const void *, size_t *); static ssize_t extract_pack_stream(struct archive_read *, size_t); static void fileTimeToUtc(uint64_t, time_t *, long *); static uint64_t folder_uncompressed_size(struct _7z_folder *); static void free_CodersInfo(struct _7z_coders_info *); static void free_Digest(struct _7z_digests *); static void free_Folder(struct _7z_folder *); static void free_Header(struct _7z_header_info *); static void free_PackInfo(struct _7z_pack_info *); static void free_StreamsInfo(struct _7z_stream_info *); static void free_SubStreamsInfo(struct _7z_substream_info *); static int free_decompression(struct archive_read *, struct _7zip *); static ssize_t get_uncompressed_data(struct archive_read *, const void **, size_t, size_t); static const unsigned char * header_bytes(struct archive_read *, size_t); static int init_decompression(struct archive_read *, struct _7zip *, const struct _7z_coder *, const struct _7z_coder *); static int parse_7zip_uint64(struct archive_read *, uint64_t *); static int read_Bools(struct archive_read *, unsigned char *, size_t); static int read_CodersInfo(struct archive_read *, struct _7z_coders_info *); static int read_Digests(struct archive_read *, struct _7z_digests *, size_t); static int read_Folder(struct archive_read *, struct _7z_folder *); static int read_Header(struct archive_read *, struct _7z_header_info *, int); static int read_PackInfo(struct archive_read *, struct _7z_pack_info *); static int read_StreamsInfo(struct archive_read *, struct _7z_stream_info *); static int read_SubStreamsInfo(struct archive_read *, struct _7z_substream_info *, struct _7z_folder *, size_t); static int read_Times(struct archive_read *, struct _7z_header_info *, int); static void read_consume(struct archive_read *); static ssize_t read_stream(struct archive_read *, const void **, size_t, size_t); static int seek_pack(struct archive_read *); static int64_t skip_stream(struct archive_read *, size_t); static int skip_sfx(struct archive_read *, ssize_t); static int slurp_central_directory(struct archive_read *, struct _7zip *, struct _7z_header_info *); static int setup_decode_folder(struct archive_read *, struct _7z_folder *, int); static void x86_Init(struct _7zip *); static size_t x86_Convert(struct _7zip *, uint8_t *, size_t); static ssize_t Bcj2_Decode(struct _7zip *, uint8_t *, size_t); int archive_read_support_format_7zip(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct _7zip *zip; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_7zip"); zip = calloc(1, sizeof(*zip)); if (zip == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate 7zip data"); return (ARCHIVE_FATAL); } /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, zip, "7zip", archive_read_format_7zip_bid, NULL, archive_read_format_7zip_read_header, archive_read_format_7zip_read_data, archive_read_format_7zip_read_data_skip, NULL, archive_read_format_7zip_cleanup, archive_read_support_format_7zip_capabilities, archive_read_format_7zip_has_encrypted_entries); if (r != ARCHIVE_OK) free(zip); return (ARCHIVE_OK); } static int archive_read_support_format_7zip_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct _7zip * zip = (struct _7zip *)_a->format->data; if (zip) { return zip->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_7zip_bid(struct archive_read *a, int best_bid) { const char *p; /* If someone has already bid more than 32, then avoid trashing the look-ahead buffers with a seek. */ if (best_bid > 32) return (-1); if ((p = __archive_read_ahead(a, 6, NULL)) == NULL) return (0); /* If first six bytes are the 7-Zip signature, * return the bid right now. */ if (memcmp(p, _7ZIP_SIGNATURE, 6) == 0) return (48); /* * It may a 7-Zip SFX archive file. If first two bytes are * 'M' and 'Z' available on Windows or first four bytes are * "\x7F\x45LF" available on posix like system, seek the 7-Zip * signature. Although we will perform a seek when reading * a header, what we do not use __archive_read_seek() here is * due to a bidding performance. */ if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { ssize_t offset = SFX_MIN_ADDR; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (SFX_MAX_ADDR)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 32 < buff + bytes_avail) { int step = check_7zip_header_in_sfx(p); if (step == 0) return (48); p += step; } offset = p - buff; } } return (0); } static int check_7zip_header_in_sfx(const char *p) { switch ((unsigned char)p[5]) { case 0x1C: if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) return (6); /* * Test the CRC because its extraction code has 7-Zip * Magic Code, so we should do this in order not to * make a mis-detection. */ if (crc32(0, (const unsigned char *)p + 12, 20) != archive_le32dec(p + 8)) return (6); /* Hit the header! */ return (0); case 0x37: return (5); case 0x7A: return (4); case 0xBC: return (3); case 0xAF: return (2); case 0x27: return (1); default: return (6); } } static int skip_sfx(struct archive_read *a, ssize_t bytes_avail) { const void *h; const char *p, *q; size_t skip, offset; ssize_t bytes, window; /* * If bytes_avail > SFX_MIN_ADDR we do not have to call * __archive_read_seek() at this time since we have * already had enough data. */ if (bytes_avail > SFX_MIN_ADDR) __archive_read_consume(a, SFX_MIN_ADDR); else if (__archive_read_seek(a, SFX_MIN_ADDR, SEEK_SET) < 0) return (ARCHIVE_FATAL); offset = 0; window = 1; while (offset + window <= SFX_MAX_ADDR - SFX_MIN_ADDR) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 6) { /* This case might happen when window == 1. */ window = 4096; continue; } p = (const char *)h; q = p + bytes; /* * Scan ahead until we find something that looks * like the 7-Zip header. */ while (p + 32 < q) { int step = check_7zip_header_in_sfx(p); if (step == 0) { struct _7zip *zip = (struct _7zip *)a->format->data; skip = p - (const char *)h; __archive_read_consume(a, skip); zip->seek_base = SFX_MIN_ADDR + offset + skip; return (ARCHIVE_OK); } p += step; } skip = p - (const char *)h; __archive_read_consume(a, skip); offset += skip; if (window == 1) window = 4096; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out 7-Zip header"); return (ARCHIVE_FATAL); } static int archive_read_format_7zip_read_header(struct archive_read *a, struct archive_entry *entry) { struct _7zip *zip = (struct _7zip *)a->format->data; struct _7zip_entry *zip_entry; int r, ret = ARCHIVE_OK; struct _7z_folder *folder = 0; uint64_t fidx = 0; /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } a->archive.archive_format = ARCHIVE_FORMAT_7ZIP; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "7-Zip"; if (zip->entries == NULL) { struct _7z_header_info header; memset(&header, 0, sizeof(header)); r = slurp_central_directory(a, zip, &header); free_Header(&header); if (r != ARCHIVE_OK) return (r); zip->entries_remaining = (size_t)zip->numFiles; zip->entry = zip->entries; } else { ++zip->entry; } zip_entry = zip->entry; if (zip->entries_remaining <= 0 || zip_entry == NULL) return ARCHIVE_EOF; --zip->entries_remaining; zip->entry_offset = 0; zip->end_of_entry = 0; zip->entry_crc32 = crc32(0, NULL, 0); /* Setup a string conversion for a filename. */ if (zip->sconv == NULL) { zip->sconv = archive_string_conversion_from_charset( &a->archive, "UTF-16LE", 1); if (zip->sconv == NULL) return (ARCHIVE_FATAL); } /* Figure out if the entry is encrypted by looking at the folder that is associated to the current 7zip entry. If the folder has a coder with a _7Z_CRYPTO codec then the folder is encrypted. Hence the entry must also be encrypted. */ if (zip_entry && zip_entry->folderIndex < zip->si.ci.numFolders) { folder = &(zip->si.ci.folders[zip_entry->folderIndex]); for (fidx=0; folder && fidx<folder->numCoders; fidx++) { switch(folder->coders[fidx].codec) { case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: { archive_entry_set_is_data_encrypted(entry, 1); zip->has_encrypted_entries = 1; break; } } } } /* Now that we've checked for encryption, if there were still no * encrypted entries found we can say for sure that there are none. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if (archive_entry_copy_pathname_l(entry, (const char *)zip_entry->utf16name, zip_entry->name_len, zip->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name(zip->sconv)); ret = ARCHIVE_WARN; } /* Populate some additional entry fields: */ archive_entry_set_mode(entry, zip_entry->mode); if (zip_entry->flg & MTIME_IS_SET) archive_entry_set_mtime(entry, zip_entry->mtime, zip_entry->mtime_ns); if (zip_entry->flg & CTIME_IS_SET) archive_entry_set_ctime(entry, zip_entry->ctime, zip_entry->ctime_ns); if (zip_entry->flg & ATIME_IS_SET) archive_entry_set_atime(entry, zip_entry->atime, zip_entry->atime_ns); if (zip_entry->ssIndex != (uint32_t)-1) { zip->entry_bytes_remaining = zip->si.ss.unpackSizes[zip_entry->ssIndex]; archive_entry_set_size(entry, zip->entry_bytes_remaining); } else { zip->entry_bytes_remaining = 0; archive_entry_set_size(entry, 0); } /* If there's no body, force read_data() to return EOF immediately. */ if (zip->entry_bytes_remaining < 1) zip->end_of_entry = 1; if ((zip_entry->mode & AE_IFMT) == AE_IFLNK) { unsigned char *symname = NULL; size_t symsize = 0; /* * Symbolic-name is recorded as its contents. We have to * read the contents at this time. */ while (zip->entry_bytes_remaining > 0) { const void *buff; unsigned char *mem; size_t size; int64_t offset; r = archive_read_format_7zip_read_data(a, &buff, &size, &offset); if (r < ARCHIVE_WARN) { free(symname); return (r); } mem = realloc(symname, symsize + size + 1); if (mem == NULL) { free(symname); archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Symname"); return (ARCHIVE_FATAL); } symname = mem; memcpy(symname+symsize, buff, size); symsize += size; } if (symsize == 0) { /* If there is no symname, handle it as a regular * file. */ zip_entry->mode &= ~AE_IFMT; zip_entry->mode |= AE_IFREG; archive_entry_set_mode(entry, zip_entry->mode); } else { symname[symsize] = '\0'; archive_entry_copy_symlink(entry, (const char *)symname); } free(symname); archive_entry_set_size(entry, 0); } /* Set up a more descriptive format name. */ sprintf(zip->format_name, "7-Zip"); a->archive.archive_format_name = zip->format_name; return (ret); } static int archive_read_format_7zip_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct _7zip *zip; ssize_t bytes; int ret = ARCHIVE_OK; zip = (struct _7zip *)(a->format->data); if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if (zip->pack_stream_bytes_unconsumed) read_consume(a); *offset = zip->entry_offset; *size = 0; *buff = NULL; /* * If we hit end-of-entry last time, clean up and return * ARCHIVE_EOF this time. */ if (zip->end_of_entry) return (ARCHIVE_EOF); bytes = read_stream(a, buff, (size_t)zip->entry_bytes_remaining, 0); if (bytes < 0) return ((int)bytes); if (bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } zip->entry_bytes_remaining -= bytes; if (zip->entry_bytes_remaining == 0) zip->end_of_entry = 1; /* Update checksum */ if ((zip->entry->flg & CRC32_IS_SET) && bytes) zip->entry_crc32 = crc32(zip->entry_crc32, *buff, (unsigned)bytes); /* If we hit the end, swallow any end-of-data marker. */ if (zip->end_of_entry) { /* Check computed CRC against file contents. */ if ((zip->entry->flg & CRC32_IS_SET) && zip->si.ss.digests[zip->entry->ssIndex] != zip->entry_crc32) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "7-Zip bad CRC: 0x%lx should be 0x%lx", (unsigned long)zip->entry_crc32, (unsigned long)zip->si.ss.digests[ zip->entry->ssIndex]); ret = ARCHIVE_WARN; } } *size = bytes; *offset = zip->entry_offset; zip->entry_offset += bytes; return (ret); } static int archive_read_format_7zip_read_data_skip(struct archive_read *a) { struct _7zip *zip; int64_t bytes_skipped; zip = (struct _7zip *)(a->format->data); if (zip->pack_stream_bytes_unconsumed) read_consume(a); /* If we've already read to end of data, we're done. */ if (zip->end_of_entry) return (ARCHIVE_OK); /* * If the length is at the beginning, we can skip the * compressed data much more quickly. */ bytes_skipped = skip_stream(a, (size_t)zip->entry_bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); zip->entry_bytes_remaining = 0; /* This entry is finished and done. */ zip->end_of_entry = 1; return (ARCHIVE_OK); } static int archive_read_format_7zip_cleanup(struct archive_read *a) { struct _7zip *zip; zip = (struct _7zip *)(a->format->data); free_StreamsInfo(&(zip->si)); free(zip->entries); free(zip->entry_names); free_decompression(a, zip); free(zip->uncompressed_buffer); free(zip->sub_stream_buff[0]); free(zip->sub_stream_buff[1]); free(zip->sub_stream_buff[2]); free(zip->tmp_stream_buff); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); } static void read_consume(struct archive_read *a) { struct _7zip *zip = (struct _7zip *)a->format->data; if (zip->pack_stream_bytes_unconsumed) { __archive_read_consume(a, zip->pack_stream_bytes_unconsumed); zip->stream_offset += zip->pack_stream_bytes_unconsumed; zip->pack_stream_bytes_unconsumed = 0; } } #ifdef HAVE_LZMA_H /* * Set an error code and choose an error message for liblzma. */ static void set_error(struct archive_read *a, int ret) { switch (ret) { case LZMA_STREAM_END: /* Found end of stream. */ case LZMA_OK: /* Decompressor made some progress. */ break; case LZMA_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Lzma library error: Cannot allocate memory"); break; case LZMA_MEMLIMIT_ERROR: archive_set_error(&a->archive, ENOMEM, "Lzma library error: Out of memory"); break; case LZMA_FORMAT_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: format not recognized"); break; case LZMA_OPTIONS_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: Invalid options"); break; case LZMA_DATA_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: Corrupted input data"); break; case LZMA_BUF_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: No progress is possible"); break; default: /* Return an error. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma decompression failed: Unknown error"); break; } } #endif static unsigned long decode_codec_id(const unsigned char *codecId, size_t id_size) { unsigned i; unsigned long id = 0; for (i = 0; i < id_size; i++) { id <<= 8; id += codecId[i]; } return (id); } static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct _7zip *zip = (struct _7zip *)(a->format->data); Byte b; if (zip->ppstream.avail_in == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); zip->ppstream.overconsumed = 1; return (0); } b = *zip->ppstream.next_in++; zip->ppstream.avail_in--; zip->ppstream.total_in++; return (b); } static int init_decompression(struct archive_read *a, struct _7zip *zip, const struct _7z_coder *coder1, const struct _7z_coder *coder2) { int r; zip->codec = coder1->codec; zip->codec2 = -1; switch (zip->codec) { case _7Z_COPY: case _7Z_BZ2: case _7Z_DEFLATE: case _7Z_PPMD: if (coder2 != NULL) { if (coder2->codec != _7Z_X86 && coder2->codec != _7Z_X86_BCJ2) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unsupported filter %lx for %lx", coder2->codec, coder1->codec); return (ARCHIVE_FAILED); } zip->codec2 = coder2->codec; zip->bcj_state = 0; if (coder2->codec == _7Z_X86) x86_Init(zip); } break; default: break; } switch (zip->codec) { case _7Z_COPY: break; case _7Z_LZMA: case _7Z_LZMA2: #ifdef HAVE_LZMA_H #if LZMA_VERSION_MAJOR >= 5 /* Effectively disable the limiter. */ #define LZMA_MEMLIMIT UINT64_MAX #else /* NOTE: This needs to check memory size which running system has. */ #define LZMA_MEMLIMIT (1U << 30) #endif { lzma_options_delta delta_opt; lzma_filter filters[LZMA_FILTERS_MAX], *ff; int fi = 0; if (zip->lzstream_valid) { lzma_end(&(zip->lzstream)); zip->lzstream_valid = 0; } /* * NOTE: liblzma incompletely handle the BCJ+LZMA compressed * data made by 7-Zip because 7-Zip does not add End-Of- * Payload Marker(EOPM) at the end of LZMA compressed data, * and so liblzma cannot know the end of the compressed data * without EOPM. So consequently liblzma will not return last * three or four bytes of uncompressed data because * LZMA_FILTER_X86 filter does not handle input data if its * data size is less than five bytes. If liblzma detect EOPM * or know the uncompressed data size, liblzma will flush out * the remaining that three or four bytes of uncompressed * data. That is why we have to use our converting program * for BCJ+LZMA. If we were able to tell the uncompressed * size to liblzma when using lzma_raw_decoder() liblzma * could correctly deal with BCJ+LZMA. But unfortunately * there is no way to do that. * Discussion about this can be found at XZ Utils forum. */ if (coder2 != NULL) { zip->codec2 = coder2->codec; filters[fi].options = NULL; switch (zip->codec2) { case _7Z_X86: if (zip->codec == _7Z_LZMA2) { filters[fi].id = LZMA_FILTER_X86; fi++; } else /* Use our filter. */ x86_Init(zip); break; case _7Z_X86_BCJ2: /* Use our filter. */ zip->bcj_state = 0; break; case _7Z_DELTA: filters[fi].id = LZMA_FILTER_DELTA; memset(&delta_opt, 0, sizeof(delta_opt)); delta_opt.type = LZMA_DELTA_TYPE_BYTE; delta_opt.dist = 1; filters[fi].options = &delta_opt; fi++; break; /* Following filters have not been tested yet. */ case _7Z_POWERPC: filters[fi].id = LZMA_FILTER_POWERPC; fi++; break; case _7Z_IA64: filters[fi].id = LZMA_FILTER_IA64; fi++; break; case _7Z_ARM: filters[fi].id = LZMA_FILTER_ARM; fi++; break; case _7Z_ARMTHUMB: filters[fi].id = LZMA_FILTER_ARMTHUMB; fi++; break; case _7Z_SPARC: filters[fi].id = LZMA_FILTER_SPARC; fi++; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unexpected codec ID: %lX", zip->codec2); return (ARCHIVE_FAILED); } } if (zip->codec == _7Z_LZMA2) filters[fi].id = LZMA_FILTER_LZMA2; else filters[fi].id = LZMA_FILTER_LZMA1; filters[fi].options = NULL; ff = &filters[fi]; r = lzma_properties_decode(&filters[fi], NULL, coder1->properties, (size_t)coder1->propertiesSize); if (r != LZMA_OK) { set_error(a, r); return (ARCHIVE_FAILED); } fi++; filters[fi].id = LZMA_VLI_UNKNOWN; filters[fi].options = NULL; r = lzma_raw_decoder(&(zip->lzstream), filters); free(ff->options); if (r != LZMA_OK) { set_error(a, r); return (ARCHIVE_FAILED); } zip->lzstream_valid = 1; zip->lzstream.total_in = 0; zip->lzstream.total_out = 0; break; } #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "LZMA codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_BZ2: #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&(zip->bzstream)); zip->bzstream_valid = 0; } r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 0); if (r == BZ_MEM_ERROR) r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 1); if (r != BZ_OK) { int err = ARCHIVE_ERRNO_MISC; const char *detail = NULL; switch (r) { case BZ_PARAM_ERROR: detail = "invalid setup parameter"; break; case BZ_MEM_ERROR: err = ENOMEM; detail = "out of memory"; break; case BZ_CONFIG_ERROR: detail = "mis-compiled library"; break; } archive_set_error(&a->archive, err, "Internal error initializing decompressor: %s", detail != NULL ? detail : "??"); zip->bzstream_valid = 0; return (ARCHIVE_FAILED); } zip->bzstream_valid = 1; zip->bzstream.total_in_lo32 = 0; zip->bzstream.total_in_hi32 = 0; zip->bzstream.total_out_lo32 = 0; zip->bzstream.total_out_hi32 = 0; break; #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "BZ2 codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_DEFLATE: #ifdef HAVE_ZLIB_H if (zip->stream_valid) r = inflateReset(&(zip->stream)); else r = inflateInit2(&(zip->stream), -15 /* Don't check for zlib header */); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't initialize zlib stream."); return (ARCHIVE_FAILED); } zip->stream_valid = 1; zip->stream.total_in = 0; zip->stream.total_out = 0; break; #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "DEFLATE codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_PPMD: { unsigned order; uint32_t msize; if (zip->ppmd7_valid) { __archive_ppmd7_functions.Ppmd7_Free( &zip->ppmd7_context); zip->ppmd7_valid = 0; } if (coder1->propertiesSize < 5) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed PPMd parameter"); return (ARCHIVE_FAILED); } order = coder1->properties[0]; msize = archive_le32dec(&(coder1->properties[1])); if (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER || msize < PPMD7_MIN_MEM_SIZE || msize > PPMD7_MAX_MEM_SIZE) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed PPMd parameter"); return (ARCHIVE_FAILED); } __archive_ppmd7_functions.Ppmd7_Construct(&zip->ppmd7_context); r = __archive_ppmd7_functions.Ppmd7_Alloc( &zip->ppmd7_context, msize); if (r == 0) { archive_set_error(&a->archive, ENOMEM, "Coludn't allocate memory for PPMd"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init( &zip->ppmd7_context, order); __archive_ppmd7_functions.Ppmd7z_RangeDec_CreateVTable( &zip->range_dec); zip->ppmd7_valid = 1; zip->ppmd7_stat = 0; zip->ppstream.overconsumed = 0; zip->ppstream.total_in = 0; zip->ppstream.total_out = 0; break; } case _7Z_X86: case _7Z_X86_BCJ2: case _7Z_POWERPC: case _7Z_IA64: case _7Z_ARM: case _7Z_ARMTHUMB: case _7Z_SPARC: case _7Z_DELTA: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unexpected codec ID: %lX", zip->codec); return (ARCHIVE_FAILED); case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: if (a->entry) { archive_entry_set_is_metadata_encrypted(a->entry, 1); archive_entry_set_is_data_encrypted(a->entry, 1); zip->has_encrypted_entries = 1; } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Crypto codec not supported yet (ID: 0x%lX)", zip->codec); return (ARCHIVE_FAILED); default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unknown codec ID: %lX", zip->codec); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } static int decompress(struct archive_read *a, struct _7zip *zip, void *buff, size_t *outbytes, const void *b, size_t *used) { const uint8_t *t_next_in; uint8_t *t_next_out; size_t o_avail_in, o_avail_out; size_t t_avail_in, t_avail_out; uint8_t *bcj2_next_out; size_t bcj2_avail_out; int r, ret = ARCHIVE_OK; t_avail_in = o_avail_in = *used; t_avail_out = o_avail_out = *outbytes; t_next_in = b; t_next_out = buff; if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { int i; /* Do not copy out the BCJ remaining bytes when the output * buffer size is less than five bytes. */ if (o_avail_in != 0 && t_avail_out < 5 && zip->odd_bcj_size) { *used = 0; *outbytes = 0; return (ret); } for (i = 0; zip->odd_bcj_size > 0 && t_avail_out; i++) { *t_next_out++ = zip->odd_bcj[i]; t_avail_out--; zip->odd_bcj_size--; } if (o_avail_in == 0 || t_avail_out == 0) { *used = o_avail_in - t_avail_in; *outbytes = o_avail_out - t_avail_out; if (o_avail_in == 0) ret = ARCHIVE_EOF; return (ret); } } bcj2_next_out = t_next_out; bcj2_avail_out = t_avail_out; if (zip->codec2 == _7Z_X86_BCJ2) { /* * Decord a remaining decompressed main stream for BCJ2. */ if (zip->tmp_stream_bytes_remaining) { ssize_t bytes; size_t remaining = zip->tmp_stream_bytes_remaining; bytes = Bcj2_Decode(zip, t_next_out, t_avail_out); if (bytes < 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed"); return (ARCHIVE_FAILED); } zip->main_stream_bytes_remaining -= remaining - zip->tmp_stream_bytes_remaining; t_avail_out -= bytes; if (o_avail_in == 0 || t_avail_out == 0) { *used = 0; *outbytes = o_avail_out - t_avail_out; if (o_avail_in == 0 && zip->tmp_stream_bytes_remaining) ret = ARCHIVE_EOF; return (ret); } t_next_out += bytes; bcj2_next_out = t_next_out; bcj2_avail_out = t_avail_out; } t_next_out = zip->tmp_stream_buff; t_avail_out = zip->tmp_stream_buff_size; } switch (zip->codec) { case _7Z_COPY: { size_t bytes = (t_avail_in > t_avail_out)?t_avail_out:t_avail_in; memcpy(t_next_out, t_next_in, bytes); t_avail_in -= bytes; t_avail_out -= bytes; if (o_avail_in == 0) ret = ARCHIVE_EOF; break; } #ifdef HAVE_LZMA_H case _7Z_LZMA: case _7Z_LZMA2: zip->lzstream.next_in = t_next_in; zip->lzstream.avail_in = t_avail_in; zip->lzstream.next_out = t_next_out; zip->lzstream.avail_out = t_avail_out; r = lzma_code(&(zip->lzstream), LZMA_RUN); switch (r) { case LZMA_STREAM_END: /* Found end of stream. */ lzma_end(&(zip->lzstream)); zip->lzstream_valid = 0; ret = ARCHIVE_EOF; break; case LZMA_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression failed(%d)", r); return (ARCHIVE_FAILED); } t_avail_in = zip->lzstream.avail_in; t_avail_out = zip->lzstream.avail_out; break; #endif #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case _7Z_BZ2: zip->bzstream.next_in = (char *)(uintptr_t)t_next_in; zip->bzstream.avail_in = t_avail_in; zip->bzstream.next_out = (char *)(uintptr_t)t_next_out; zip->bzstream.avail_out = t_avail_out; r = BZ2_bzDecompress(&(zip->bzstream)); switch (r) { case BZ_STREAM_END: /* Found end of stream. */ switch (BZ2_bzDecompressEnd(&(zip->bzstream))) { case BZ_OK: break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Failed to clean up decompressor"); return (ARCHIVE_FAILED); } zip->bzstream_valid = 0; ret = ARCHIVE_EOF; break; case BZ_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "bzip decompression failed"); return (ARCHIVE_FAILED); } t_avail_in = zip->bzstream.avail_in; t_avail_out = zip->bzstream.avail_out; break; #endif #ifdef HAVE_ZLIB_H case _7Z_DEFLATE: zip->stream.next_in = (Bytef *)(uintptr_t)t_next_in; zip->stream.avail_in = (uInt)t_avail_in; zip->stream.next_out = t_next_out; zip->stream.avail_out = (uInt)t_avail_out; r = inflate(&(zip->stream), 0); switch (r) { case Z_STREAM_END: /* Found end of stream. */ ret = ARCHIVE_EOF; break; case Z_OK: /* Decompressor made some progress.*/ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "File decompression failed (%d)", r); return (ARCHIVE_FAILED); } t_avail_in = zip->stream.avail_in; t_avail_out = zip->stream.avail_out; break; #endif case _7Z_PPMD: { uint64_t flush_bytes; if (!zip->ppmd7_valid || zip->ppmd7_stat < 0 || t_avail_out <= 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression internal error"); return (ARCHIVE_FAILED); } zip->ppstream.next_in = t_next_in; zip->ppstream.avail_in = t_avail_in; zip->ppstream.next_out = t_next_out; zip->ppstream.avail_out = t_avail_out; if (zip->ppmd7_stat == 0) { zip->bytein.a = a; zip->bytein.Read = &ppmd_read; zip->range_dec.Stream = &zip->bytein; r = __archive_ppmd7_functions.Ppmd7z_RangeDec_Init( &(zip->range_dec)); if (r == 0) { zip->ppmd7_stat = -1; archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to initialize PPMd range decorder"); return (ARCHIVE_FAILED); } if (zip->ppstream.overconsumed) { zip->ppmd7_stat = -1; return (ARCHIVE_FAILED); } zip->ppmd7_stat = 1; } if (t_avail_in == 0) /* XXX Flush out remaining decoded data XXX */ flush_bytes = zip->folder_outbytes_remaining; else flush_bytes = 0; do { int sym; sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &(zip->ppmd7_context), &(zip->range_dec.p)); if (sym < 0) { zip->ppmd7_stat = -1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Failed to decode PPMd"); return (ARCHIVE_FAILED); } if (zip->ppstream.overconsumed) { zip->ppmd7_stat = -1; return (ARCHIVE_FAILED); } *zip->ppstream.next_out++ = (unsigned char)sym; zip->ppstream.avail_out--; zip->ppstream.total_out++; if (flush_bytes) flush_bytes--; } while (zip->ppstream.avail_out && (zip->ppstream.avail_in || flush_bytes)); t_avail_in = (size_t)zip->ppstream.avail_in; t_avail_out = (size_t)zip->ppstream.avail_out; break; } default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression internal error"); return (ARCHIVE_FAILED); } if (ret != ARCHIVE_OK && ret != ARCHIVE_EOF) return (ret); *used = o_avail_in - t_avail_in; *outbytes = o_avail_out - t_avail_out; /* * Decord BCJ. */ if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { size_t l = x86_Convert(zip, buff, *outbytes); zip->odd_bcj_size = *outbytes - l; if (zip->odd_bcj_size > 0 && zip->odd_bcj_size <= 4 && o_avail_in && ret != ARCHIVE_EOF) { memcpy(zip->odd_bcj, ((unsigned char *)buff) + l, zip->odd_bcj_size); *outbytes = l; } else zip->odd_bcj_size = 0; } /* * Decord BCJ2 with a decompressed main stream. */ if (zip->codec2 == _7Z_X86_BCJ2) { ssize_t bytes; zip->tmp_stream_bytes_avail = zip->tmp_stream_buff_size - t_avail_out; if (zip->tmp_stream_bytes_avail > zip->main_stream_bytes_remaining) zip->tmp_stream_bytes_avail = zip->main_stream_bytes_remaining; zip->tmp_stream_bytes_remaining = zip->tmp_stream_bytes_avail; bytes = Bcj2_Decode(zip, bcj2_next_out, bcj2_avail_out); if (bytes < 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed"); return (ARCHIVE_FAILED); } zip->main_stream_bytes_remaining -= zip->tmp_stream_bytes_avail - zip->tmp_stream_bytes_remaining; bcj2_avail_out -= bytes; *outbytes = o_avail_out - bcj2_avail_out; } return (ret); } static int free_decompression(struct archive_read *a, struct _7zip *zip) { int r = ARCHIVE_OK; #if !defined(HAVE_ZLIB_H) &&\ !(defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)) (void)a;/* UNUSED */ #endif #ifdef HAVE_LZMA_H if (zip->lzstream_valid) lzma_end(&(zip->lzstream)); #endif #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (zip->bzstream_valid) { if (BZ2_bzDecompressEnd(&(zip->bzstream)) != BZ_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up bzip2 decompressor"); r = ARCHIVE_FATAL; } zip->bzstream_valid = 0; } #endif #ifdef HAVE_ZLIB_H if (zip->stream_valid) { if (inflateEnd(&(zip->stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up zlib decompressor"); r = ARCHIVE_FATAL; } zip->stream_valid = 0; } #endif if (zip->ppmd7_valid) { __archive_ppmd7_functions.Ppmd7_Free( &zip->ppmd7_context); zip->ppmd7_valid = 0; } return (r); } static int parse_7zip_uint64(struct archive_read *a, uint64_t *val) { const unsigned char *p; unsigned char avail, mask; int i; if ((p = header_bytes(a, 1)) == NULL) return (-1); avail = *p; mask = 0x80; *val = 0; for (i = 0; i < 8; i++) { if (avail & mask) { if ((p = header_bytes(a, 1)) == NULL) return (-1); *val |= ((uint64_t)*p) << (8 * i); mask >>= 1; continue; } *val += ((uint64_t)(avail & (mask -1))) << (8 * i); break; } return (0); } static int read_Bools(struct archive_read *a, unsigned char *data, size_t num) { const unsigned char *p; unsigned i, mask = 0, avail = 0; for (i = 0; i < num; i++) { if (mask == 0) { if ((p = header_bytes(a, 1)) == NULL) return (-1); avail = *p; mask = 0x80; } data[i] = (avail & mask)?1:0; mask >>= 1; } return (0); } static void free_Digest(struct _7z_digests *d) { free(d->defineds); free(d->digests); } static int read_Digests(struct archive_read *a, struct _7z_digests *d, size_t num) { const unsigned char *p; unsigned i; if (num == 0) return (-1); memset(d, 0, sizeof(*d)); d->defineds = malloc(num); if (d->defineds == NULL) return (-1); /* * Read Bools. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) { if (read_Bools(a, d->defineds, num) < 0) return (-1); } else /* All are defined */ memset(d->defineds, 1, num); d->digests = calloc(num, sizeof(*d->digests)); if (d->digests == NULL) return (-1); for (i = 0; i < num; i++) { if (d->defineds[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); d->digests[i] = archive_le32dec(p); } } return (0); } static void free_PackInfo(struct _7z_pack_info *pi) { free(pi->sizes); free(pi->positions); free_Digest(&(pi->digest)); } static int read_PackInfo(struct archive_read *a, struct _7z_pack_info *pi) { const unsigned char *p; unsigned i; memset(pi, 0, sizeof(*pi)); /* * Read PackPos. */ if (parse_7zip_uint64(a, &(pi->pos)) < 0) return (-1); /* * Read NumPackStreams. */ if (parse_7zip_uint64(a, &(pi->numPackStreams)) < 0) return (-1); if (pi->numPackStreams == 0) return (-1); if (UMAX_ENTRY < pi->numPackStreams) return (-1); /* * Read PackSizes[num] */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kEnd) /* PackSizes[num] are not present. */ return (0); if (*p != kSize) return (-1); pi->sizes = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); pi->positions = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); if (pi->sizes == NULL || pi->positions == NULL) return (-1); for (i = 0; i < pi->numPackStreams; i++) { if (parse_7zip_uint64(a, &(pi->sizes[i])) < 0) return (-1); } /* * Read PackStreamDigests[num] */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kEnd) { /* PackStreamDigests[num] are not present. */ pi->digest.defineds = calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.defineds)); pi->digest.digests = calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.digests)); if (pi->digest.defineds == NULL || pi->digest.digests == NULL) return (-1); return (0); } if (*p != kSize) return (-1); if (read_Digests(a, &(pi->digest), (size_t)pi->numPackStreams) < 0) return (-1); /* * Must be marked by kEnd. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kEnd) return (-1); return (0); } static void free_Folder(struct _7z_folder *f) { unsigned i; if (f->coders) { for (i = 0; i< f->numCoders; i++) { free(f->coders[i].properties); } free(f->coders); } free(f->bindPairs); free(f->packedStreams); free(f->unPackSize); } static int read_Folder(struct archive_read *a, struct _7z_folder *f) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; uint64_t numInStreamsTotal = 0; uint64_t numOutStreamsTotal = 0; unsigned i; memset(f, 0, sizeof(*f)); /* * Read NumCoders. */ if (parse_7zip_uint64(a, &(f->numCoders)) < 0) return (-1); if (f->numCoders > 4) /* Too many coders. */ return (-1); f->coders = calloc((size_t)f->numCoders, sizeof(*f->coders)); if (f->coders == NULL) return (-1); for (i = 0; i< f->numCoders; i++) { size_t codec_size; int simple, attr; if ((p = header_bytes(a, 1)) == NULL) return (-1); /* * 0:3 CodecIdSize * 4: 0 - IsSimple * 1 - Is not Simple * 5: 0 - No Attributes * 1 - There are Attributes; * 7: Must be zero. */ codec_size = *p & 0xf; simple = (*p & 0x10)?0:1; attr = *p & 0x20; if (*p & 0x80) return (-1);/* Not supported. */ /* * Read Decompression Method IDs. */ if ((p = header_bytes(a, codec_size)) == NULL) return (-1); f->coders[i].codec = decode_codec_id(p, codec_size); if (simple) { f->coders[i].numInStreams = 1; f->coders[i].numOutStreams = 1; } else { if (parse_7zip_uint64( a, &(f->coders[i].numInStreams)) < 0) return (-1); if (UMAX_ENTRY < f->coders[i].numInStreams) return (-1); if (parse_7zip_uint64( a, &(f->coders[i].numOutStreams)) < 0) return (-1); if (UMAX_ENTRY < f->coders[i].numOutStreams) return (-1); } if (attr) { if (parse_7zip_uint64( a, &(f->coders[i].propertiesSize)) < 0) return (-1); if ((p = header_bytes( a, (size_t)f->coders[i].propertiesSize)) == NULL) return (-1); f->coders[i].properties = malloc((size_t)f->coders[i].propertiesSize); if (f->coders[i].properties == NULL) return (-1); memcpy(f->coders[i].properties, p, (size_t)f->coders[i].propertiesSize); } numInStreamsTotal += f->coders[i].numInStreams; numOutStreamsTotal += f->coders[i].numOutStreams; } if (numOutStreamsTotal == 0 || numInStreamsTotal < numOutStreamsTotal-1) return (-1); f->numBindPairs = numOutStreamsTotal - 1; if (zip->header_bytes_remaining < f->numBindPairs) return (-1); if (f->numBindPairs > 0) { f->bindPairs = calloc((size_t)f->numBindPairs, sizeof(*f->bindPairs)); if (f->bindPairs == NULL) return (-1); } else f->bindPairs = NULL; for (i = 0; i < f->numBindPairs; i++) { if (parse_7zip_uint64(a, &(f->bindPairs[i].inIndex)) < 0) return (-1); if (UMAX_ENTRY < f->bindPairs[i].inIndex) return (-1); if (parse_7zip_uint64(a, &(f->bindPairs[i].outIndex)) < 0) return (-1); if (UMAX_ENTRY < f->bindPairs[i].outIndex) return (-1); } f->numPackedStreams = numInStreamsTotal - f->numBindPairs; f->packedStreams = calloc((size_t)f->numPackedStreams, sizeof(*f->packedStreams)); if (f->packedStreams == NULL) return (-1); if (f->numPackedStreams == 1) { for (i = 0; i < numInStreamsTotal; i++) { unsigned j; for (j = 0; j < f->numBindPairs; j++) { if (f->bindPairs[j].inIndex == i) break; } if (j == f->numBindPairs) break; } if (i == numInStreamsTotal) return (-1); f->packedStreams[0] = i; } else { for (i = 0; i < f->numPackedStreams; i++) { if (parse_7zip_uint64(a, &(f->packedStreams[i])) < 0) return (-1); if (UMAX_ENTRY < f->packedStreams[i]) return (-1); } } f->numInStreams = numInStreamsTotal; f->numOutStreams = numOutStreamsTotal; return (0); } static void free_CodersInfo(struct _7z_coders_info *ci) { unsigned i; if (ci->folders) { for (i = 0; i < ci->numFolders; i++) free_Folder(&(ci->folders[i])); free(ci->folders); } } static int read_CodersInfo(struct archive_read *a, struct _7z_coders_info *ci) { const unsigned char *p; struct _7z_digests digest; unsigned i; memset(ci, 0, sizeof(*ci)); memset(&digest, 0, sizeof(digest)); if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kFolder) goto failed; /* * Read NumFolders. */ if (parse_7zip_uint64(a, &(ci->numFolders)) < 0) goto failed; if (UMAX_ENTRY < ci->numFolders) return (-1); /* * Read External. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; switch (*p) { case 0: ci->folders = calloc((size_t)ci->numFolders, sizeof(*ci->folders)); if (ci->folders == NULL) return (-1); for (i = 0; i < ci->numFolders; i++) { if (read_Folder(a, &(ci->folders[i])) < 0) goto failed; } break; case 1: if (parse_7zip_uint64(a, &(ci->dataStreamIndex)) < 0) return (-1); if (UMAX_ENTRY < ci->dataStreamIndex) return (-1); if (ci->numFolders > 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); goto failed; } break; default: archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); goto failed; } if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kCodersUnPackSize) goto failed; for (i = 0; i < ci->numFolders; i++) { struct _7z_folder *folder = &(ci->folders[i]); unsigned j; folder->unPackSize = calloc((size_t)folder->numOutStreams, sizeof(*folder->unPackSize)); if (folder->unPackSize == NULL) goto failed; for (j = 0; j < folder->numOutStreams; j++) { if (parse_7zip_uint64(a, &(folder->unPackSize[j])) < 0) goto failed; } } /* * Read CRCs. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p == kEnd) return (0); if (*p != kCRC) goto failed; if (read_Digests(a, &digest, (size_t)ci->numFolders) < 0) goto failed; for (i = 0; i < ci->numFolders; i++) { ci->folders[i].digest_defined = digest.defineds[i]; ci->folders[i].digest = digest.digests[i]; } /* * Must be kEnd. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kEnd) goto failed; free_Digest(&digest); return (0); failed: free_Digest(&digest); return (-1); } static uint64_t folder_uncompressed_size(struct _7z_folder *f) { int n = (int)f->numOutStreams; unsigned pairs = (unsigned)f->numBindPairs; while (--n >= 0) { unsigned i; for (i = 0; i < pairs; i++) { if (f->bindPairs[i].outIndex == (uint64_t)n) break; } if (i >= pairs) return (f->unPackSize[n]); } return (0); } static void free_SubStreamsInfo(struct _7z_substream_info *ss) { free(ss->unpackSizes); free(ss->digestsDefined); free(ss->digests); } static int read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { return (-1); } unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); } static void free_StreamsInfo(struct _7z_stream_info *si) { free_PackInfo(&(si->pi)); free_CodersInfo(&(si->ci)); free_SubStreamsInfo(&(si->ss)); } static int read_StreamsInfo(struct archive_read *a, struct _7z_stream_info *si) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; unsigned i; memset(si, 0, sizeof(*si)); if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kPackInfo) { uint64_t packPos; if (read_PackInfo(a, &(si->pi)) < 0) return (-1); if (si->pi.positions == NULL || si->pi.sizes == NULL) return (-1); /* * Calculate packed stream positions. */ packPos = si->pi.pos; for (i = 0; i < si->pi.numPackStreams; i++) { si->pi.positions[i] = packPos; packPos += si->pi.sizes[i]; if (packPos > zip->header_offset) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kUnPackInfo) { uint32_t packIndex; struct _7z_folder *f; if (read_CodersInfo(a, &(si->ci)) < 0) return (-1); /* * Calculate packed stream indexes. */ packIndex = 0; f = si->ci.folders; for (i = 0; i < si->ci.numFolders; i++) { f[i].packIndex = packIndex; packIndex += (uint32_t)f[i].numPackedStreams; if (packIndex > si->pi.numPackStreams) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kSubStreamsInfo) { if (read_SubStreamsInfo(a, &(si->ss), si->ci.folders, (size_t)si->ci.numFolders) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Must be kEnd. */ if (*p != kEnd) return (-1); return (0); } static void free_Header(struct _7z_header_info *h) { free(h->emptyStreamBools); free(h->emptyFileBools); free(h->antiBools); free(h->attrBools); } static int read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: if (h->emptyStreamBools != NULL) return (-1); h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } if (h->emptyFileBools != NULL) return (-1); h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } if (h->antiBools != NULL) return (-1); h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); if (zip->entry_names != NULL) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; if (h->attrBools != NULL) return (-1); h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; __LA_FALLTHROUGH; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); } #define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) static void fileTimeToUtc(uint64_t fileTime, time_t *timep, long *ns) { if (fileTime >= EPOC_TIME) { fileTime -= EPOC_TIME; /* milli seconds base */ *timep = (time_t)(fileTime / 10000000); /* nano seconds base */ *ns = (long)(fileTime % 10000000) * 100; } else { *timep = 0; *ns = 0; } } static int read_Times(struct archive_read *a, struct _7z_header_info *h, int type) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7zip_entry *entries = zip->entries; unsigned char *timeBools; int allAreDefined; unsigned i; timeBools = calloc((size_t)zip->numFiles, sizeof(*timeBools)); if (timeBools == NULL) return (-1); /* Read allAreDefined. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; allAreDefined = *p; if (allAreDefined) memset(timeBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, timeBools, (size_t)zip->numFiles) < 0) goto failed; } /* Read external. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p) { if (parse_7zip_uint64(a, &(h->dataIndex)) < 0) goto failed; if (UMAX_ENTRY < h->dataIndex) goto failed; } for (i = 0; i < zip->numFiles; i++) { if (!timeBools[i]) continue; if ((p = header_bytes(a, 8)) == NULL) goto failed; switch (type) { case kCTime: fileTimeToUtc(archive_le64dec(p), &(entries[i].ctime), &(entries[i].ctime_ns)); entries[i].flg |= CTIME_IS_SET; break; case kATime: fileTimeToUtc(archive_le64dec(p), &(entries[i].atime), &(entries[i].atime_ns)); entries[i].flg |= ATIME_IS_SET; break; case kMTime: fileTimeToUtc(archive_le64dec(p), &(entries[i].mtime), &(entries[i].mtime_ns)); entries[i].flg |= MTIME_IS_SET; break; } } free(timeBools); return (0); failed: free(timeBools); return (-1); } static int decode_encoded_header_info(struct archive_read *a, struct _7z_stream_info *si) { struct _7zip *zip = (struct _7zip *)a->format->data; errno = 0; if (read_StreamsInfo(a, si) < 0) { if (errno == ENOMEM) archive_set_error(&a->archive, -1, "Couldn't allocate memory"); else archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } if (si->pi.numPackStreams == 0 || si->ci.numFolders == 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } if (zip->header_offset < si->pi.pos + si->pi.sizes[0] || (int64_t)(si->pi.pos + si->pi.sizes[0]) < 0 || si->pi.sizes[0] == 0 || (int64_t)si->pi.pos < 0) { archive_set_error(&a->archive, -1, "Malformed Header offset"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } static const unsigned char * header_bytes(struct archive_read *a, size_t rbytes) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; if (zip->header_bytes_remaining < rbytes) return (NULL); if (zip->pack_stream_bytes_unconsumed) read_consume(a); if (zip->header_is_encoded == 0) { p = __archive_read_ahead(a, rbytes, NULL); if (p == NULL) return (NULL); zip->header_bytes_remaining -= rbytes; zip->pack_stream_bytes_unconsumed = rbytes; } else { const void *buff; ssize_t bytes; bytes = read_stream(a, &buff, rbytes, rbytes); if (bytes <= 0) return (NULL); zip->header_bytes_remaining -= bytes; p = buff; } /* Update checksum */ zip->header_crc32 = crc32(zip->header_crc32, p, (unsigned)rbytes); return (p); } static int slurp_central_directory(struct archive_read *a, struct _7zip *zip, struct _7z_header_info *header) { const unsigned char *p; uint64_t next_header_offset; uint64_t next_header_size; uint32_t next_header_crc; ssize_t bytes_avail; int check_header_crc, r; if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) return (ARCHIVE_FATAL); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is an executable ? Must be self-extracting... */ r = skip_sfx(a, bytes_avail); if (r < ARCHIVE_WARN) return (r); if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) return (ARCHIVE_FATAL); } zip->seek_base += 32; if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) { archive_set_error(&a->archive, -1, "Not 7-Zip archive file"); return (ARCHIVE_FATAL); } /* CRC check. */ if (crc32(0, (const unsigned char *)p + 12, 20) != archive_le32dec(p + 8)) { archive_set_error(&a->archive, -1, "Header CRC error"); return (ARCHIVE_FATAL); } next_header_offset = archive_le64dec(p + 12); next_header_size = archive_le64dec(p + 20); next_header_crc = archive_le32dec(p + 28); if (next_header_size == 0) /* There is no entry in an archive file. */ return (ARCHIVE_EOF); if (((int64_t)next_header_offset) < 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 32); if (next_header_offset != 0) { if (bytes_avail >= (ssize_t)next_header_offset) __archive_read_consume(a, next_header_offset); else if (__archive_read_seek(a, next_header_offset + zip->seek_base, SEEK_SET) < 0) return (ARCHIVE_FATAL); } zip->stream_offset = next_header_offset; zip->header_offset = next_header_offset; zip->header_bytes_remaining = next_header_size; zip->header_crc32 = 0; zip->header_is_encoded = 0; zip->header_is_being_read = 1; zip->has_encrypted_entries = 0; check_header_crc = 1; if ((p = header_bytes(a, 1)) == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } /* Parse ArchiveProperties. */ switch (p[0]) { case kEncodedHeader: /* * The archive has an encoded header and we have to decode it * in order to parse the header correctly. */ r = decode_encoded_header_info(a, &(zip->si)); /* Check the EncodedHeader CRC.*/ if (r == 0 && zip->header_crc32 != next_header_crc) { archive_set_error(&a->archive, -1, "Damaged 7-Zip archive"); r = -1; } if (r == 0) { if (zip->si.ci.folders[0].digest_defined) next_header_crc = zip->si.ci.folders[0].digest; else check_header_crc = 0; if (zip->pack_stream_bytes_unconsumed) read_consume(a); r = setup_decode_folder(a, zip->si.ci.folders, 1); if (r == 0) { zip->header_bytes_remaining = zip->folder_outbytes_remaining; r = seek_pack(a); } } /* Clean up StreamsInfo. */ free_StreamsInfo(&(zip->si)); memset(&(zip->si), 0, sizeof(zip->si)); if (r < 0) return (ARCHIVE_FATAL); zip->header_is_encoded = 1; zip->header_crc32 = 0; /* FALL THROUGH */ case kHeader: /* * Parse the header. */ errno = 0; r = read_Header(a, header, zip->header_is_encoded); if (r < 0) { if (errno == ENOMEM) archive_set_error(&a->archive, -1, "Couldn't allocate memory"); else archive_set_error(&a->archive, -1, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } /* * Must be kEnd. */ if ((p = header_bytes(a, 1)) == NULL ||*p != kEnd) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } /* Check the Header CRC.*/ if (check_header_crc && zip->header_crc32 != next_header_crc) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } break; default: archive_set_error(&a->archive, -1, "Unexpected Property ID = %X", p[0]); return (ARCHIVE_FATAL); } /* Clean up variables be used for decoding the archive header */ zip->pack_stream_remaining = 0; zip->pack_stream_index = 0; zip->folder_outbytes_remaining = 0; zip->uncompressed_buffer_bytes_remaining = 0; zip->pack_stream_bytes_unconsumed = 0; zip->header_is_being_read = 0; return (ARCHIVE_OK); } static ssize_t get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { /* Copy mode. */ *buff = __archive_read_ahead(a, minimum, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file data"); return (ARCHIVE_FATAL); } if ((size_t)bytes_avail > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; if ((size_t)bytes_avail > size) bytes_avail = (ssize_t)size; zip->pack_stream_bytes_unconsumed = bytes_avail; } else if (zip->uncompressed_buffer_pointer == NULL) { /* Decompression has failed. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } else { /* Packed mode. */ if (minimum > zip->uncompressed_buffer_bytes_remaining) { /* * If remaining uncompressed data size is less than * the minimum size, fill the buffer up to the * minimum size. */ if (extract_pack_stream(a, minimum) < 0) return (ARCHIVE_FATAL); } if (size > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; else bytes_avail = (ssize_t)size; *buff = zip->uncompressed_buffer_pointer; zip->uncompressed_buffer_pointer += bytes_avail; } zip->uncompressed_buffer_bytes_remaining -= bytes_avail; return (bytes_avail); } static ssize_t extract_pack_stream(struct archive_read *a, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; int r; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { if (minimum == 0) minimum = 1; if (__archive_read_ahead(a, minimum, &bytes_avail) == NULL || bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } if (bytes_avail > (ssize_t)zip->pack_stream_inbytes_remaining) bytes_avail = (ssize_t)zip->pack_stream_inbytes_remaining; zip->pack_stream_inbytes_remaining -= bytes_avail; if (bytes_avail > (ssize_t)zip->folder_outbytes_remaining) bytes_avail = (ssize_t)zip->folder_outbytes_remaining; zip->folder_outbytes_remaining -= bytes_avail; zip->uncompressed_buffer_bytes_remaining = bytes_avail; return (ARCHIVE_OK); } /* If the buffer hasn't been allocated, allocate it now. */ if (zip->uncompressed_buffer == NULL) { zip->uncompressed_buffer_size = UBUFF_SIZE; if (zip->uncompressed_buffer_size < minimum) { zip->uncompressed_buffer_size = minimum + 1023; zip->uncompressed_buffer_size &= ~0x3ff; } zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size); if (zip->uncompressed_buffer == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer_bytes_remaining = 0; } else if (zip->uncompressed_buffer_size < minimum || zip->uncompressed_buffer_bytes_remaining < minimum) { /* * Make sure the uncompressed buffer can have bytes * at least `minimum' bytes. * NOTE: This case happen when reading the header. */ size_t used; if (zip->uncompressed_buffer_pointer != 0) used = zip->uncompressed_buffer_pointer - zip->uncompressed_buffer; else used = 0; if (zip->uncompressed_buffer_size < minimum) { /* * Expand the uncompressed buffer up to * the minimum size. */ void *p; size_t new_size; new_size = minimum + 1023; new_size &= ~0x3ff; p = realloc(zip->uncompressed_buffer, new_size); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer = (unsigned char *)p; zip->uncompressed_buffer_size = new_size; } /* * Move unconsumed bytes to the head. */ if (used) { memmove(zip->uncompressed_buffer, zip->uncompressed_buffer + used, zip->uncompressed_buffer_bytes_remaining); } } else zip->uncompressed_buffer_bytes_remaining = 0; zip->uncompressed_buffer_pointer = NULL; for (;;) { size_t bytes_in, bytes_out; const void *buff_in; unsigned char *buff_out; int end_of_data; /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ buff_in = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } buff_out = zip->uncompressed_buffer + zip->uncompressed_buffer_bytes_remaining; bytes_out = zip->uncompressed_buffer_size - zip->uncompressed_buffer_bytes_remaining; bytes_in = bytes_avail; if (bytes_in > zip->pack_stream_inbytes_remaining) bytes_in = (size_t)zip->pack_stream_inbytes_remaining; /* Drive decompression. */ r = decompress(a, zip, buff_out, &bytes_out, buff_in, &bytes_in); switch (r) { case ARCHIVE_OK: end_of_data = 0; break; case ARCHIVE_EOF: end_of_data = 1; break; default: return (ARCHIVE_FATAL); } zip->pack_stream_inbytes_remaining -= bytes_in; if (bytes_out > zip->folder_outbytes_remaining) bytes_out = (size_t)zip->folder_outbytes_remaining; zip->folder_outbytes_remaining -= bytes_out; zip->uncompressed_buffer_bytes_remaining += bytes_out; zip->pack_stream_bytes_unconsumed = bytes_in; /* * Continue decompression until uncompressed_buffer is full. */ if (zip->uncompressed_buffer_bytes_remaining == zip->uncompressed_buffer_size) break; if (zip->codec2 == _7Z_X86 && zip->odd_bcj_size && zip->uncompressed_buffer_bytes_remaining + 5 > zip->uncompressed_buffer_size) break; if (zip->pack_stream_inbytes_remaining == 0 && zip->folder_outbytes_remaining == 0) break; if (end_of_data || (bytes_in == 0 && bytes_out == 0)) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } read_consume(a); } if (zip->uncompressed_buffer_bytes_remaining < minimum) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer_pointer = zip->uncompressed_buffer; return (ARCHIVE_OK); } static int seek_pack(struct archive_read *a) { struct _7zip *zip = (struct _7zip *)a->format->data; int64_t pack_offset; if (zip->pack_stream_remaining <= 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } zip->pack_stream_inbytes_remaining = zip->si.pi.sizes[zip->pack_stream_index]; pack_offset = zip->si.pi.positions[zip->pack_stream_index]; if (zip->stream_offset != pack_offset) { if (0 > __archive_read_seek(a, pack_offset + zip->seek_base, SEEK_SET)) return (ARCHIVE_FATAL); zip->stream_offset = pack_offset; } zip->pack_stream_index++; zip->pack_stream_remaining--; return (ARCHIVE_OK); } static ssize_t read_stream(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; uint64_t skip_bytes = 0; ssize_t r; if (zip->uncompressed_buffer_bytes_remaining == 0) { if (zip->pack_stream_inbytes_remaining > 0) { r = extract_pack_stream(a, 0); if (r < 0) return (r); return (get_uncompressed_data(a, buff, size, minimum)); } else if (zip->folder_outbytes_remaining > 0) { /* Extract a remaining pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); return (get_uncompressed_data(a, buff, size, minimum)); } } else return (get_uncompressed_data(a, buff, size, minimum)); /* * Current pack stream has been consumed. */ if (zip->pack_stream_remaining == 0) { if (zip->header_is_being_read) { /* Invalid sequence. This might happen when * reading a malformed archive. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } /* * All current folder's pack streams have been * consumed. Switch to next folder. */ if (zip->folder_index == 0 && (zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes || zip->folder_index != zip->entry->folderIndex)) { zip->folder_index = zip->entry->folderIndex; skip_bytes = zip->si.ci.folders[zip->folder_index].skipped_bytes; } if (zip->folder_index >= zip->si.ci.numFolders) { /* * We have consumed all folders and its pack streams. */ *buff = NULL; return (0); } r = setup_decode_folder(a, &(zip->si.ci.folders[zip->folder_index]), 0); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); zip->folder_index++; } /* * Switch to next pack stream. */ r = seek_pack(a); if (r < 0) return (r); /* Extract a new pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); /* * Skip the bytes we already has skipped in skip_stream(). */ while (skip_bytes) { ssize_t skipped; if (zip->uncompressed_buffer_bytes_remaining == 0) { if (zip->pack_stream_inbytes_remaining > 0) { r = extract_pack_stream(a, 0); if (r < 0) return (r); } else if (zip->folder_outbytes_remaining > 0) { /* Extract a remaining pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } } skipped = get_uncompressed_data( a, buff, (size_t)skip_bytes, 0); if (skipped < 0) return (skipped); skip_bytes -= skipped; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } return (get_uncompressed_data(a, buff, size, minimum)); } static int setup_decode_folder(struct archive_read *a, struct _7z_folder *folder, int header) { struct _7zip *zip = (struct _7zip *)a->format->data; const struct _7z_coder *coder1, *coder2; const char *cname = (header)?"archive header":"file content"; unsigned i; int r, found_bcj2 = 0; /* * Release the memory which the previous folder used for BCJ2. */ for (i = 0; i < 3; i++) { if (zip->sub_stream_buff[i] != NULL) free(zip->sub_stream_buff[i]); zip->sub_stream_buff[i] = NULL; } /* * Initialize a stream reader. */ zip->pack_stream_remaining = (unsigned)folder->numPackedStreams; zip->pack_stream_index = (unsigned)folder->packIndex; zip->folder_outbytes_remaining = folder_uncompressed_size(folder); zip->uncompressed_buffer_bytes_remaining = 0; /* * Check coder types. */ for (i = 0; i < folder->numCoders; i++) { switch(folder->coders[i].codec) { case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: { /* For entry that is associated with this folder, mark it as encrypted (data+metadata). */ zip->has_encrypted_entries = 1; if (a->entry) { archive_entry_set_is_data_encrypted(a->entry, 1); archive_entry_set_is_metadata_encrypted(a->entry, 1); } archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "The %s is encrypted, " "but currently not supported", cname); return (ARCHIVE_FATAL); } case _7Z_X86_BCJ2: { found_bcj2++; break; } } } /* Now that we've checked for encryption, if there were still no * encrypted entries found we can say for sure that there are none. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if ((folder->numCoders > 2 && !found_bcj2) || found_bcj2 > 1) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "The %s is encoded with many filters, " "but currently not supported", cname); return (ARCHIVE_FATAL); } coder1 = &(folder->coders[0]); if (folder->numCoders == 2) coder2 = &(folder->coders[1]); else coder2 = NULL; if (found_bcj2) { /* * Preparation to decode BCJ2. * Decoding BCJ2 requires four sources. Those are at least, * as far as I know, two types of the storage form. */ const struct _7z_coder *fc = folder->coders; static const struct _7z_coder coder_copy = {0, 1, 1, 0, NULL}; const struct _7z_coder *scoder[3] = {&coder_copy, &coder_copy, &coder_copy}; const void *buff; ssize_t bytes; unsigned char *b[3] = {NULL, NULL, NULL}; uint64_t sunpack[3] ={-1, -1, -1}; size_t s[3] = {0, 0, 0}; int idx[3] = {0, 1, 2}; if (folder->numCoders == 4 && fc[3].codec == _7Z_X86_BCJ2 && folder->numInStreams == 7 && folder->numOutStreams == 4 && zip->pack_stream_remaining == 4) { /* Source type 1 made by 7zr or 7z with -m options. */ if (folder->bindPairs[0].inIndex == 5) { /* The form made by 7zr */ idx[0] = 1; idx[1] = 2; idx[2] = 0; scoder[1] = &(fc[1]); scoder[2] = &(fc[0]); sunpack[1] = folder->unPackSize[1]; sunpack[2] = folder->unPackSize[0]; coder1 = &(fc[2]); } else { /* * NOTE: Some patterns do not work. * work: * 7z a -m0=BCJ2 -m1=COPY -m2=COPY * -m3=(any) * 7z a -m0=BCJ2 -m1=COPY -m2=(any) * -m3=COPY * 7z a -m0=BCJ2 -m1=(any) -m2=COPY * -m3=COPY * not work: * other patterns. * * We have to handle this like `pipe' or * our libarchive7s filter frame work, * decoding the BCJ2 main stream sequentially, * m3 -> m2 -> m1 -> BCJ2. * */ if (fc[0].codec == _7Z_COPY && fc[1].codec == _7Z_COPY) coder1 = &(folder->coders[2]); else if (fc[0].codec == _7Z_COPY && fc[2].codec == _7Z_COPY) coder1 = &(folder->coders[1]); else if (fc[1].codec == _7Z_COPY && fc[2].codec == _7Z_COPY) coder1 = &(folder->coders[0]); else { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unsupported form of " "BCJ2 streams"); return (ARCHIVE_FATAL); } } coder2 = &(fc[3]); zip->main_stream_bytes_remaining = (size_t)folder->unPackSize[2]; } else if (coder2 != NULL && coder2->codec == _7Z_X86_BCJ2 && zip->pack_stream_remaining == 4 && folder->numInStreams == 5 && folder->numOutStreams == 2) { /* Source type 0 made by 7z */ zip->main_stream_bytes_remaining = (size_t)folder->unPackSize[0]; } else { /* We got an unexpected form. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unsupported form of BCJ2 streams"); return (ARCHIVE_FATAL); } /* Skip the main stream at this time. */ if ((r = seek_pack(a)) < 0) return (r); zip->pack_stream_bytes_unconsumed = (size_t)zip->pack_stream_inbytes_remaining; read_consume(a); /* Read following three sub streams. */ for (i = 0; i < 3; i++) { const struct _7z_coder *coder = scoder[i]; if ((r = seek_pack(a)) < 0) { free(b[0]); free(b[1]); free(b[2]); return (r); } if (sunpack[i] == (uint64_t)-1) zip->folder_outbytes_remaining = zip->pack_stream_inbytes_remaining; else zip->folder_outbytes_remaining = sunpack[i]; r = init_decompression(a, zip, coder, NULL); if (r != ARCHIVE_OK) { free(b[0]); free(b[1]); free(b[2]); return (ARCHIVE_FATAL); } /* Allocate memory for the decoded data of a sub * stream. */ b[i] = malloc((size_t)zip->folder_outbytes_remaining); if (b[i] == NULL) { free(b[0]); free(b[1]); free(b[2]); archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } /* Extract a sub stream. */ while (zip->pack_stream_inbytes_remaining > 0) { r = (int)extract_pack_stream(a, 0); if (r < 0) { free(b[0]); free(b[1]); free(b[2]); return (r); } bytes = get_uncompressed_data(a, &buff, zip->uncompressed_buffer_bytes_remaining, 0); if (bytes < 0) { free(b[0]); free(b[1]); free(b[2]); return ((int)bytes); } memcpy(b[i]+s[i], buff, bytes); s[i] += bytes; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } } /* Set the sub streams to the right place. */ for (i = 0; i < 3; i++) { zip->sub_stream_buff[i] = b[idx[i]]; zip->sub_stream_size[i] = s[idx[i]]; zip->sub_stream_bytes_remaining[i] = s[idx[i]]; } /* Allocate memory used for decoded main stream bytes. */ if (zip->tmp_stream_buff == NULL) { zip->tmp_stream_buff_size = 32 * 1024; zip->tmp_stream_buff = malloc(zip->tmp_stream_buff_size); if (zip->tmp_stream_buff == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } } zip->tmp_stream_bytes_avail = 0; zip->tmp_stream_bytes_remaining = 0; zip->odd_bcj_size = 0; zip->bcj2_outPos = 0; /* * Reset a stream reader in order to read the main stream * of BCJ2. */ zip->pack_stream_remaining = 1; zip->pack_stream_index = (unsigned)folder->packIndex; zip->folder_outbytes_remaining = folder_uncompressed_size(folder); zip->uncompressed_buffer_bytes_remaining = 0; } /* * Initialize the decompressor for the new folder's pack streams. */ r = init_decompression(a, zip, coder1, coder2); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } static int64_t skip_stream(struct archive_read *a, size_t skip_bytes) { struct _7zip *zip = (struct _7zip *)a->format->data; const void *p; int64_t skipped_bytes; size_t bytes = skip_bytes; if (zip->folder_index == 0) { /* * Optimization for a list mode. * Avoid unnecessary decoding operations. */ zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes += skip_bytes; return (skip_bytes); } while (bytes) { skipped_bytes = read_stream(a, &p, bytes, 0); if (skipped_bytes < 0) return (skipped_bytes); if (skipped_bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } bytes -= (size_t)skipped_bytes; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } return (skip_bytes); } /* * Brought from LZMA SDK. * * Bra86.c -- Converter for x86 code (BCJ) * 2008-10-04 : Igor Pavlov : Public domain * */ #define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) static void x86_Init(struct _7zip *zip) { zip->bcj_state = 0; zip->bcj_prevPosT = (size_t)0 - 1; zip->bcj_prevMask = 0; zip->bcj_ip = 5; } static size_t x86_Convert(struct _7zip *zip, uint8_t *data, size_t size) { static const uint8_t kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; static const uint8_t kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; size_t bufferPos, prevPosT; uint32_t ip, prevMask; if (size < 5) return 0; bufferPos = 0; prevPosT = zip->bcj_prevPosT; prevMask = zip->bcj_prevMask; ip = zip->bcj_ip; for (;;) { uint8_t *p = data + bufferPos; uint8_t *limit = data + size - 4; for (; p < limit; p++) if ((*p & 0xFE) == 0xE8) break; bufferPos = (size_t)(p - data); if (p >= limit) break; prevPosT = bufferPos - prevPosT; if (prevPosT > 3) prevMask = 0; else { prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; if (prevMask != 0) { unsigned char b = p[4 - kMaskToBitNumber[prevMask]]; if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) { prevPosT = bufferPos; prevMask = ((prevMask << 1) & 0x7) | 1; bufferPos++; continue; } } } prevPosT = bufferPos; if (Test86MSByte(p[4])) { uint32_t src = ((uint32_t)p[4] << 24) | ((uint32_t)p[3] << 16) | ((uint32_t)p[2] << 8) | ((uint32_t)p[1]); uint32_t dest; for (;;) { uint8_t b; int b_index; dest = src - (ip + (uint32_t)bufferPos); if (prevMask == 0) break; b_index = kMaskToBitNumber[prevMask] * 8; b = (uint8_t)(dest >> (24 - b_index)); if (!Test86MSByte(b)) break; src = dest ^ ((1 << (32 - b_index)) - 1); } p[4] = (uint8_t)(~(((dest >> 24) & 1) - 1)); p[3] = (uint8_t)(dest >> 16); p[2] = (uint8_t)(dest >> 8); p[1] = (uint8_t)dest; bufferPos += 5; } else { prevMask = ((prevMask << 1) & 0x7) | 1; bufferPos++; } } zip->bcj_prevPosT = prevPosT; zip->bcj_prevMask = prevMask; zip->bcj_ip += (uint32_t)bufferPos; return (bufferPos); } /* * Brought from LZMA SDK. * * Bcj2.c -- Converter for x86 code (BCJ2) * 2008-10-04 : Igor Pavlov : Public domain * */ #define SZ_ERROR_DATA ARCHIVE_FAILED #define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80) #define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)) #define kNumTopBits 24 #define kTopValue ((uint32_t)1 << kNumTopBits) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 #define RC_READ_BYTE (*buffer++) #define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; } #define RC_INIT2 zip->bcj2_code = 0; zip->bcj2_range = 0xFFFFFFFF; \ { int ii; for (ii = 0; ii < 5; ii++) { RC_TEST; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; }} #define NORMALIZE if (zip->bcj2_range < kTopValue) { RC_TEST; zip->bcj2_range <<= 8; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; } #define IF_BIT_0(p) ttt = *(p); bound = (zip->bcj2_range >> kNumBitModelTotalBits) * ttt; if (zip->bcj2_code < bound) #define UPDATE_0(p) zip->bcj2_range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE; #define UPDATE_1(p) zip->bcj2_range -= bound; zip->bcj2_code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE; static ssize_t Bcj2_Decode(struct _7zip *zip, uint8_t *outBuf, size_t outSize) { size_t inPos = 0, outPos = 0; const uint8_t *buf0, *buf1, *buf2, *buf3; size_t size0, size1, size2, size3; const uint8_t *buffer, *bufferLim; unsigned int i, j; size0 = zip->tmp_stream_bytes_remaining; buf0 = zip->tmp_stream_buff + zip->tmp_stream_bytes_avail - size0; size1 = zip->sub_stream_bytes_remaining[0]; buf1 = zip->sub_stream_buff[0] + zip->sub_stream_size[0] - size1; size2 = zip->sub_stream_bytes_remaining[1]; buf2 = zip->sub_stream_buff[1] + zip->sub_stream_size[1] - size2; size3 = zip->sub_stream_bytes_remaining[2]; buf3 = zip->sub_stream_buff[2] + zip->sub_stream_size[2] - size3; buffer = buf3; bufferLim = buffer + size3; if (zip->bcj_state == 0) { /* * Initialize. */ zip->bcj2_prevByte = 0; for (i = 0; i < sizeof(zip->bcj2_p) / sizeof(zip->bcj2_p[0]); i++) zip->bcj2_p[i] = kBitModelTotal >> 1; RC_INIT2; zip->bcj_state = 1; } /* * Gather the odd bytes of a previous call. */ for (i = 0; zip->odd_bcj_size > 0 && outPos < outSize; i++) { outBuf[outPos++] = zip->odd_bcj[i]; zip->odd_bcj_size--; } if (outSize == 0) { zip->bcj2_outPos += outPos; return (outPos); } for (;;) { uint8_t b; CProb *prob; uint32_t bound; uint32_t ttt; size_t limit = size0 - inPos; if (outSize - outPos < limit) limit = outSize - outPos; if (zip->bcj_state == 1) { while (limit != 0) { uint8_t bb = buf0[inPos]; outBuf[outPos++] = bb; if (IsJ(zip->bcj2_prevByte, bb)) { zip->bcj_state = 2; break; } inPos++; zip->bcj2_prevByte = bb; limit--; } } if (limit == 0 || outPos == outSize) break; zip->bcj_state = 1; b = buf0[inPos++]; if (b == 0xE8) prob = zip->bcj2_p + zip->bcj2_prevByte; else if (b == 0xE9) prob = zip->bcj2_p + 256; else prob = zip->bcj2_p + 257; IF_BIT_0(prob) { UPDATE_0(prob) zip->bcj2_prevByte = b; } else { uint32_t dest; const uint8_t *v; uint8_t out[4]; UPDATE_1(prob) if (b == 0xE8) { v = buf1; if (size1 < 4) return SZ_ERROR_DATA; buf1 += 4; size1 -= 4; } else { v = buf2; if (size2 < 4) return SZ_ERROR_DATA; buf2 += 4; size2 -= 4; } dest = (((uint32_t)v[0] << 24) | ((uint32_t)v[1] << 16) | ((uint32_t)v[2] << 8) | ((uint32_t)v[3])) - ((uint32_t)zip->bcj2_outPos + (uint32_t)outPos + 4); out[0] = (uint8_t)dest; out[1] = (uint8_t)(dest >> 8); out[2] = (uint8_t)(dest >> 16); out[3] = zip->bcj2_prevByte = (uint8_t)(dest >> 24); for (i = 0; i < 4 && outPos < outSize; i++) outBuf[outPos++] = out[i]; if (i < 4) { /* * Save odd bytes which we could not add into * the output buffer because of out of space. */ zip->odd_bcj_size = 4 -i; for (; i < 4; i++) { j = i - 4 + (unsigned)zip->odd_bcj_size; zip->odd_bcj[j] = out[i]; } break; } } } zip->tmp_stream_bytes_remaining -= inPos; zip->sub_stream_bytes_remaining[0] = size1; zip->sub_stream_bytes_remaining[1] = size2; zip->sub_stream_bytes_remaining[2] = bufferLim - buffer; zip->bcj2_outPos += outPos; return ((ssize_t)outPos); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_706_0
crossvul-cpp_data_good_2714_0
/* * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more * complete PPP support. */ /* \summary: Point to Point Protocol (PPP) printer */ /* * TODO: * o resolve XXX as much as possible * o MP support * o BAP support */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #ifdef __bsdi__ #include <net/slcompress.h> #include <net/if_ppp.h> #endif #include <stdlib.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ppp.h" #include "chdlc.h" #include "ethertype.h" #include "oui.h" /* * The following constatns are defined by IANA. Please refer to * http://www.isi.edu/in-notes/iana/assignments/ppp-numbers * for the up-to-date information. */ /* Protocol Codes defined in ppp.h */ static const struct tok ppptype2str[] = { { PPP_IP, "IP" }, { PPP_OSI, "OSI" }, { PPP_NS, "NS" }, { PPP_DECNET, "DECNET" }, { PPP_APPLE, "APPLE" }, { PPP_IPX, "IPX" }, { PPP_VJC, "VJC IP" }, { PPP_VJNC, "VJNC IP" }, { PPP_BRPDU, "BRPDU" }, { PPP_STII, "STII" }, { PPP_VINES, "VINES" }, { PPP_MPLS_UCAST, "MPLS" }, { PPP_MPLS_MCAST, "MPLS" }, { PPP_COMP, "Compressed"}, { PPP_ML, "MLPPP"}, { PPP_IPV6, "IP6"}, { PPP_HELLO, "HELLO" }, { PPP_LUXCOM, "LUXCOM" }, { PPP_SNS, "SNS" }, { PPP_IPCP, "IPCP" }, { PPP_OSICP, "OSICP" }, { PPP_NSCP, "NSCP" }, { PPP_DECNETCP, "DECNETCP" }, { PPP_APPLECP, "APPLECP" }, { PPP_IPXCP, "IPXCP" }, { PPP_STIICP, "STIICP" }, { PPP_VINESCP, "VINESCP" }, { PPP_IPV6CP, "IP6CP" }, { PPP_MPLSCP, "MPLSCP" }, { PPP_LCP, "LCP" }, { PPP_PAP, "PAP" }, { PPP_LQM, "LQM" }, { PPP_CHAP, "CHAP" }, { PPP_EAP, "EAP" }, { PPP_SPAP, "SPAP" }, { PPP_SPAP_OLD, "Old-SPAP" }, { PPP_BACP, "BACP" }, { PPP_BAP, "BAP" }, { PPP_MPCP, "MLPPP-CP" }, { PPP_CCP, "CCP" }, { 0, NULL } }; /* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */ #define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */ #define CPCODES_CONF_REQ 1 /* Configure-Request */ #define CPCODES_CONF_ACK 2 /* Configure-Ack */ #define CPCODES_CONF_NAK 3 /* Configure-Nak */ #define CPCODES_CONF_REJ 4 /* Configure-Reject */ #define CPCODES_TERM_REQ 5 /* Terminate-Request */ #define CPCODES_TERM_ACK 6 /* Terminate-Ack */ #define CPCODES_CODE_REJ 7 /* Code-Reject */ #define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */ #define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */ #define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */ #define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */ #define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */ #define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */ #define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */ #define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */ static const struct tok cpcodes[] = { {CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */ {CPCODES_CONF_REQ, "Conf-Request"}, {CPCODES_CONF_ACK, "Conf-Ack"}, {CPCODES_CONF_NAK, "Conf-Nack"}, {CPCODES_CONF_REJ, "Conf-Reject"}, {CPCODES_TERM_REQ, "Term-Request"}, {CPCODES_TERM_ACK, "Term-Ack"}, {CPCODES_CODE_REJ, "Code-Reject"}, {CPCODES_PROT_REJ, "Prot-Reject"}, {CPCODES_ECHO_REQ, "Echo-Request"}, {CPCODES_ECHO_RPL, "Echo-Reply"}, {CPCODES_DISC_REQ, "Disc-Req"}, {CPCODES_ID, "Ident"}, /* RFC1570 */ {CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */ {CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */ {CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */ {0, NULL} }; /* LCP Config Options */ #define LCPOPT_VEXT 0 #define LCPOPT_MRU 1 #define LCPOPT_ACCM 2 #define LCPOPT_AP 3 #define LCPOPT_QP 4 #define LCPOPT_MN 5 #define LCPOPT_DEP6 6 #define LCPOPT_PFC 7 #define LCPOPT_ACFC 8 #define LCPOPT_FCSALT 9 #define LCPOPT_SDP 10 #define LCPOPT_NUMMODE 11 #define LCPOPT_DEP12 12 #define LCPOPT_CBACK 13 #define LCPOPT_DEP14 14 #define LCPOPT_DEP15 15 #define LCPOPT_DEP16 16 #define LCPOPT_MLMRRU 17 #define LCPOPT_MLSSNHF 18 #define LCPOPT_MLED 19 #define LCPOPT_PROP 20 #define LCPOPT_DCEID 21 #define LCPOPT_MPP 22 #define LCPOPT_LD 23 #define LCPOPT_LCPAOPT 24 #define LCPOPT_COBS 25 #define LCPOPT_PE 26 #define LCPOPT_MLHF 27 #define LCPOPT_I18N 28 #define LCPOPT_SDLOS 29 #define LCPOPT_PPPMUX 30 #define LCPOPT_MIN LCPOPT_VEXT #define LCPOPT_MAX LCPOPT_PPPMUX static const char *lcpconfopts[] = { "Vend-Ext", /* (0) */ "MRU", /* (1) */ "ACCM", /* (2) */ "Auth-Prot", /* (3) */ "Qual-Prot", /* (4) */ "Magic-Num", /* (5) */ "deprecated(6)", /* used to be a Quality Protocol */ "PFC", /* (7) */ "ACFC", /* (8) */ "FCS-Alt", /* (9) */ "SDP", /* (10) */ "Num-Mode", /* (11) */ "deprecated(12)", /* used to be a Multi-Link-Procedure*/ "Call-Back", /* (13) */ "deprecated(14)", /* used to be a Connect-Time */ "deprecated(15)", /* used to be a Compund-Frames */ "deprecated(16)", /* used to be a Nominal-Data-Encap */ "MRRU", /* (17) */ "12-Bit seq #", /* (18) */ "End-Disc", /* (19) */ "Proprietary", /* (20) */ "DCE-Id", /* (21) */ "MP+", /* (22) */ "Link-Disc", /* (23) */ "LCP-Auth-Opt", /* (24) */ "COBS", /* (25) */ "Prefix-elision", /* (26) */ "Multilink-header-Form",/* (27) */ "I18N", /* (28) */ "SDL-over-SONET/SDH", /* (29) */ "PPP-Muxing", /* (30) */ }; /* ECP - to be supported */ /* CCP Config Options */ #define CCPOPT_OUI 0 /* RFC1962 */ #define CCPOPT_PRED1 1 /* RFC1962 */ #define CCPOPT_PRED2 2 /* RFC1962 */ #define CCPOPT_PJUMP 3 /* RFC1962 */ /* 4-15 unassigned */ #define CCPOPT_HPPPC 16 /* RFC1962 */ #define CCPOPT_STACLZS 17 /* RFC1974 */ #define CCPOPT_MPPC 18 /* RFC2118 */ #define CCPOPT_GFZA 19 /* RFC1962 */ #define CCPOPT_V42BIS 20 /* RFC1962 */ #define CCPOPT_BSDCOMP 21 /* RFC1977 */ /* 22 unassigned */ #define CCPOPT_LZSDCP 23 /* RFC1967 */ #define CCPOPT_MVRCA 24 /* RFC1975 */ #define CCPOPT_DEC 25 /* RFC1976 */ #define CCPOPT_DEFLATE 26 /* RFC1979 */ /* 27-254 unassigned */ #define CCPOPT_RESV 255 /* RFC1962 */ static const struct tok ccpconfopts_values[] = { { CCPOPT_OUI, "OUI" }, { CCPOPT_PRED1, "Pred-1" }, { CCPOPT_PRED2, "Pred-2" }, { CCPOPT_PJUMP, "Puddle" }, { CCPOPT_HPPPC, "HP-PPC" }, { CCPOPT_STACLZS, "Stac-LZS" }, { CCPOPT_MPPC, "MPPC" }, { CCPOPT_GFZA, "Gand-FZA" }, { CCPOPT_V42BIS, "V.42bis" }, { CCPOPT_BSDCOMP, "BSD-Comp" }, { CCPOPT_LZSDCP, "LZS-DCP" }, { CCPOPT_MVRCA, "MVRCA" }, { CCPOPT_DEC, "DEC" }, { CCPOPT_DEFLATE, "Deflate" }, { CCPOPT_RESV, "Reserved"}, {0, NULL} }; /* BACP Config Options */ #define BACPOPT_FPEER 1 /* RFC2125 */ static const struct tok bacconfopts_values[] = { { BACPOPT_FPEER, "Favored-Peer" }, {0, NULL} }; /* SDCP - to be supported */ /* IPCP Config Options */ #define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */ #define IPCPOPT_IPCOMP 2 /* RFC1332 */ #define IPCPOPT_ADDR 3 /* RFC1332 */ #define IPCPOPT_MOBILE4 4 /* RFC2290 */ #define IPCPOPT_PRIDNS 129 /* RFC1877 */ #define IPCPOPT_PRINBNS 130 /* RFC1877 */ #define IPCPOPT_SECDNS 131 /* RFC1877 */ #define IPCPOPT_SECNBNS 132 /* RFC1877 */ static const struct tok ipcpopt_values[] = { { IPCPOPT_2ADDR, "IP-Addrs" }, { IPCPOPT_IPCOMP, "IP-Comp" }, { IPCPOPT_ADDR, "IP-Addr" }, { IPCPOPT_MOBILE4, "Home-Addr" }, { IPCPOPT_PRIDNS, "Pri-DNS" }, { IPCPOPT_PRINBNS, "Pri-NBNS" }, { IPCPOPT_SECDNS, "Sec-DNS" }, { IPCPOPT_SECNBNS, "Sec-NBNS" }, { 0, NULL } }; #define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */ #define IPCPOPT_IPCOMP_MINLEN 14 static const struct tok ipcpopt_compproto_values[] = { { PPP_VJC, "VJ-Comp" }, { IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" }, { 0, NULL } }; static const struct tok ipcpopt_compproto_subopt_values[] = { { 1, "RTP-Compression" }, { 2, "Enhanced RTP-Compression" }, { 0, NULL } }; /* IP6CP Config Options */ #define IP6CP_IFID 1 static const struct tok ip6cpopt_values[] = { { IP6CP_IFID, "Interface-ID" }, { 0, NULL } }; /* ATCP - to be supported */ /* OSINLCP - to be supported */ /* BVCP - to be supported */ /* BCP - to be supported */ /* IPXCP - to be supported */ /* MPLSCP - to be supported */ /* Auth Algorithms */ /* 0-4 Reserved (RFC1994) */ #define AUTHALG_CHAPMD5 5 /* RFC1994 */ #define AUTHALG_MSCHAP1 128 /* RFC2433 */ #define AUTHALG_MSCHAP2 129 /* RFC2795 */ static const struct tok authalg_values[] = { { AUTHALG_CHAPMD5, "MD5" }, { AUTHALG_MSCHAP1, "MS-CHAPv1" }, { AUTHALG_MSCHAP2, "MS-CHAPv2" }, { 0, NULL } }; /* FCS Alternatives - to be supported */ /* Multilink Endpoint Discriminator (RFC1717) */ #define MEDCLASS_NULL 0 /* Null Class */ #define MEDCLASS_LOCAL 1 /* Locally Assigned */ #define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */ #define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */ #define MEDCLASS_MNB 4 /* PPP Magic Number Block */ #define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */ /* PPP LCP Callback */ #define CALLBACK_AUTH 0 /* Location determined by user auth */ #define CALLBACK_DSTR 1 /* Dialing string */ #define CALLBACK_LID 2 /* Location identifier */ #define CALLBACK_E164 3 /* E.164 number */ #define CALLBACK_X500 4 /* X.500 distinguished name */ #define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */ static const struct tok ppp_callback_values[] = { { CALLBACK_AUTH, "UserAuth" }, { CALLBACK_DSTR, "DialString" }, { CALLBACK_LID, "LocalID" }, { CALLBACK_E164, "E.164" }, { CALLBACK_X500, "X.500" }, { CALLBACK_CBCP, "CBCP" }, { 0, NULL } }; /* CHAP */ #define CHAP_CHAL 1 #define CHAP_RESP 2 #define CHAP_SUCC 3 #define CHAP_FAIL 4 static const struct tok chapcode_values[] = { { CHAP_CHAL, "Challenge" }, { CHAP_RESP, "Response" }, { CHAP_SUCC, "Success" }, { CHAP_FAIL, "Fail" }, { 0, NULL} }; /* PAP */ #define PAP_AREQ 1 #define PAP_AACK 2 #define PAP_ANAK 3 static const struct tok papcode_values[] = { { PAP_AREQ, "Auth-Req" }, { PAP_AACK, "Auth-ACK" }, { PAP_ANAK, "Auth-NACK" }, { 0, NULL } }; /* BAP */ #define BAP_CALLREQ 1 #define BAP_CALLRES 2 #define BAP_CBREQ 3 #define BAP_CBRES 4 #define BAP_LDQREQ 5 #define BAP_LDQRES 6 #define BAP_CSIND 7 #define BAP_CSRES 8 static int print_lcp_config_options(netdissect_options *, const u_char *p, int); static int print_ipcp_config_options(netdissect_options *, const u_char *p, int); static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int); static int print_ccp_config_options(netdissect_options *, const u_char *p, int); static int print_bacp_config_options(netdissect_options *, const u_char *p, int); static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length); /* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */ static void handle_ctrl_proto(netdissect_options *ndo, u_int proto, const u_char *pptr, int length) { const char *typestr; u_int code, len; int (*pfunc)(netdissect_options *, const u_char *, int); int x, j; const u_char *tptr; tptr=pptr; typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto); ND_PRINT((ndo, "%s, ", typestr)); if (length < 4) /* FIXME weak boundary checking */ goto trunc; ND_TCHECK2(*tptr, 2); code = *tptr++; ND_PRINT((ndo, "%s (0x%02x), id %u, length %u", tok2str(cpcodes, "Unknown Opcode",code), code, *tptr++, /* ID */ length + 2)); if (!ndo->ndo_vflag) return; if (length <= 4) return; /* there may be a NULL confreq etc. */ ND_TCHECK2(*tptr, 2); len = EXTRACT_16BITS(tptr); tptr += 2; ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr - 2, "\n\t", 6); switch (code) { case CPCODES_VEXT: if (length < 11) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); tptr += 4; ND_TCHECK2(*tptr, 3); ND_PRINT((ndo, " Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr))); /* XXX: need to decode Kind and Value(s)? */ break; case CPCODES_CONF_REQ: case CPCODES_CONF_ACK: case CPCODES_CONF_NAK: case CPCODES_CONF_REJ: x = len - 4; /* Code(1), Identifier(1) and Length(2) */ do { switch (proto) { case PPP_LCP: pfunc = print_lcp_config_options; break; case PPP_IPCP: pfunc = print_ipcp_config_options; break; case PPP_IPV6CP: pfunc = print_ip6cp_config_options; break; case PPP_CCP: pfunc = print_ccp_config_options; break; case PPP_BACP: pfunc = print_bacp_config_options; break; default: /* * No print routine for the options for * this protocol. */ pfunc = NULL; break; } if (pfunc == NULL) /* catch the above null pointer if unknown CP */ break; if ((j = (*pfunc)(ndo, tptr, len)) == 0) break; x -= j; tptr += j; } while (x > 0); break; case CPCODES_TERM_REQ: case CPCODES_TERM_ACK: /* XXX: need to decode Data? */ break; case CPCODES_CODE_REJ: /* XXX: need to decode Rejected-Packet? */ break; case CPCODES_PROT_REJ: if (length < 6) break; ND_TCHECK2(*tptr, 2); ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)", tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); /* XXX: need to decode Rejected-Information? - hexdump for now */ if (len > 6) { ND_PRINT((ndo, "\n\t Rejected Packet")); print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2); } break; case CPCODES_ECHO_REQ: case CPCODES_ECHO_RPL: case CPCODES_DISC_REQ: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* XXX: need to decode Data? - hexdump for now */ if (len > 8) { ND_PRINT((ndo, "\n\t -----trailing data-----")); ND_TCHECK2(tptr[4], len - 8); print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8); } break; case CPCODES_ID: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* RFC 1661 says this is intended to be human readable */ if (len > 8) { ND_PRINT((ndo, "\n\t Message\n\t ")); if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend)) goto trunc; } break; case CPCODES_TIME_REM: if (length < 12) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4))); /* XXX: need to decode Message? */ break; default: /* XXX this is dirty but we do not get the * original pointer passed to the begin * the PPP packet */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2); break; } return; trunc: ND_PRINT((ndo, "[|%s]", typestr)); } /* LCP config options */ static int print_lcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", lcpconfopts[opt], opt, len)); else ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return 0; } if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len)); else { ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return len; } switch (opt) { case LCPOPT_VEXT: if (len < 6) { ND_PRINT((ndo, " (length bogus, should be >= 6)")); return len; } ND_TCHECK_24BITS(p + 2); ND_PRINT((ndo, ": Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)), EXTRACT_24BITS(p + 2))); #if 0 ND_TCHECK(p[5]); ND_PRINT((ndo, ", kind: 0x%02x", p[5])); ND_PRINT((ndo, ", Value: 0x")); for (i = 0; i < len - 6; i++) { ND_TCHECK(p[6 + i]); ND_PRINT((ndo, "%02x", p[6 + i])); } #endif break; case LCPOPT_MRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_ACCM: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_AP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2)))); switch (EXTRACT_16BITS(p+2)) { case PPP_CHAP: ND_TCHECK(p[4]); ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4]))); break; case PPP_PAP: /* fall through */ case PPP_EAP: case PPP_SPAP: case PPP_SPAP_OLD: break; default: print_unknown_data(ndo, p, "\n\t", len); } break; case LCPOPT_QP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK_16BITS(p+2); if (EXTRACT_16BITS(p+2) == PPP_LQM) ND_PRINT((ndo, ": LQR")); else ND_PRINT((ndo, ": unknown")); break; case LCPOPT_MN: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_PFC: break; case LCPOPT_ACFC: break; case LCPOPT_LD: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2))); break; case LCPOPT_CBACK: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_PRINT((ndo, ": ")); ND_TCHECK(p[2]); ND_PRINT((ndo, ": Callback Operation %s (%u)", tok2str(ppp_callback_values, "Unknown", p[2]), p[2])); break; case LCPOPT_MLMRRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_MLED: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_TCHECK(p[2]); switch (p[2]) { /* class */ case MEDCLASS_NULL: ND_PRINT((ndo, ": Null")); break; case MEDCLASS_LOCAL: ND_PRINT((ndo, ": Local")); /* XXX */ break; case MEDCLASS_IPV4: if (len != 7) { ND_PRINT((ndo, " (length bogus, should be = 7)")); return 0; } ND_TCHECK2(*(p + 3), 4); ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3))); break; case MEDCLASS_MAC: if (len != 9) { ND_PRINT((ndo, " (length bogus, should be = 9)")); return 0; } ND_TCHECK2(*(p + 3), 6); ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3))); break; case MEDCLASS_MNB: ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */ break; case MEDCLASS_PSNDN: ND_PRINT((ndo, ": PSNDN")); /* XXX */ break; default: ND_PRINT((ndo, ": Unknown class %u", p[2])); break; } break; /* XXX: to be supported */ #if 0 case LCPOPT_DEP6: case LCPOPT_FCSALT: case LCPOPT_SDP: case LCPOPT_NUMMODE: case LCPOPT_DEP12: case LCPOPT_DEP14: case LCPOPT_DEP15: case LCPOPT_DEP16: case LCPOPT_MLSSNHF: case LCPOPT_PROP: case LCPOPT_DCEID: case LCPOPT_MPP: case LCPOPT_LCPAOPT: case LCPOPT_COBS: case LCPOPT_PE: case LCPOPT_MLHF: case LCPOPT_I18N: case LCPOPT_SDLOS: case LCPOPT_PPPMUX: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|lcp]")); return 0; } /* ML-PPP*/ static const struct tok ppp_ml_flag_values[] = { { 0x80, "begin" }, { 0x40, "end" }, { 0, NULL } }; static void handle_mlppp(netdissect_options *ndo, const u_char *p, int length) { if (!ndo->ndo_eflag) ND_PRINT((ndo, "MLPPP, ")); if (length < 2) { ND_PRINT((ndo, "[|mlppp]")); return; } if (!ND_TTEST_16BITS(p)) { ND_PRINT((ndo, "[|mlppp]")); return; } ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u", (EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */ bittok2str(ppp_ml_flag_values, "none", *p & 0xc0), length)); } /* CHAP */ static void handle_chap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int val_size, name_size, msg_size; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|chap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|chap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "CHAP, %s (0x%02x)", tok2str(chapcode_values,"unknown",code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; /* * Note that this is a generic CHAP decoding routine. Since we * don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1, * MS-CHAPv2) is used at this point, we can't decode packet * specifically to each algorithms. Instead, we simply decode * the GCD (Gratest Common Denominator) for all algorithms. */ switch (code) { case CHAP_CHAL: case CHAP_RESP: if (length - (p - p0) < 1) return; ND_TCHECK(*p); val_size = *p; /* value size */ p++; if (length - (p - p0) < val_size) return; ND_PRINT((ndo, ", Value ")); for (i = 0; i < val_size; i++) { ND_TCHECK(*p); ND_PRINT((ndo, "%02x", *p++)); } name_size = len - (p - p0); ND_PRINT((ndo, ", Name ")); for (i = 0; i < name_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case CHAP_SUCC: case CHAP_FAIL: msg_size = len - (p - p0); ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|chap]")); } /* PAP (see RFC 1334) */ static void handle_pap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int peerid_len, passwd_len, msg_len; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|pap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|pap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "PAP, %s (0x%02x)", tok2str(papcode_values, "unknown", code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; if ((int)len > length) { ND_PRINT((ndo, ", length %u > packet size", len)); return; } length = len; if (length < (p - p0)) { ND_PRINT((ndo, ", length %u < PAP header length", length)); return; } switch (code) { case PAP_AREQ: /* A valid Authenticate-Request is 6 or more octets long. */ if (len < 6) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); peerid_len = *p; /* Peer-ID Length */ p++; if (length - (p - p0) < peerid_len) return; ND_PRINT((ndo, ", Peer ")); for (i = 0; i < peerid_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } if (length - (p - p0) < 1) return; ND_TCHECK(*p); passwd_len = *p; /* Password Length */ p++; if (length - (p - p0) < passwd_len) return; ND_PRINT((ndo, ", Name ")); for (i = 0; i < passwd_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case PAP_AACK: case PAP_ANAK: /* Although some implementations ignore truncation at * this point and at least one generates a truncated * packet, RFC 1334 section 2.2.2 clearly states that * both AACK and ANAK are at least 5 bytes long. */ if (len < 5) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); msg_len = *p; /* Msg-Length */ p++; if (length - (p - p0) < msg_len) return; ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|pap]")); } /* BAP */ static void handle_bap(netdissect_options *ndo _U_, const u_char *p _U_, int length _U_) { /* XXX: to be supported!! */ } /* IPCP config options */ static int print_ipcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ipcpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ipcpopt_values,"unknown",opt), opt, len)); switch (opt) { case IPCPOPT_2ADDR: /* deprecated */ if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 6), 4); ND_PRINT((ndo, ": src %s, dst %s", ipaddr_string(ndo, p + 2), ipaddr_string(ndo, p + 6))); break; case IPCPOPT_IPCOMP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK_16BITS(p+2); compproto = EXTRACT_16BITS(p+2); ND_PRINT((ndo, ": %s (0x%02x):", tok2str(ipcpopt_compproto_values, "Unknown", compproto), compproto)); switch (compproto) { case PPP_VJC: /* XXX: VJ-Comp parameters should be decoded */ break; case IPCPOPT_IPCOMP_HDRCOMP: if (len < IPCPOPT_IPCOMP_MINLEN) { ND_PRINT((ndo, " (length bogus, should be >= %u)", IPCPOPT_IPCOMP_MINLEN)); return 0; } ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN); ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \ ", maxPeriod %u, maxTime %u, maxHdr %u", EXTRACT_16BITS(p+4), EXTRACT_16BITS(p+6), EXTRACT_16BITS(p+8), EXTRACT_16BITS(p+10), EXTRACT_16BITS(p+12))); /* suboptions present ? */ if (len > IPCPOPT_IPCOMP_MINLEN) { ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN; p += IPCPOPT_IPCOMP_MINLEN; ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen)); while (ipcomp_subopttotallen >= 2) { ND_TCHECK2(*p, 2); ipcomp_subopt = *p; ipcomp_suboptlen = *(p+1); /* sanity check */ if (ipcomp_subopt == 0 || ipcomp_suboptlen == 0 ) break; /* XXX: just display the suboptions for now */ ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u", tok2str(ipcpopt_compproto_subopt_values, "Unknown", ipcomp_subopt), ipcomp_subopt, ipcomp_suboptlen)); ipcomp_subopttotallen -= ipcomp_suboptlen; p += ipcomp_suboptlen; } } break; default: break; } break; case IPCPOPT_ADDR: /* those options share the same format - fall through */ case IPCPOPT_MOBILE4: case IPCPOPT_PRIDNS: case IPCPOPT_PRINBNS: case IPCPOPT_SECDNS: case IPCPOPT_SECNBNS: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ipcp]")); return 0; } /* IP6CP config options */ static int print_ip6cp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); switch (opt) { case IP6CP_IFID: if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 2), 8); ND_PRINT((ndo, ": %04x:%04x:%04x:%04x", EXTRACT_16BITS(p + 2), EXTRACT_16BITS(p + 4), EXTRACT_16BITS(p + 6), EXTRACT_16BITS(p + 8))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ip6cp]")); return 0; } /* CCP config options */ static int print_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK(p[2]); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; } /* BACP config options */ static int print_bacp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case BACPOPT_FPEER: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|bacp]")); return 0; } static void ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *t, c; const u_char *s; int i, proto; const void *se; if (length <= 0) return; b = (u_char *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { c = *s++; if (c == 0x7d) { if (i <= 1 || !ND_TTEST(*s)) break; i--; c = *s++ ^ 0x20; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); } /* PPP */ static void handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } /* Standard PPP printer */ u_int ppp_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto,ppp_header; u_int olen = length; /* _o_riginal length */ u_int hdr_len = 0; /* * Here, we assume that p points to the Address and Control * field (if they present). */ if (length < 2) goto trunc; ND_TCHECK2(*p, 2); ppp_header = EXTRACT_16BITS(p); switch(ppp_header) { case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "In ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "Out ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_ADDRESS << 8 | PPP_CONTROL): p += 2; /* ACFC not used */ length -= 2; hdr_len += 2; break; default: break; } if (length < 2) goto trunc; ND_TCHECK(*p); if (*p % 2) { proto = *p; /* PFC is used */ p++; length--; hdr_len++; } else { ND_TCHECK2(*p, 2); proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdr_len += 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%s (0x%04x), length %u: ", tok2str(ppptype2str, "unknown", proto), proto, olen)); handle_ppp(ndo, proto, p, length); return (hdr_len); trunc: ND_PRINT((ndo, "[|ppp]")); return (0); } /* PPP I/F printer */ u_int ppp_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < PPP_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } #if 0 /* * XXX: seems to assume that there are 2 octets prepended to an * actual PPP frame. The 1st octet looks like Input/Output flag * while 2nd octet is unknown, at least to me * (mshindo@mshindo.net). * * That was what the original tcpdump code did. * * FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound * packets and 0 for inbound packets - but only if the * protocol field has the 0x8000 bit set (i.e., it's a network * control protocol); it does so before running the packet through * "bpf_filter" to see if it should be discarded, and to see * if we should update the time we sent the most recent packet... * * ...but it puts the original address field back after doing * so. * * NetBSD's "if_ppp.c" doesn't set the first octet in that fashion. * * I don't know if any PPP implementation handed up to a BPF * device packets with the first octet being 1 for outbound and * 0 for inbound packets, so I (guy@alum.mit.edu) don't know * whether that ever needs to be checked or not. * * Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP, * and its tcpdump appears to assume that the frame always * begins with an address field and a control field, and that * the address field might be 0x0f or 0x8f, for Cisco * point-to-point with HDLC framing as per section 4.3.1 of RFC * 1547, as well as 0xff, for PPP in HDLC-like framing as per * RFC 1662. * * (Is the Cisco framing in question what DLT_C_HDLC, in * BSD/OS, is?) */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1])); #endif ppp_print(ndo, p, length); return (0); } /* * PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like * framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547, * is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL, * discard them *if* those are the first two octets, and parse the remaining * packet as a PPP packet, as "ppp_print()" does). * * This handles, for example, DLT_PPP_SERIAL in NetBSD. */ u_int ppp_hdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; u_int proto; u_int hdrlen = 0; if (caplen < 2) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } switch (p[0]) { case PPP_ADDRESS: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; length -= 2; hdrlen += 2; proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdrlen += 2; ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); handle_ppp(ndo, proto, p, length); break; case CHDLC_UNICAST: case CHDLC_BCAST: return (chdlc_if_print(ndo, h, p)); default: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; hdrlen += 2; /* * XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats * the next two octets as an Ethernet type; does that * ever happen? */ ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1])); break; } return (hdrlen); } #define PPP_BSDI_HDRLEN 24 /* BSD/OS specific PPP printer */ u_int ppp_bsdos_if_print(netdissect_options *ndo _U_, const struct pcap_pkthdr *h _U_, register const u_char *p _U_) { register int hdrlength; #ifdef __bsdi__ register u_int length = h->len; register u_int caplen = h->caplen; uint16_t ptype; const u_char *q; int i; if (caplen < PPP_BSDI_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen) } hdrlength = 0; #if 0 if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", p[0], p[1])); p += 2; hdrlength = 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); /* Retrieve the protocol type */ if (*p & 01) { /* Compressed protocol field */ ptype = *p; if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x ", ptype)); p++; hdrlength += 1; } else { /* Un-compressed protocol field */ ptype = EXTRACT_16BITS(p); if (ndo->ndo_eflag) ND_PRINT((ndo, "%04x ", ptype)); p += 2; hdrlength += 2; } #else ptype = 0; /*XXX*/ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I')); if (p[SLC_LLHL]) { /* link level header */ struct ppp_header *ph; q = p + SLC_BPFHDRLEN; ph = (struct ppp_header *)q; if (ph->phdr_addr == PPP_ADDRESS && ph->phdr_ctl == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", q[0], q[1])); ptype = EXTRACT_16BITS(&ph->phdr_type); if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) { ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "proto-#%d", ptype))); } } else { if (ndo->ndo_eflag) { ND_PRINT((ndo, "LLH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } } } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); if (p[SLC_CHL]) { q = p + SLC_BPFHDRLEN + p[SLC_LLHL]; switch (ptype) { case PPP_VJC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; case PPP_VJNC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; default: if (ndo->ndo_eflag) { ND_PRINT((ndo, "CH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } break; } } hdrlength = PPP_BSDI_HDRLEN; #endif length -= hdrlength; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype))); } printx: #else /* __bsdi */ hdrlength = 0; #endif /* __bsdi__ */ return (hdrlength); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2714_0
crossvul-cpp_data_good_2690_0
/* * Copyright (c) 2004 - Michael Richardson <mcr@xelerance.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Extensible Authentication Protocol (EAP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #define EAP_FRAME_TYPE_PACKET 0 #define EAP_FRAME_TYPE_START 1 #define EAP_FRAME_TYPE_LOGOFF 2 #define EAP_FRAME_TYPE_KEY 3 #define EAP_FRAME_TYPE_ENCAP_ASF_ALERT 4 struct eap_frame_t { unsigned char version; unsigned char type; unsigned char length[2]; }; static const struct tok eap_frame_type_values[] = { { EAP_FRAME_TYPE_PACKET, "EAP packet" }, { EAP_FRAME_TYPE_START, "EAPOL start" }, { EAP_FRAME_TYPE_LOGOFF, "EAPOL logoff" }, { EAP_FRAME_TYPE_KEY, "EAPOL key" }, { EAP_FRAME_TYPE_ENCAP_ASF_ALERT, "Encapsulated ASF alert" }, { 0, NULL} }; /* RFC 3748 */ struct eap_packet_t { unsigned char code; unsigned char id; unsigned char length[2]; }; #define EAP_REQUEST 1 #define EAP_RESPONSE 2 #define EAP_SUCCESS 3 #define EAP_FAILURE 4 static const struct tok eap_code_values[] = { { EAP_REQUEST, "Request" }, { EAP_RESPONSE, "Response" }, { EAP_SUCCESS, "Success" }, { EAP_FAILURE, "Failure" }, { 0, NULL} }; #define EAP_TYPE_NO_PROPOSED 0 #define EAP_TYPE_IDENTITY 1 #define EAP_TYPE_NOTIFICATION 2 #define EAP_TYPE_NAK 3 #define EAP_TYPE_MD5_CHALLENGE 4 #define EAP_TYPE_OTP 5 #define EAP_TYPE_GTC 6 #define EAP_TYPE_TLS 13 /* RFC 2716 */ #define EAP_TYPE_SIM 18 /* RFC 4186 */ #define EAP_TYPE_TTLS 21 /* draft-funk-eap-ttls-v0-01.txt */ #define EAP_TYPE_AKA 23 /* RFC 4187 */ #define EAP_TYPE_FAST 43 /* RFC 4851 */ #define EAP_TYPE_EXPANDED_TYPES 254 #define EAP_TYPE_EXPERIMENTAL 255 static const struct tok eap_type_values[] = { { EAP_TYPE_NO_PROPOSED, "No proposed" }, { EAP_TYPE_IDENTITY, "Identity" }, { EAP_TYPE_NOTIFICATION, "Notification" }, { EAP_TYPE_NAK, "Nak" }, { EAP_TYPE_MD5_CHALLENGE, "MD5-challenge" }, { EAP_TYPE_OTP, "OTP" }, { EAP_TYPE_GTC, "GTC" }, { EAP_TYPE_TLS, "TLS" }, { EAP_TYPE_SIM, "SIM" }, { EAP_TYPE_TTLS, "TTLS" }, { EAP_TYPE_AKA, "AKA" }, { EAP_TYPE_FAST, "FAST" }, { EAP_TYPE_EXPANDED_TYPES, "Expanded types" }, { EAP_TYPE_EXPERIMENTAL, "Experimental" }, { 0, NULL} }; #define EAP_TLS_EXTRACT_BIT_L(x) (((x)&0x80)>>7) /* RFC 2716 - EAP TLS bits */ #define EAP_TLS_FLAGS_LEN_INCLUDED (1 << 7) #define EAP_TLS_FLAGS_MORE_FRAGMENTS (1 << 6) #define EAP_TLS_FLAGS_START (1 << 5) static const struct tok eap_tls_flags_values[] = { { EAP_TLS_FLAGS_LEN_INCLUDED, "L bit" }, { EAP_TLS_FLAGS_MORE_FRAGMENTS, "More fragments bit"}, { EAP_TLS_FLAGS_START, "Start bit"}, { 0, NULL} }; #define EAP_TTLS_VERSION(x) ((x)&0x07) /* EAP-AKA and EAP-SIM - RFC 4187 */ #define EAP_AKA_CHALLENGE 1 #define EAP_AKA_AUTH_REJECT 2 #define EAP_AKA_SYNC_FAILURE 4 #define EAP_AKA_IDENTITY 5 #define EAP_SIM_START 10 #define EAP_SIM_CHALLENGE 11 #define EAP_AKA_NOTIFICATION 12 #define EAP_AKA_REAUTH 13 #define EAP_AKA_CLIENT_ERROR 14 static const struct tok eap_aka_subtype_values[] = { { EAP_AKA_CHALLENGE, "Challenge" }, { EAP_AKA_AUTH_REJECT, "Auth reject" }, { EAP_AKA_SYNC_FAILURE, "Sync failure" }, { EAP_AKA_IDENTITY, "Identity" }, { EAP_SIM_START, "Start" }, { EAP_SIM_CHALLENGE, "Challenge" }, { EAP_AKA_NOTIFICATION, "Notification" }, { EAP_AKA_REAUTH, "Reauth" }, { EAP_AKA_CLIENT_ERROR, "Client error" }, { 0, NULL} }; /* * Print EAP requests / responses */ void eap_print(netdissect_options *ndo, register const u_char *cp, u_int length) { const struct eap_frame_t *eap; const u_char *tptr; u_int tlen, type, subtype; int count=0, len; tptr = cp; tlen = length; eap = (const struct eap_frame_t *)cp; ND_TCHECK(*eap); /* in non-verbose mode just lets print the basic info */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); return; } ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); tptr += sizeof(const struct eap_frame_t); tlen -= sizeof(const struct eap_frame_t); switch (eap->type) { case EAP_FRAME_TYPE_PACKET: ND_TCHECK_8BITS(tptr); type = *(tptr); ND_TCHECK_16BITS(tptr+2); len = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, ", %s (%u), id %u, len %u", tok2str(eap_code_values, "unknown", type), type, *(tptr+1), len)); ND_TCHECK2(*tptr, len); if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */ ND_TCHECK_8BITS(tptr+4); subtype = *(tptr+4); ND_PRINT((ndo, "\n\t\t Type %s (%u)", tok2str(eap_type_values, "unknown", subtype), subtype)); switch (subtype) { case EAP_TYPE_IDENTITY: if (len - 5 > 0) { ND_PRINT((ndo, ", Identity: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NOTIFICATION: if (len - 5 > 0) { ND_PRINT((ndo, ", Notification: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NAK: count = 5; /* * one or more octets indicating * the desired authentication * type one octet per type */ while (count < len) { ND_TCHECK_8BITS(tptr+count); ND_PRINT((ndo, " %s (%u),", tok2str(eap_type_values, "unknown", *(tptr+count)), *(tptr + count))); count++; } break; case EAP_TYPE_TTLS: case EAP_TYPE_TLS: ND_TCHECK_8BITS(tptr + 5); if (subtype == EAP_TYPE_TTLS) ND_PRINT((ndo, " TTLSv%u", EAP_TTLS_VERSION(*(tptr + 5)))); ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_TCHECK_32BITS(tptr + 6); ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } break; case EAP_TYPE_FAST: ND_TCHECK_8BITS(tptr + 5); ND_PRINT((ndo, " FASTv%u", EAP_TTLS_VERSION(*(tptr + 5)))); ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_TCHECK_32BITS(tptr + 6); ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } /* FIXME - TLV attributes follow */ break; case EAP_TYPE_AKA: case EAP_TYPE_SIM: ND_TCHECK_8BITS(tptr + 5); ND_PRINT((ndo, " subtype [%s] 0x%02x,", tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)), *(tptr + 5))); /* FIXME - TLV attributes follow */ break; case EAP_TYPE_MD5_CHALLENGE: case EAP_TYPE_OTP: case EAP_TYPE_GTC: case EAP_TYPE_EXPANDED_TYPES: case EAP_TYPE_EXPERIMENTAL: default: break; } } break; case EAP_FRAME_TYPE_LOGOFF: case EAP_FRAME_TYPE_ENCAP_ASF_ALERT: default: break; } return; trunc: ND_PRINT((ndo, "\n\t[|EAP]")); } /* * Local Variables: * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2690_0
crossvul-cpp_data_bad_950_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % 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/attribute.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; 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); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red); Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red); gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+ snr); Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green); Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green); gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr); Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue); Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity* Bi->opacity+snr); Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity* Bi->opacity); Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity* Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red); Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green); Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5; Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity); Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red); Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red); Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green); Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green); Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue); Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity* Bi->opacity); Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity* Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize Fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image,RedChannel, modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse Fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source_pixels; const char *value; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_950_1
crossvul-cpp_data_bad_5362_0
/*- * Copyright (c) 2011 Michihiro NAKAJIMA * 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 AUTHOR(S) ``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 AUTHOR(S) 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 "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_BZLIB_H #include <bzlib.h> #endif #ifdef HAVE_LZMA_H #include <lzma.h> #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #include "archive.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" #include "archive_endian.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #define _7ZIP_SIGNATURE "7z\xBC\xAF\x27\x1C" #define SFX_MIN_ADDR 0x27000 #define SFX_MAX_ADDR 0x60000 /* * Codec ID */ #define _7Z_COPY 0 #define _7Z_LZMA 0x030101 #define _7Z_LZMA2 0x21 #define _7Z_DEFLATE 0x040108 #define _7Z_BZ2 0x040202 #define _7Z_PPMD 0x030401 #define _7Z_DELTA 0x03 #define _7Z_CRYPTO_MAIN_ZIP 0x06F10101 /* Main Zip crypto algo */ #define _7Z_CRYPTO_RAR_29 0x06F10303 /* Rar29 AES-128 + (modified SHA-1) */ #define _7Z_CRYPTO_AES_256_SHA_256 0x06F10701 /* AES-256 + SHA-256 */ #define _7Z_X86 0x03030103 #define _7Z_X86_BCJ2 0x0303011B #define _7Z_POWERPC 0x03030205 #define _7Z_IA64 0x03030401 #define _7Z_ARM 0x03030501 #define _7Z_ARMTHUMB 0x03030701 #define _7Z_SPARC 0x03030805 /* * 7-Zip header property IDs. */ #define kEnd 0x00 #define kHeader 0x01 #define kArchiveProperties 0x02 #define kAdditionalStreamsInfo 0x03 #define kMainStreamsInfo 0x04 #define kFilesInfo 0x05 #define kPackInfo 0x06 #define kUnPackInfo 0x07 #define kSubStreamsInfo 0x08 #define kSize 0x09 #define kCRC 0x0A #define kFolder 0x0B #define kCodersUnPackSize 0x0C #define kNumUnPackStream 0x0D #define kEmptyStream 0x0E #define kEmptyFile 0x0F #define kAnti 0x10 #define kName 0x11 #define kCTime 0x12 #define kATime 0x13 #define kMTime 0x14 #define kAttributes 0x15 #define kEncodedHeader 0x17 #define kDummy 0x19 struct _7z_digests { unsigned char *defineds; uint32_t *digests; }; struct _7z_folder { uint64_t numCoders; struct _7z_coder { unsigned long codec; uint64_t numInStreams; uint64_t numOutStreams; uint64_t propertiesSize; unsigned char *properties; } *coders; uint64_t numBindPairs; struct { uint64_t inIndex; uint64_t outIndex; } *bindPairs; uint64_t numPackedStreams; uint64_t *packedStreams; uint64_t numInStreams; uint64_t numOutStreams; uint64_t *unPackSize; unsigned char digest_defined; uint32_t digest; uint64_t numUnpackStreams; uint32_t packIndex; /* Unoperated bytes. */ uint64_t skipped_bytes; }; struct _7z_coders_info { uint64_t numFolders; struct _7z_folder *folders; uint64_t dataStreamIndex; }; struct _7z_pack_info { uint64_t pos; uint64_t numPackStreams; uint64_t *sizes; struct _7z_digests digest; /* Calculated from pos and numPackStreams. */ uint64_t *positions; }; struct _7z_substream_info { size_t unpack_streams; uint64_t *unpackSizes; unsigned char *digestsDefined; uint32_t *digests; }; struct _7z_stream_info { struct _7z_pack_info pi; struct _7z_coders_info ci; struct _7z_substream_info ss; }; struct _7z_header_info { uint64_t dataIndex; unsigned char *emptyStreamBools; unsigned char *emptyFileBools; unsigned char *antiBools; unsigned char *attrBools; }; struct _7zip_entry { size_t name_len; unsigned char *utf16name; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) const wchar_t *wname; #endif uint32_t folderIndex; uint32_t ssIndex; unsigned flg; #define MTIME_IS_SET (1<<0) #define ATIME_IS_SET (1<<1) #define CTIME_IS_SET (1<<2) #define CRC32_IS_SET (1<<3) #define HAS_STREAM (1<<4) time_t mtime; time_t atime; time_t ctime; long mtime_ns; long atime_ns; long ctime_ns; uint32_t mode; uint32_t attr; }; struct _7zip { /* Structural information about the archive. */ struct _7z_stream_info si; int header_is_being_read; int header_is_encoded; uint64_t header_bytes_remaining; unsigned long header_crc32; /* Header offset to check that reading pointes of the file contens * will not exceed the header. */ uint64_t header_offset; /* Base offset of the archive file for a seek in case reading SFX. */ uint64_t seek_base; /* List of entries */ size_t entries_remaining; uint64_t numFiles; struct _7zip_entry *entries; struct _7zip_entry *entry; unsigned char *entry_names; /* entry_bytes_remaining is the number of bytes we expect. */ int64_t entry_offset; uint64_t entry_bytes_remaining; /* Running CRC32 of the decompressed data */ unsigned long entry_crc32; /* Flags to mark progress of decompression. */ char end_of_entry; /* Uncompressed buffer control. */ #define UBUFF_SIZE (64 * 1024) unsigned char *uncompressed_buffer; unsigned char *uncompressed_buffer_pointer; size_t uncompressed_buffer_size; size_t uncompressed_buffer_bytes_remaining; /* Offset of the compressed data. */ int64_t stream_offset; /* * Decompressing control data. */ unsigned folder_index; uint64_t folder_outbytes_remaining; unsigned pack_stream_index; unsigned pack_stream_remaining; uint64_t pack_stream_inbytes_remaining; size_t pack_stream_bytes_unconsumed; /* The codec information of a folder. */ unsigned long codec; unsigned long codec2; /* * Decompressor controllers. */ /* Decording LZMA1 and LZMA2 data. */ #ifdef HAVE_LZMA_H lzma_stream lzstream; int lzstream_valid; #endif /* Decording bzip2 data. */ #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) bz_stream bzstream; int bzstream_valid; #endif /* Decording deflate data. */ #ifdef HAVE_ZLIB_H z_stream stream; int stream_valid; #endif /* Decording PPMd data. */ int ppmd7_stat; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; struct { const unsigned char *next_in; int64_t avail_in; int64_t total_in; unsigned char *next_out; int64_t avail_out; int64_t total_out; int overconsumed; } ppstream; int ppmd7_valid; /* Decoding BCJ and BCJ2 data. */ uint32_t bcj_state; size_t odd_bcj_size; unsigned char odd_bcj[4]; /* Decoding BCJ data. */ size_t bcj_prevPosT; uint32_t bcj_prevMask; uint32_t bcj_ip; /* Decoding BCJ2 data. */ size_t main_stream_bytes_remaining; unsigned char *sub_stream_buff[3]; size_t sub_stream_size[3]; size_t sub_stream_bytes_remaining[3]; unsigned char *tmp_stream_buff; size_t tmp_stream_buff_size; size_t tmp_stream_bytes_avail; size_t tmp_stream_bytes_remaining; #ifdef _LZMA_PROB32 #define CProb uint32_t #else #define CProb uint16_t #endif CProb bcj2_p[256 + 2]; uint8_t bcj2_prevByte; uint32_t bcj2_range; uint32_t bcj2_code; uint64_t bcj2_outPos; /* Filename character-set conversion data. */ struct archive_string_conv *sconv; char format_name[64]; /* Custom value that is non-zero if this archive contains encrypted entries. */ int has_encrypted_entries; }; /* Maximum entry size. This limitation prevents reading intentional * corrupted 7-zip files on assuming there are not so many entries in * the files. */ #define UMAX_ENTRY ARCHIVE_LITERAL_ULL(100000000) static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *); static int archive_read_support_format_7zip_capabilities(struct archive_read *a); static int archive_read_format_7zip_bid(struct archive_read *, int); static int archive_read_format_7zip_cleanup(struct archive_read *); static int archive_read_format_7zip_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_7zip_read_data_skip(struct archive_read *); static int archive_read_format_7zip_read_header(struct archive_read *, struct archive_entry *); static int check_7zip_header_in_sfx(const char *); static unsigned long decode_codec_id(const unsigned char *, size_t); static int decode_encoded_header_info(struct archive_read *, struct _7z_stream_info *); static int decompress(struct archive_read *, struct _7zip *, void *, size_t *, const void *, size_t *); static ssize_t extract_pack_stream(struct archive_read *, size_t); static void fileTimeToUtc(uint64_t, time_t *, long *); static uint64_t folder_uncompressed_size(struct _7z_folder *); static void free_CodersInfo(struct _7z_coders_info *); static void free_Digest(struct _7z_digests *); static void free_Folder(struct _7z_folder *); static void free_Header(struct _7z_header_info *); static void free_PackInfo(struct _7z_pack_info *); static void free_StreamsInfo(struct _7z_stream_info *); static void free_SubStreamsInfo(struct _7z_substream_info *); static int free_decompression(struct archive_read *, struct _7zip *); static ssize_t get_uncompressed_data(struct archive_read *, const void **, size_t, size_t); static const unsigned char * header_bytes(struct archive_read *, size_t); static int init_decompression(struct archive_read *, struct _7zip *, const struct _7z_coder *, const struct _7z_coder *); static int parse_7zip_uint64(struct archive_read *, uint64_t *); static int read_Bools(struct archive_read *, unsigned char *, size_t); static int read_CodersInfo(struct archive_read *, struct _7z_coders_info *); static int read_Digests(struct archive_read *, struct _7z_digests *, size_t); static int read_Folder(struct archive_read *, struct _7z_folder *); static int read_Header(struct archive_read *, struct _7z_header_info *, int); static int read_PackInfo(struct archive_read *, struct _7z_pack_info *); static int read_StreamsInfo(struct archive_read *, struct _7z_stream_info *); static int read_SubStreamsInfo(struct archive_read *, struct _7z_substream_info *, struct _7z_folder *, size_t); static int read_Times(struct archive_read *, struct _7z_header_info *, int); static void read_consume(struct archive_read *); static ssize_t read_stream(struct archive_read *, const void **, size_t, size_t); static int seek_pack(struct archive_read *); static int64_t skip_stream(struct archive_read *, size_t); static int skip_sfx(struct archive_read *, ssize_t); static int slurp_central_directory(struct archive_read *, struct _7zip *, struct _7z_header_info *); static int setup_decode_folder(struct archive_read *, struct _7z_folder *, int); static void x86_Init(struct _7zip *); static size_t x86_Convert(struct _7zip *, uint8_t *, size_t); static ssize_t Bcj2_Decode(struct _7zip *, uint8_t *, size_t); int archive_read_support_format_7zip(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct _7zip *zip; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_7zip"); zip = calloc(1, sizeof(*zip)); if (zip == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate 7zip data"); return (ARCHIVE_FATAL); } /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, zip, "7zip", archive_read_format_7zip_bid, NULL, archive_read_format_7zip_read_header, archive_read_format_7zip_read_data, archive_read_format_7zip_read_data_skip, NULL, archive_read_format_7zip_cleanup, archive_read_support_format_7zip_capabilities, archive_read_format_7zip_has_encrypted_entries); if (r != ARCHIVE_OK) free(zip); return (ARCHIVE_OK); } static int archive_read_support_format_7zip_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_7zip_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct _7zip * zip = (struct _7zip *)_a->format->data; if (zip) { return zip->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_7zip_bid(struct archive_read *a, int best_bid) { const char *p; /* If someone has already bid more than 32, then avoid trashing the look-ahead buffers with a seek. */ if (best_bid > 32) return (-1); if ((p = __archive_read_ahead(a, 6, NULL)) == NULL) return (0); /* If first six bytes are the 7-Zip signature, * return the bid right now. */ if (memcmp(p, _7ZIP_SIGNATURE, 6) == 0) return (48); /* * It may a 7-Zip SFX archive file. If first two bytes are * 'M' and 'Z' available on Windows or first four bytes are * "\x7F\x45LF" available on posix like system, seek the 7-Zip * signature. Although we will perform a seek when reading * a header, what we do not use __archive_read_seek() here is * due to a bidding performance. */ if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { ssize_t offset = SFX_MIN_ADDR; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (SFX_MAX_ADDR)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 32 < buff + bytes_avail) { int step = check_7zip_header_in_sfx(p); if (step == 0) return (48); p += step; } offset = p - buff; } } return (0); } static int check_7zip_header_in_sfx(const char *p) { switch ((unsigned char)p[5]) { case 0x1C: if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) return (6); /* * Test the CRC because its extraction code has 7-Zip * Magic Code, so we should do this in order not to * make a mis-detection. */ if (crc32(0, (const unsigned char *)p + 12, 20) != archive_le32dec(p + 8)) return (6); /* Hit the header! */ return (0); case 0x37: return (5); case 0x7A: return (4); case 0xBC: return (3); case 0xAF: return (2); case 0x27: return (1); default: return (6); } } static int skip_sfx(struct archive_read *a, ssize_t bytes_avail) { const void *h; const char *p, *q; size_t skip, offset; ssize_t bytes, window; /* * If bytes_avail > SFX_MIN_ADDR we do not have to call * __archive_read_seek() at this time since we have * alredy had enough data. */ if (bytes_avail > SFX_MIN_ADDR) __archive_read_consume(a, SFX_MIN_ADDR); else if (__archive_read_seek(a, SFX_MIN_ADDR, SEEK_SET) < 0) return (ARCHIVE_FATAL); offset = 0; window = 1; while (offset + window <= SFX_MAX_ADDR - SFX_MIN_ADDR) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 6) { /* This case might happen when window == 1. */ window = 4096; continue; } p = (const char *)h; q = p + bytes; /* * Scan ahead until we find something that looks * like the 7-Zip header. */ while (p + 32 < q) { int step = check_7zip_header_in_sfx(p); if (step == 0) { struct _7zip *zip = (struct _7zip *)a->format->data; skip = p - (const char *)h; __archive_read_consume(a, skip); zip->seek_base = SFX_MIN_ADDR + offset + skip; return (ARCHIVE_OK); } p += step; } skip = p - (const char *)h; __archive_read_consume(a, skip); offset += skip; if (window == 1) window = 4096; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out 7-Zip header"); return (ARCHIVE_FATAL); } static int archive_read_format_7zip_read_header(struct archive_read *a, struct archive_entry *entry) { struct _7zip *zip = (struct _7zip *)a->format->data; struct _7zip_entry *zip_entry; int r, ret = ARCHIVE_OK; struct _7z_folder *folder = 0; uint64_t fidx = 0; /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } a->archive.archive_format = ARCHIVE_FORMAT_7ZIP; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "7-Zip"; if (zip->entries == NULL) { struct _7z_header_info header; memset(&header, 0, sizeof(header)); r = slurp_central_directory(a, zip, &header); free_Header(&header); if (r != ARCHIVE_OK) return (r); zip->entries_remaining = (size_t)zip->numFiles; zip->entry = zip->entries; } else { ++zip->entry; } zip_entry = zip->entry; if (zip->entries_remaining <= 0 || zip_entry == NULL) return ARCHIVE_EOF; --zip->entries_remaining; zip->entry_offset = 0; zip->end_of_entry = 0; zip->entry_crc32 = crc32(0, NULL, 0); /* Setup a string conversion for a filename. */ if (zip->sconv == NULL) { zip->sconv = archive_string_conversion_from_charset( &a->archive, "UTF-16LE", 1); if (zip->sconv == NULL) return (ARCHIVE_FATAL); } /* Figure out if the entry is encrypted by looking at the folder that is associated to the current 7zip entry. If the folder has a coder with a _7Z_CRYPTO codec then the folder is encrypted. Hence the entry must also be encrypted. */ if (zip_entry && zip_entry->folderIndex < zip->si.ci.numFolders) { folder = &(zip->si.ci.folders[zip_entry->folderIndex]); for (fidx=0; folder && fidx<folder->numCoders; fidx++) { switch(folder->coders[fidx].codec) { case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: { archive_entry_set_is_data_encrypted(entry, 1); zip->has_encrypted_entries = 1; break; } } } } /* Now that we've checked for encryption, if there were still no * encrypted entries found we can say for sure that there are none. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if (archive_entry_copy_pathname_l(entry, (const char *)zip_entry->utf16name, zip_entry->name_len, zip->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name(zip->sconv)); ret = ARCHIVE_WARN; } /* Populate some additional entry fields: */ archive_entry_set_mode(entry, zip_entry->mode); if (zip_entry->flg & MTIME_IS_SET) archive_entry_set_mtime(entry, zip_entry->mtime, zip_entry->mtime_ns); if (zip_entry->flg & CTIME_IS_SET) archive_entry_set_ctime(entry, zip_entry->ctime, zip_entry->ctime_ns); if (zip_entry->flg & ATIME_IS_SET) archive_entry_set_atime(entry, zip_entry->atime, zip_entry->atime_ns); if (zip_entry->ssIndex != (uint32_t)-1) { zip->entry_bytes_remaining = zip->si.ss.unpackSizes[zip_entry->ssIndex]; archive_entry_set_size(entry, zip->entry_bytes_remaining); } else { zip->entry_bytes_remaining = 0; archive_entry_set_size(entry, 0); } /* If there's no body, force read_data() to return EOF immediately. */ if (zip->entry_bytes_remaining < 1) zip->end_of_entry = 1; if ((zip_entry->mode & AE_IFMT) == AE_IFLNK) { unsigned char *symname = NULL; size_t symsize = 0; /* * Symbolic-name is recorded as its contents. We have to * read the contents at this time. */ while (zip->entry_bytes_remaining > 0) { const void *buff; unsigned char *mem; size_t size; int64_t offset; r = archive_read_format_7zip_read_data(a, &buff, &size, &offset); if (r < ARCHIVE_WARN) { free(symname); return (r); } mem = realloc(symname, symsize + size + 1); if (mem == NULL) { free(symname); archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Symname"); return (ARCHIVE_FATAL); } symname = mem; memcpy(symname+symsize, buff, size); symsize += size; } if (symsize == 0) { /* If there is no synname, handle it as a regular * file. */ zip_entry->mode &= ~AE_IFMT; zip_entry->mode |= AE_IFREG; archive_entry_set_mode(entry, zip_entry->mode); } else { symname[symsize] = '\0'; archive_entry_copy_symlink(entry, (const char *)symname); } free(symname); archive_entry_set_size(entry, 0); } /* Set up a more descriptive format name. */ sprintf(zip->format_name, "7-Zip"); a->archive.archive_format_name = zip->format_name; return (ret); } static int archive_read_format_7zip_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct _7zip *zip; ssize_t bytes; int ret = ARCHIVE_OK; zip = (struct _7zip *)(a->format->data); if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if (zip->pack_stream_bytes_unconsumed) read_consume(a); *offset = zip->entry_offset; *size = 0; *buff = NULL; /* * If we hit end-of-entry last time, clean up and return * ARCHIVE_EOF this time. */ if (zip->end_of_entry) return (ARCHIVE_EOF); bytes = read_stream(a, buff, (size_t)zip->entry_bytes_remaining, 0); if (bytes < 0) return ((int)bytes); if (bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } zip->entry_bytes_remaining -= bytes; if (zip->entry_bytes_remaining == 0) zip->end_of_entry = 1; /* Update checksum */ if ((zip->entry->flg & CRC32_IS_SET) && bytes) zip->entry_crc32 = crc32(zip->entry_crc32, *buff, (unsigned)bytes); /* If we hit the end, swallow any end-of-data marker. */ if (zip->end_of_entry) { /* Check computed CRC against file contents. */ if ((zip->entry->flg & CRC32_IS_SET) && zip->si.ss.digests[zip->entry->ssIndex] != zip->entry_crc32) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "7-Zip bad CRC: 0x%lx should be 0x%lx", (unsigned long)zip->entry_crc32, (unsigned long)zip->si.ss.digests[ zip->entry->ssIndex]); ret = ARCHIVE_WARN; } } *size = bytes; *offset = zip->entry_offset; zip->entry_offset += bytes; return (ret); } static int archive_read_format_7zip_read_data_skip(struct archive_read *a) { struct _7zip *zip; int64_t bytes_skipped; zip = (struct _7zip *)(a->format->data); if (zip->pack_stream_bytes_unconsumed) read_consume(a); /* If we've already read to end of data, we're done. */ if (zip->end_of_entry) return (ARCHIVE_OK); /* * If the length is at the beginning, we can skip the * compressed data much more quickly. */ bytes_skipped = skip_stream(a, (size_t)zip->entry_bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); zip->entry_bytes_remaining = 0; /* This entry is finished and done. */ zip->end_of_entry = 1; return (ARCHIVE_OK); } static int archive_read_format_7zip_cleanup(struct archive_read *a) { struct _7zip *zip; zip = (struct _7zip *)(a->format->data); free_StreamsInfo(&(zip->si)); free(zip->entries); free(zip->entry_names); free_decompression(a, zip); free(zip->uncompressed_buffer); free(zip->sub_stream_buff[0]); free(zip->sub_stream_buff[1]); free(zip->sub_stream_buff[2]); free(zip->tmp_stream_buff); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); } static void read_consume(struct archive_read *a) { struct _7zip *zip = (struct _7zip *)a->format->data; if (zip->pack_stream_bytes_unconsumed) { __archive_read_consume(a, zip->pack_stream_bytes_unconsumed); zip->stream_offset += zip->pack_stream_bytes_unconsumed; zip->pack_stream_bytes_unconsumed = 0; } } #ifdef HAVE_LZMA_H /* * Set an error code and choose an error message for liblzma. */ static void set_error(struct archive_read *a, int ret) { switch (ret) { case LZMA_STREAM_END: /* Found end of stream. */ case LZMA_OK: /* Decompressor made some progress. */ break; case LZMA_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Lzma library error: Cannot allocate memory"); break; case LZMA_MEMLIMIT_ERROR: archive_set_error(&a->archive, ENOMEM, "Lzma library error: Out of memory"); break; case LZMA_FORMAT_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: format not recognized"); break; case LZMA_OPTIONS_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: Invalid options"); break; case LZMA_DATA_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: Corrupted input data"); break; case LZMA_BUF_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma library error: No progress is possible"); break; default: /* Return an error. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Lzma decompression failed: Unknown error"); break; } } #endif static unsigned long decode_codec_id(const unsigned char *codecId, size_t id_size) { unsigned i; unsigned long id = 0; for (i = 0; i < id_size; i++) { id <<= 8; id += codecId[i]; } return (id); } static void * ppmd_alloc(void *p, size_t size) { (void)p; return malloc(size); } static void ppmd_free(void *p, void *address) { (void)p; free(address); } static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct _7zip *zip = (struct _7zip *)(a->format->data); Byte b; if (zip->ppstream.avail_in == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); zip->ppstream.overconsumed = 1; return (0); } b = *zip->ppstream.next_in++; zip->ppstream.avail_in--; zip->ppstream.total_in++; return (b); } static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free }; static int init_decompression(struct archive_read *a, struct _7zip *zip, const struct _7z_coder *coder1, const struct _7z_coder *coder2) { int r; zip->codec = coder1->codec; zip->codec2 = -1; switch (zip->codec) { case _7Z_COPY: case _7Z_BZ2: case _7Z_DEFLATE: case _7Z_PPMD: if (coder2 != NULL) { if (coder2->codec != _7Z_X86 && coder2->codec != _7Z_X86_BCJ2) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unsupported filter %lx for %lx", coder2->codec, coder1->codec); return (ARCHIVE_FAILED); } zip->codec2 = coder2->codec; zip->bcj_state = 0; if (coder2->codec == _7Z_X86) x86_Init(zip); } break; default: break; } switch (zip->codec) { case _7Z_COPY: break; case _7Z_LZMA: case _7Z_LZMA2: #ifdef HAVE_LZMA_H #if LZMA_VERSION_MAJOR >= 5 /* Effectively disable the limiter. */ #define LZMA_MEMLIMIT UINT64_MAX #else /* NOTE: This needs to check memory size which running system has. */ #define LZMA_MEMLIMIT (1U << 30) #endif { lzma_options_delta delta_opt; lzma_filter filters[LZMA_FILTERS_MAX]; #if LZMA_VERSION < 50010000 lzma_filter *ff; #endif int fi = 0; if (zip->lzstream_valid) { lzma_end(&(zip->lzstream)); zip->lzstream_valid = 0; } /* * NOTE: liblzma incompletely handle the BCJ+LZMA compressed * data made by 7-Zip because 7-Zip does not add End-Of- * Payload Marker(EOPM) at the end of LZMA compressed data, * and so liblzma cannot know the end of the compressed data * without EOPM. So consequently liblzma will not return last * three or four bytes of uncompressed data because * LZMA_FILTER_X86 filter does not handle input data if its * data size is less than five bytes. If liblzma detect EOPM * or know the uncompressed data size, liblzma will flush out * the remaining that three or four bytes of uncompressed * data. That is why we have to use our converting program * for BCJ+LZMA. If we were able to tell the uncompressed * size to liblzma when using lzma_raw_decoder() liblzma * could correctly deal with BCJ+LZMA. But unfortunately * there is no way to do that. * Discussion about this can be found at XZ Utils forum. */ if (coder2 != NULL) { zip->codec2 = coder2->codec; filters[fi].options = NULL; switch (zip->codec2) { case _7Z_X86: if (zip->codec == _7Z_LZMA2) { filters[fi].id = LZMA_FILTER_X86; fi++; } else /* Use our filter. */ x86_Init(zip); break; case _7Z_X86_BCJ2: /* Use our filter. */ zip->bcj_state = 0; break; case _7Z_DELTA: filters[fi].id = LZMA_FILTER_DELTA; memset(&delta_opt, 0, sizeof(delta_opt)); delta_opt.type = LZMA_DELTA_TYPE_BYTE; delta_opt.dist = 1; filters[fi].options = &delta_opt; fi++; break; /* Following filters have not been tested yet. */ case _7Z_POWERPC: filters[fi].id = LZMA_FILTER_POWERPC; fi++; break; case _7Z_IA64: filters[fi].id = LZMA_FILTER_IA64; fi++; break; case _7Z_ARM: filters[fi].id = LZMA_FILTER_ARM; fi++; break; case _7Z_ARMTHUMB: filters[fi].id = LZMA_FILTER_ARMTHUMB; fi++; break; case _7Z_SPARC: filters[fi].id = LZMA_FILTER_SPARC; fi++; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unexpected codec ID: %lX", zip->codec2); return (ARCHIVE_FAILED); } } if (zip->codec == _7Z_LZMA2) filters[fi].id = LZMA_FILTER_LZMA2; else filters[fi].id = LZMA_FILTER_LZMA1; filters[fi].options = NULL; #if LZMA_VERSION < 50010000 ff = &filters[fi]; #endif r = lzma_properties_decode(&filters[fi], NULL, coder1->properties, (size_t)coder1->propertiesSize); if (r != LZMA_OK) { set_error(a, r); return (ARCHIVE_FAILED); } fi++; filters[fi].id = LZMA_VLI_UNKNOWN; filters[fi].options = NULL; r = lzma_raw_decoder(&(zip->lzstream), filters); #if LZMA_VERSION < 50010000 free(ff->options); #endif if (r != LZMA_OK) { set_error(a, r); return (ARCHIVE_FAILED); } zip->lzstream_valid = 1; zip->lzstream.total_in = 0; zip->lzstream.total_out = 0; break; } #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "LZMA codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_BZ2: #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&(zip->bzstream)); zip->bzstream_valid = 0; } r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 0); if (r == BZ_MEM_ERROR) r = BZ2_bzDecompressInit(&(zip->bzstream), 0, 1); if (r != BZ_OK) { int err = ARCHIVE_ERRNO_MISC; const char *detail = NULL; switch (r) { case BZ_PARAM_ERROR: detail = "invalid setup parameter"; break; case BZ_MEM_ERROR: err = ENOMEM; detail = "out of memory"; break; case BZ_CONFIG_ERROR: detail = "mis-compiled library"; break; } archive_set_error(&a->archive, err, "Internal error initializing decompressor: %s", detail != NULL ? detail : "??"); zip->bzstream_valid = 0; return (ARCHIVE_FAILED); } zip->bzstream_valid = 1; zip->bzstream.total_in_lo32 = 0; zip->bzstream.total_in_hi32 = 0; zip->bzstream.total_out_lo32 = 0; zip->bzstream.total_out_hi32 = 0; break; #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "BZ2 codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_DEFLATE: #ifdef HAVE_ZLIB_H if (zip->stream_valid) r = inflateReset(&(zip->stream)); else r = inflateInit2(&(zip->stream), -15 /* Don't check for zlib header */); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't initialize zlib stream."); return (ARCHIVE_FAILED); } zip->stream_valid = 1; zip->stream.total_in = 0; zip->stream.total_out = 0; break; #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "DEFLATE codec is unsupported"); return (ARCHIVE_FAILED); #endif case _7Z_PPMD: { unsigned order; uint32_t msize; if (zip->ppmd7_valid) { __archive_ppmd7_functions.Ppmd7_Free( &zip->ppmd7_context, &g_szalloc); zip->ppmd7_valid = 0; } if (coder1->propertiesSize < 5) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed PPMd parameter"); return (ARCHIVE_FAILED); } order = coder1->properties[0]; msize = archive_le32dec(&(coder1->properties[1])); if (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER || msize < PPMD7_MIN_MEM_SIZE || msize > PPMD7_MAX_MEM_SIZE) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed PPMd parameter"); return (ARCHIVE_FAILED); } __archive_ppmd7_functions.Ppmd7_Construct(&zip->ppmd7_context); r = __archive_ppmd7_functions.Ppmd7_Alloc( &zip->ppmd7_context, msize, &g_szalloc); if (r == 0) { archive_set_error(&a->archive, ENOMEM, "Coludn't allocate memory for PPMd"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init( &zip->ppmd7_context, order); __archive_ppmd7_functions.Ppmd7z_RangeDec_CreateVTable( &zip->range_dec); zip->ppmd7_valid = 1; zip->ppmd7_stat = 0; zip->ppstream.overconsumed = 0; zip->ppstream.total_in = 0; zip->ppstream.total_out = 0; break; } case _7Z_X86: case _7Z_X86_BCJ2: case _7Z_POWERPC: case _7Z_IA64: case _7Z_ARM: case _7Z_ARMTHUMB: case _7Z_SPARC: case _7Z_DELTA: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unexpected codec ID: %lX", zip->codec); return (ARCHIVE_FAILED); case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: if (a->entry) { archive_entry_set_is_metadata_encrypted(a->entry, 1); archive_entry_set_is_data_encrypted(a->entry, 1); zip->has_encrypted_entries = 1; } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Crypto codec not supported yet (ID: 0x%lX)", zip->codec); return (ARCHIVE_FAILED); default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Unknown codec ID: %lX", zip->codec); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } static int decompress(struct archive_read *a, struct _7zip *zip, void *buff, size_t *outbytes, const void *b, size_t *used) { const uint8_t *t_next_in; uint8_t *t_next_out; size_t o_avail_in, o_avail_out; size_t t_avail_in, t_avail_out; uint8_t *bcj2_next_out; size_t bcj2_avail_out; int r, ret = ARCHIVE_OK; t_avail_in = o_avail_in = *used; t_avail_out = o_avail_out = *outbytes; t_next_in = b; t_next_out = buff; if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { int i; /* Do not copy out the BCJ remaining bytes when the output * buffer size is less than five bytes. */ if (o_avail_in != 0 && t_avail_out < 5 && zip->odd_bcj_size) { *used = 0; *outbytes = 0; return (ret); } for (i = 0; zip->odd_bcj_size > 0 && t_avail_out; i++) { *t_next_out++ = zip->odd_bcj[i]; t_avail_out--; zip->odd_bcj_size--; } if (o_avail_in == 0 || t_avail_out == 0) { *used = o_avail_in - t_avail_in; *outbytes = o_avail_out - t_avail_out; if (o_avail_in == 0) ret = ARCHIVE_EOF; return (ret); } } bcj2_next_out = t_next_out; bcj2_avail_out = t_avail_out; if (zip->codec2 == _7Z_X86_BCJ2) { /* * Decord a remaining decompressed main stream for BCJ2. */ if (zip->tmp_stream_bytes_remaining) { ssize_t bytes; size_t remaining = zip->tmp_stream_bytes_remaining; bytes = Bcj2_Decode(zip, t_next_out, t_avail_out); if (bytes < 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed"); return (ARCHIVE_FAILED); } zip->main_stream_bytes_remaining -= remaining - zip->tmp_stream_bytes_remaining; t_avail_out -= bytes; if (o_avail_in == 0 || t_avail_out == 0) { *used = 0; *outbytes = o_avail_out - t_avail_out; if (o_avail_in == 0 && zip->tmp_stream_bytes_remaining) ret = ARCHIVE_EOF; return (ret); } t_next_out += bytes; bcj2_next_out = t_next_out; bcj2_avail_out = t_avail_out; } t_next_out = zip->tmp_stream_buff; t_avail_out = zip->tmp_stream_buff_size; } switch (zip->codec) { case _7Z_COPY: { size_t bytes = (t_avail_in > t_avail_out)?t_avail_out:t_avail_in; memcpy(t_next_out, t_next_in, bytes); t_avail_in -= bytes; t_avail_out -= bytes; if (o_avail_in == 0) ret = ARCHIVE_EOF; break; } #ifdef HAVE_LZMA_H case _7Z_LZMA: case _7Z_LZMA2: zip->lzstream.next_in = t_next_in; zip->lzstream.avail_in = t_avail_in; zip->lzstream.next_out = t_next_out; zip->lzstream.avail_out = t_avail_out; r = lzma_code(&(zip->lzstream), LZMA_RUN); switch (r) { case LZMA_STREAM_END: /* Found end of stream. */ lzma_end(&(zip->lzstream)); zip->lzstream_valid = 0; ret = ARCHIVE_EOF; break; case LZMA_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression failed(%d)", r); return (ARCHIVE_FAILED); } t_avail_in = zip->lzstream.avail_in; t_avail_out = zip->lzstream.avail_out; break; #endif #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case _7Z_BZ2: zip->bzstream.next_in = (char *)(uintptr_t)t_next_in; zip->bzstream.avail_in = t_avail_in; zip->bzstream.next_out = (char *)(uintptr_t)t_next_out; zip->bzstream.avail_out = t_avail_out; r = BZ2_bzDecompress(&(zip->bzstream)); switch (r) { case BZ_STREAM_END: /* Found end of stream. */ switch (BZ2_bzDecompressEnd(&(zip->bzstream))) { case BZ_OK: break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Failed to clean up decompressor"); return (ARCHIVE_FAILED); } zip->bzstream_valid = 0; ret = ARCHIVE_EOF; break; case BZ_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "bzip decompression failed"); return (ARCHIVE_FAILED); } t_avail_in = zip->bzstream.avail_in; t_avail_out = zip->bzstream.avail_out; break; #endif #ifdef HAVE_ZLIB_H case _7Z_DEFLATE: zip->stream.next_in = (Bytef *)(uintptr_t)t_next_in; zip->stream.avail_in = (uInt)t_avail_in; zip->stream.next_out = t_next_out; zip->stream.avail_out = (uInt)t_avail_out; r = inflate(&(zip->stream), 0); switch (r) { case Z_STREAM_END: /* Found end of stream. */ ret = ARCHIVE_EOF; break; case Z_OK: /* Decompressor made some progress.*/ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "File decompression failed (%d)", r); return (ARCHIVE_FAILED); } t_avail_in = zip->stream.avail_in; t_avail_out = zip->stream.avail_out; break; #endif case _7Z_PPMD: { uint64_t flush_bytes; if (!zip->ppmd7_valid || zip->ppmd7_stat < 0 || t_avail_out <= 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression internal error"); return (ARCHIVE_FAILED); } zip->ppstream.next_in = t_next_in; zip->ppstream.avail_in = t_avail_in; zip->ppstream.next_out = t_next_out; zip->ppstream.avail_out = t_avail_out; if (zip->ppmd7_stat == 0) { zip->bytein.a = a; zip->bytein.Read = &ppmd_read; zip->range_dec.Stream = &zip->bytein; r = __archive_ppmd7_functions.Ppmd7z_RangeDec_Init( &(zip->range_dec)); if (r == 0) { zip->ppmd7_stat = -1; archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to initialize PPMd range decorder"); return (ARCHIVE_FAILED); } if (zip->ppstream.overconsumed) { zip->ppmd7_stat = -1; return (ARCHIVE_FAILED); } zip->ppmd7_stat = 1; } if (t_avail_in == 0) /* XXX Flush out remaining decoded data XXX */ flush_bytes = zip->folder_outbytes_remaining; else flush_bytes = 0; do { int sym; sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &(zip->ppmd7_context), &(zip->range_dec.p)); if (sym < 0) { zip->ppmd7_stat = -1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Failed to decode PPMd"); return (ARCHIVE_FAILED); } if (zip->ppstream.overconsumed) { zip->ppmd7_stat = -1; return (ARCHIVE_FAILED); } *zip->ppstream.next_out++ = (unsigned char)sym; zip->ppstream.avail_out--; zip->ppstream.total_out++; if (flush_bytes) flush_bytes--; } while (zip->ppstream.avail_out && (zip->ppstream.avail_in || flush_bytes)); t_avail_in = (size_t)zip->ppstream.avail_in; t_avail_out = (size_t)zip->ppstream.avail_out; break; } default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompression internal error"); return (ARCHIVE_FAILED); } if (ret != ARCHIVE_OK && ret != ARCHIVE_EOF) return (ret); *used = o_avail_in - t_avail_in; *outbytes = o_avail_out - t_avail_out; /* * Decord BCJ. */ if (zip->codec != _7Z_LZMA2 && zip->codec2 == _7Z_X86) { size_t l = x86_Convert(zip, buff, *outbytes); zip->odd_bcj_size = *outbytes - l; if (zip->odd_bcj_size > 0 && zip->odd_bcj_size <= 4 && o_avail_in && ret != ARCHIVE_EOF) { memcpy(zip->odd_bcj, ((unsigned char *)buff) + l, zip->odd_bcj_size); *outbytes = l; } else zip->odd_bcj_size = 0; } /* * Decord BCJ2 with a decompressed main stream. */ if (zip->codec2 == _7Z_X86_BCJ2) { ssize_t bytes; zip->tmp_stream_bytes_avail = zip->tmp_stream_buff_size - t_avail_out; if (zip->tmp_stream_bytes_avail > zip->main_stream_bytes_remaining) zip->tmp_stream_bytes_avail = zip->main_stream_bytes_remaining; zip->tmp_stream_bytes_remaining = zip->tmp_stream_bytes_avail; bytes = Bcj2_Decode(zip, bcj2_next_out, bcj2_avail_out); if (bytes < 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "BCJ2 conversion Failed"); return (ARCHIVE_FAILED); } zip->main_stream_bytes_remaining -= zip->tmp_stream_bytes_avail - zip->tmp_stream_bytes_remaining; bcj2_avail_out -= bytes; *outbytes = o_avail_out - bcj2_avail_out; } return (ret); } static int free_decompression(struct archive_read *a, struct _7zip *zip) { int r = ARCHIVE_OK; #if !defined(HAVE_ZLIB_H) &&\ !(defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)) (void)a;/* UNUSED */ #endif #ifdef HAVE_LZMA_H if (zip->lzstream_valid) lzma_end(&(zip->lzstream)); #endif #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (zip->bzstream_valid) { if (BZ2_bzDecompressEnd(&(zip->bzstream)) != BZ_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up bzip2 decompressor"); r = ARCHIVE_FATAL; } zip->bzstream_valid = 0; } #endif #ifdef HAVE_ZLIB_H if (zip->stream_valid) { if (inflateEnd(&(zip->stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up zlib decompressor"); r = ARCHIVE_FATAL; } zip->stream_valid = 0; } #endif if (zip->ppmd7_valid) { __archive_ppmd7_functions.Ppmd7_Free( &zip->ppmd7_context, &g_szalloc); zip->ppmd7_valid = 0; } return (r); } static int parse_7zip_uint64(struct archive_read *a, uint64_t *val) { const unsigned char *p; unsigned char avail, mask; int i; if ((p = header_bytes(a, 1)) == NULL) return (-1); avail = *p; mask = 0x80; *val = 0; for (i = 0; i < 8; i++) { if (avail & mask) { if ((p = header_bytes(a, 1)) == NULL) return (-1); *val |= ((uint64_t)*p) << (8 * i); mask >>= 1; continue; } *val += ((uint64_t)(avail & (mask -1))) << (8 * i); break; } return (0); } static int read_Bools(struct archive_read *a, unsigned char *data, size_t num) { const unsigned char *p; unsigned i, mask = 0, avail = 0; for (i = 0; i < num; i++) { if (mask == 0) { if ((p = header_bytes(a, 1)) == NULL) return (-1); avail = *p; mask = 0x80; } data[i] = (avail & mask)?1:0; mask >>= 1; } return (0); } static void free_Digest(struct _7z_digests *d) { free(d->defineds); free(d->digests); } static int read_Digests(struct archive_read *a, struct _7z_digests *d, size_t num) { const unsigned char *p; unsigned i; if (num == 0) return (-1); memset(d, 0, sizeof(*d)); d->defineds = malloc(num); if (d->defineds == NULL) return (-1); /* * Read Bools. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) { if (read_Bools(a, d->defineds, num) < 0) return (-1); } else /* All are defined */ memset(d->defineds, 1, num); d->digests = calloc(num, sizeof(*d->digests)); if (d->digests == NULL) return (-1); for (i = 0; i < num; i++) { if (d->defineds[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); d->digests[i] = archive_le32dec(p); } } return (0); } static void free_PackInfo(struct _7z_pack_info *pi) { free(pi->sizes); free(pi->positions); free_Digest(&(pi->digest)); } static int read_PackInfo(struct archive_read *a, struct _7z_pack_info *pi) { const unsigned char *p; unsigned i; memset(pi, 0, sizeof(*pi)); /* * Read PackPos. */ if (parse_7zip_uint64(a, &(pi->pos)) < 0) return (-1); /* * Read NumPackStreams. */ if (parse_7zip_uint64(a, &(pi->numPackStreams)) < 0) return (-1); if (pi->numPackStreams == 0) return (-1); if (UMAX_ENTRY < pi->numPackStreams) return (-1); /* * Read PackSizes[num] */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kEnd) /* PackSizes[num] are not present. */ return (0); if (*p != kSize) return (-1); pi->sizes = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); pi->positions = calloc((size_t)pi->numPackStreams, sizeof(uint64_t)); if (pi->sizes == NULL || pi->positions == NULL) return (-1); for (i = 0; i < pi->numPackStreams; i++) { if (parse_7zip_uint64(a, &(pi->sizes[i])) < 0) return (-1); } /* * Read PackStreamDigests[num] */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kEnd) { /* PackStreamDigests[num] are not present. */ pi->digest.defineds = calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.defineds)); pi->digest.digests = calloc((size_t)pi->numPackStreams, sizeof(*pi->digest.digests)); if (pi->digest.defineds == NULL || pi->digest.digests == NULL) return (-1); return (0); } if (*p != kSize) return (-1); if (read_Digests(a, &(pi->digest), (size_t)pi->numPackStreams) < 0) return (-1); /* * Must be marked by kEnd. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kEnd) return (-1); return (0); } static void free_Folder(struct _7z_folder *f) { unsigned i; if (f->coders) { for (i = 0; i< f->numCoders; i++) { free(f->coders[i].properties); } free(f->coders); } free(f->bindPairs); free(f->packedStreams); free(f->unPackSize); } static int read_Folder(struct archive_read *a, struct _7z_folder *f) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; uint64_t numInStreamsTotal = 0; uint64_t numOutStreamsTotal = 0; unsigned i; memset(f, 0, sizeof(*f)); /* * Read NumCoders. */ if (parse_7zip_uint64(a, &(f->numCoders)) < 0) return (-1); if (f->numCoders > 4) /* Too many coders. */ return (-1); f->coders = calloc((size_t)f->numCoders, sizeof(*f->coders)); if (f->coders == NULL) return (-1); for (i = 0; i< f->numCoders; i++) { size_t codec_size; int simple, attr; if ((p = header_bytes(a, 1)) == NULL) return (-1); /* * 0:3 CodecIdSize * 4: 0 - IsSimple * 1 - Is not Simple * 5: 0 - No Attributes * 1 - There are Attributes; * 7: Must be zero. */ codec_size = *p & 0xf; simple = (*p & 0x10)?0:1; attr = *p & 0x20; if (*p & 0x80) return (-1);/* Not supported. */ /* * Read Decompression Method IDs. */ if ((p = header_bytes(a, codec_size)) == NULL) return (-1); f->coders[i].codec = decode_codec_id(p, codec_size); if (simple) { f->coders[i].numInStreams = 1; f->coders[i].numOutStreams = 1; } else { if (parse_7zip_uint64( a, &(f->coders[i].numInStreams)) < 0) return (-1); if (UMAX_ENTRY < f->coders[i].numInStreams) return (-1); if (parse_7zip_uint64( a, &(f->coders[i].numOutStreams)) < 0) return (-1); if (UMAX_ENTRY < f->coders[i].numOutStreams) return (-1); } if (attr) { if (parse_7zip_uint64( a, &(f->coders[i].propertiesSize)) < 0) return (-1); if ((p = header_bytes( a, (size_t)f->coders[i].propertiesSize)) == NULL) return (-1); f->coders[i].properties = malloc((size_t)f->coders[i].propertiesSize); if (f->coders[i].properties == NULL) return (-1); memcpy(f->coders[i].properties, p, (size_t)f->coders[i].propertiesSize); } numInStreamsTotal += f->coders[i].numInStreams; numOutStreamsTotal += f->coders[i].numOutStreams; } if (numOutStreamsTotal == 0 || numInStreamsTotal < numOutStreamsTotal-1) return (-1); f->numBindPairs = numOutStreamsTotal - 1; if (zip->header_bytes_remaining < f->numBindPairs) return (-1); if (f->numBindPairs > 0) { f->bindPairs = calloc((size_t)f->numBindPairs, sizeof(*f->bindPairs)); if (f->bindPairs == NULL) return (-1); } else f->bindPairs = NULL; for (i = 0; i < f->numBindPairs; i++) { if (parse_7zip_uint64(a, &(f->bindPairs[i].inIndex)) < 0) return (-1); if (UMAX_ENTRY < f->bindPairs[i].inIndex) return (-1); if (parse_7zip_uint64(a, &(f->bindPairs[i].outIndex)) < 0) return (-1); if (UMAX_ENTRY < f->bindPairs[i].outIndex) return (-1); } f->numPackedStreams = numInStreamsTotal - f->numBindPairs; f->packedStreams = calloc((size_t)f->numPackedStreams, sizeof(*f->packedStreams)); if (f->packedStreams == NULL) return (-1); if (f->numPackedStreams == 1) { for (i = 0; i < numInStreamsTotal; i++) { unsigned j; for (j = 0; j < f->numBindPairs; j++) { if (f->bindPairs[j].inIndex == i) break; } if (j == f->numBindPairs) break; } if (i == numInStreamsTotal) return (-1); f->packedStreams[0] = i; } else { for (i = 0; i < f->numPackedStreams; i++) { if (parse_7zip_uint64(a, &(f->packedStreams[i])) < 0) return (-1); if (UMAX_ENTRY < f->packedStreams[i]) return (-1); } } f->numInStreams = numInStreamsTotal; f->numOutStreams = numOutStreamsTotal; return (0); } static void free_CodersInfo(struct _7z_coders_info *ci) { unsigned i; if (ci->folders) { for (i = 0; i < ci->numFolders; i++) free_Folder(&(ci->folders[i])); free(ci->folders); } } static int read_CodersInfo(struct archive_read *a, struct _7z_coders_info *ci) { const unsigned char *p; struct _7z_digests digest; unsigned i; memset(ci, 0, sizeof(*ci)); memset(&digest, 0, sizeof(digest)); if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kFolder) goto failed; /* * Read NumFolders. */ if (parse_7zip_uint64(a, &(ci->numFolders)) < 0) goto failed; if (UMAX_ENTRY < ci->numFolders) return (-1); /* * Read External. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; switch (*p) { case 0: ci->folders = calloc((size_t)ci->numFolders, sizeof(*ci->folders)); if (ci->folders == NULL) return (-1); for (i = 0; i < ci->numFolders; i++) { if (read_Folder(a, &(ci->folders[i])) < 0) goto failed; } break; case 1: if (parse_7zip_uint64(a, &(ci->dataStreamIndex)) < 0) return (-1); if (UMAX_ENTRY < ci->dataStreamIndex) return (-1); if (ci->numFolders > 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); goto failed; } break; default: archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); goto failed; } if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kCodersUnPackSize) goto failed; for (i = 0; i < ci->numFolders; i++) { struct _7z_folder *folder = &(ci->folders[i]); unsigned j; folder->unPackSize = calloc((size_t)folder->numOutStreams, sizeof(*folder->unPackSize)); if (folder->unPackSize == NULL) goto failed; for (j = 0; j < folder->numOutStreams; j++) { if (parse_7zip_uint64(a, &(folder->unPackSize[j])) < 0) goto failed; } } /* * Read CRCs. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p == kEnd) return (0); if (*p != kCRC) goto failed; if (read_Digests(a, &digest, (size_t)ci->numFolders) < 0) goto failed; for (i = 0; i < ci->numFolders; i++) { ci->folders[i].digest_defined = digest.defineds[i]; ci->folders[i].digest = digest.digests[i]; } /* * Must be kEnd. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p != kEnd) goto failed; free_Digest(&digest); return (0); failed: free_Digest(&digest); return (-1); } static uint64_t folder_uncompressed_size(struct _7z_folder *f) { int n = (int)f->numOutStreams; unsigned pairs = (unsigned)f->numBindPairs; while (--n >= 0) { unsigned i; for (i = 0; i < pairs; i++) { if (f->bindPairs[i].outIndex == (uint64_t)n) break; } if (i >= pairs) return (f->unPackSize[n]); } return (0); } static void free_SubStreamsInfo(struct _7z_substream_info *ss) { free(ss->unpackSizes); free(ss->digestsDefined); free(ss->digests); } static int read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { return (-1); } unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); } static void free_StreamsInfo(struct _7z_stream_info *si) { free_PackInfo(&(si->pi)); free_CodersInfo(&(si->ci)); free_SubStreamsInfo(&(si->ss)); } static int read_StreamsInfo(struct archive_read *a, struct _7z_stream_info *si) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; unsigned i; memset(si, 0, sizeof(*si)); if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kPackInfo) { uint64_t packPos; if (read_PackInfo(a, &(si->pi)) < 0) return (-1); if (si->pi.positions == NULL || si->pi.sizes == NULL) return (-1); /* * Calculate packed stream positions. */ packPos = si->pi.pos; for (i = 0; i < si->pi.numPackStreams; i++) { si->pi.positions[i] = packPos; packPos += si->pi.sizes[i]; if (packPos > zip->header_offset) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kUnPackInfo) { uint32_t packIndex; struct _7z_folder *f; if (read_CodersInfo(a, &(si->ci)) < 0) return (-1); /* * Calculate packed stream indexes. */ packIndex = 0; f = si->ci.folders; for (i = 0; i < si->ci.numFolders; i++) { f[i].packIndex = packIndex; packIndex += (uint32_t)f[i].numPackedStreams; if (packIndex > si->pi.numPackStreams) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kSubStreamsInfo) { if (read_SubStreamsInfo(a, &(si->ss), si->ci.folders, (size_t)si->ci.numFolders) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Must be kEnd. */ if (*p != kEnd) return (-1); return (0); } static void free_Header(struct _7z_header_info *h) { free(h->emptyStreamBools); free(h->emptyFileBools); free(h->antiBools); free(h->attrBools); } static int read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); } #define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) static void fileTimeToUtc(uint64_t fileTime, time_t *timep, long *ns) { if (fileTime >= EPOC_TIME) { fileTime -= EPOC_TIME; /* milli seconds base */ *timep = (time_t)(fileTime / 10000000); /* nano seconds base */ *ns = (long)(fileTime % 10000000) * 100; } else { *timep = 0; *ns = 0; } } static int read_Times(struct archive_read *a, struct _7z_header_info *h, int type) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7zip_entry *entries = zip->entries; unsigned char *timeBools; int allAreDefined; unsigned i; timeBools = calloc((size_t)zip->numFiles, sizeof(*timeBools)); if (timeBools == NULL) return (-1); /* Read allAreDefined. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; allAreDefined = *p; if (allAreDefined) memset(timeBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, timeBools, (size_t)zip->numFiles) < 0) goto failed; } /* Read external. */ if ((p = header_bytes(a, 1)) == NULL) goto failed; if (*p) { if (parse_7zip_uint64(a, &(h->dataIndex)) < 0) goto failed; if (UMAX_ENTRY < h->dataIndex) goto failed; } for (i = 0; i < zip->numFiles; i++) { if (!timeBools[i]) continue; if ((p = header_bytes(a, 8)) == NULL) goto failed; switch (type) { case kCTime: fileTimeToUtc(archive_le64dec(p), &(entries[i].ctime), &(entries[i].ctime_ns)); entries[i].flg |= CTIME_IS_SET; break; case kATime: fileTimeToUtc(archive_le64dec(p), &(entries[i].atime), &(entries[i].atime_ns)); entries[i].flg |= ATIME_IS_SET; break; case kMTime: fileTimeToUtc(archive_le64dec(p), &(entries[i].mtime), &(entries[i].mtime_ns)); entries[i].flg |= MTIME_IS_SET; break; } } free(timeBools); return (0); failed: free(timeBools); return (-1); } static int decode_encoded_header_info(struct archive_read *a, struct _7z_stream_info *si) { struct _7zip *zip = (struct _7zip *)a->format->data; errno = 0; if (read_StreamsInfo(a, si) < 0) { if (errno == ENOMEM) archive_set_error(&a->archive, -1, "Couldn't allocate memory"); else archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } if (si->pi.numPackStreams == 0 || si->ci.numFolders == 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } if (zip->header_offset < si->pi.pos + si->pi.sizes[0] || (int64_t)(si->pi.pos + si->pi.sizes[0]) < 0 || si->pi.sizes[0] == 0 || (int64_t)si->pi.pos < 0) { archive_set_error(&a->archive, -1, "Malformed Header offset"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } static const unsigned char * header_bytes(struct archive_read *a, size_t rbytes) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; if (zip->header_bytes_remaining < rbytes) return (NULL); if (zip->pack_stream_bytes_unconsumed) read_consume(a); if (zip->header_is_encoded == 0) { p = __archive_read_ahead(a, rbytes, NULL); if (p == NULL) return (NULL); zip->header_bytes_remaining -= rbytes; zip->pack_stream_bytes_unconsumed = rbytes; } else { const void *buff; ssize_t bytes; bytes = read_stream(a, &buff, rbytes, rbytes); if (bytes <= 0) return (NULL); zip->header_bytes_remaining -= bytes; p = buff; } /* Update checksum */ zip->header_crc32 = crc32(zip->header_crc32, p, (unsigned)rbytes); return (p); } static int slurp_central_directory(struct archive_read *a, struct _7zip *zip, struct _7z_header_info *header) { const unsigned char *p; uint64_t next_header_offset; uint64_t next_header_size; uint32_t next_header_crc; ssize_t bytes_avail; int check_header_crc, r; if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) return (ARCHIVE_FATAL); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is an executable ? Must be self-extracting... */ r = skip_sfx(a, bytes_avail); if (r < ARCHIVE_WARN) return (r); if ((p = __archive_read_ahead(a, 32, &bytes_avail)) == NULL) return (ARCHIVE_FATAL); } zip->seek_base += 32; if (memcmp(p, _7ZIP_SIGNATURE, 6) != 0) { archive_set_error(&a->archive, -1, "Not 7-Zip archive file"); return (ARCHIVE_FATAL); } /* CRC check. */ if (crc32(0, (const unsigned char *)p + 12, 20) != archive_le32dec(p + 8)) { archive_set_error(&a->archive, -1, "Header CRC error"); return (ARCHIVE_FATAL); } next_header_offset = archive_le64dec(p + 12); next_header_size = archive_le64dec(p + 20); next_header_crc = archive_le32dec(p + 28); if (next_header_size == 0) /* There is no entry in an archive file. */ return (ARCHIVE_EOF); if (((int64_t)next_header_offset) < 0) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 32); if (next_header_offset != 0) { if (bytes_avail >= (ssize_t)next_header_offset) __archive_read_consume(a, next_header_offset); else if (__archive_read_seek(a, next_header_offset + zip->seek_base, SEEK_SET) < 0) return (ARCHIVE_FATAL); } zip->stream_offset = next_header_offset; zip->header_offset = next_header_offset; zip->header_bytes_remaining = next_header_size; zip->header_crc32 = 0; zip->header_is_encoded = 0; zip->header_is_being_read = 1; zip->has_encrypted_entries = 0; check_header_crc = 1; if ((p = header_bytes(a, 1)) == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } /* Parse ArchiveProperties. */ switch (p[0]) { case kEncodedHeader: /* * The archive has an encoded header and we have to decode it * in order to parse the header correctly. */ r = decode_encoded_header_info(a, &(zip->si)); /* Check the EncodedHeader CRC.*/ if (r == 0 && zip->header_crc32 != next_header_crc) { archive_set_error(&a->archive, -1, "Damaged 7-Zip archive"); r = -1; } if (r == 0) { if (zip->si.ci.folders[0].digest_defined) next_header_crc = zip->si.ci.folders[0].digest; else check_header_crc = 0; if (zip->pack_stream_bytes_unconsumed) read_consume(a); r = setup_decode_folder(a, zip->si.ci.folders, 1); if (r == 0) { zip->header_bytes_remaining = zip->folder_outbytes_remaining; r = seek_pack(a); } } /* Clean up StreamsInfo. */ free_StreamsInfo(&(zip->si)); memset(&(zip->si), 0, sizeof(zip->si)); if (r < 0) return (ARCHIVE_FATAL); zip->header_is_encoded = 1; zip->header_crc32 = 0; /* FALL THROUGH */ case kHeader: /* * Parse the header. */ errno = 0; r = read_Header(a, header, zip->header_is_encoded); if (r < 0) { if (errno == ENOMEM) archive_set_error(&a->archive, -1, "Couldn't allocate memory"); else archive_set_error(&a->archive, -1, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } /* * Must be kEnd. */ if ((p = header_bytes(a, 1)) == NULL ||*p != kEnd) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } /* Check the Header CRC.*/ if (check_header_crc && zip->header_crc32 != next_header_crc) { archive_set_error(&a->archive, -1, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } break; default: archive_set_error(&a->archive, -1, "Unexpected Property ID = %X", p[0]); return (ARCHIVE_FATAL); } /* Clean up variables be used for decoding the archive header */ zip->pack_stream_remaining = 0; zip->pack_stream_index = 0; zip->folder_outbytes_remaining = 0; zip->uncompressed_buffer_bytes_remaining = 0; zip->pack_stream_bytes_unconsumed = 0; zip->header_is_being_read = 0; return (ARCHIVE_OK); } static ssize_t get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { /* Copy mode. */ /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ *buff = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file data"); return (ARCHIVE_FATAL); } if ((size_t)bytes_avail > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; if ((size_t)bytes_avail > size) bytes_avail = (ssize_t)size; zip->pack_stream_bytes_unconsumed = bytes_avail; } else if (zip->uncompressed_buffer_pointer == NULL) { /* Decompression has failed. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } else { /* Packed mode. */ if (minimum > zip->uncompressed_buffer_bytes_remaining) { /* * If remaining uncompressed data size is less than * the minimum size, fill the buffer up to the * minimum size. */ if (extract_pack_stream(a, minimum) < 0) return (ARCHIVE_FATAL); } if (size > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; else bytes_avail = (ssize_t)size; *buff = zip->uncompressed_buffer_pointer; zip->uncompressed_buffer_pointer += bytes_avail; } zip->uncompressed_buffer_bytes_remaining -= bytes_avail; return (bytes_avail); } static ssize_t extract_pack_stream(struct archive_read *a, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; int r; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { if (minimum == 0) minimum = 1; if (__archive_read_ahead(a, minimum, &bytes_avail) == NULL || bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } if (bytes_avail > (ssize_t)zip->pack_stream_inbytes_remaining) bytes_avail = (ssize_t)zip->pack_stream_inbytes_remaining; zip->pack_stream_inbytes_remaining -= bytes_avail; if (bytes_avail > (ssize_t)zip->folder_outbytes_remaining) bytes_avail = (ssize_t)zip->folder_outbytes_remaining; zip->folder_outbytes_remaining -= bytes_avail; zip->uncompressed_buffer_bytes_remaining = bytes_avail; return (ARCHIVE_OK); } /* If the buffer hasn't been allocated, allocate it now. */ if (zip->uncompressed_buffer == NULL) { zip->uncompressed_buffer_size = UBUFF_SIZE; if (zip->uncompressed_buffer_size < minimum) { zip->uncompressed_buffer_size = minimum + 1023; zip->uncompressed_buffer_size &= ~0x3ff; } zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size); if (zip->uncompressed_buffer == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer_bytes_remaining = 0; } else if (zip->uncompressed_buffer_size < minimum || zip->uncompressed_buffer_bytes_remaining < minimum) { /* * Make sure the uncompressed buffer can have bytes * at least `minimum' bytes. * NOTE: This case happen when reading the header. */ size_t used; if (zip->uncompressed_buffer_pointer != 0) used = zip->uncompressed_buffer_pointer - zip->uncompressed_buffer; else used = 0; if (zip->uncompressed_buffer_size < minimum) { /* * Expand the uncompressed buffer up to * the minimum size. */ void *p; size_t new_size; new_size = minimum + 1023; new_size &= ~0x3ff; p = realloc(zip->uncompressed_buffer, new_size); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer = (unsigned char *)p; zip->uncompressed_buffer_size = new_size; } /* * Move unconsumed bytes to the head. */ if (used) { memmove(zip->uncompressed_buffer, zip->uncompressed_buffer + used, zip->uncompressed_buffer_bytes_remaining); } } else zip->uncompressed_buffer_bytes_remaining = 0; zip->uncompressed_buffer_pointer = NULL; for (;;) { size_t bytes_in, bytes_out; const void *buff_in; unsigned char *buff_out; int end_of_data; /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ buff_in = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } buff_out = zip->uncompressed_buffer + zip->uncompressed_buffer_bytes_remaining; bytes_out = zip->uncompressed_buffer_size - zip->uncompressed_buffer_bytes_remaining; bytes_in = bytes_avail; if (bytes_in > zip->pack_stream_inbytes_remaining) bytes_in = (size_t)zip->pack_stream_inbytes_remaining; /* Drive decompression. */ r = decompress(a, zip, buff_out, &bytes_out, buff_in, &bytes_in); switch (r) { case ARCHIVE_OK: end_of_data = 0; break; case ARCHIVE_EOF: end_of_data = 1; break; default: return (ARCHIVE_FATAL); } zip->pack_stream_inbytes_remaining -= bytes_in; if (bytes_out > zip->folder_outbytes_remaining) bytes_out = (size_t)zip->folder_outbytes_remaining; zip->folder_outbytes_remaining -= bytes_out; zip->uncompressed_buffer_bytes_remaining += bytes_out; zip->pack_stream_bytes_unconsumed = bytes_in; /* * Continue decompression until uncompressed_buffer is full. */ if (zip->uncompressed_buffer_bytes_remaining == zip->uncompressed_buffer_size) break; if (zip->codec2 == _7Z_X86 && zip->odd_bcj_size && zip->uncompressed_buffer_bytes_remaining + 5 > zip->uncompressed_buffer_size) break; if (zip->pack_stream_inbytes_remaining == 0 && zip->folder_outbytes_remaining == 0) break; if (end_of_data || (bytes_in == 0 && bytes_out == 0)) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } read_consume(a); } if (zip->uncompressed_buffer_bytes_remaining < minimum) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } zip->uncompressed_buffer_pointer = zip->uncompressed_buffer; return (ARCHIVE_OK); } static int seek_pack(struct archive_read *a) { struct _7zip *zip = (struct _7zip *)a->format->data; int64_t pack_offset; if (zip->pack_stream_remaining <= 0) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } zip->pack_stream_inbytes_remaining = zip->si.pi.sizes[zip->pack_stream_index]; pack_offset = zip->si.pi.positions[zip->pack_stream_index]; if (zip->stream_offset != pack_offset) { if (0 > __archive_read_seek(a, pack_offset + zip->seek_base, SEEK_SET)) return (ARCHIVE_FATAL); zip->stream_offset = pack_offset; } zip->pack_stream_index++; zip->pack_stream_remaining--; return (ARCHIVE_OK); } static ssize_t read_stream(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; uint64_t skip_bytes = 0; ssize_t r; if (zip->uncompressed_buffer_bytes_remaining == 0) { if (zip->pack_stream_inbytes_remaining > 0) { r = extract_pack_stream(a, 0); if (r < 0) return (r); return (get_uncompressed_data(a, buff, size, minimum)); } else if (zip->folder_outbytes_remaining > 0) { /* Extract a remaining pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); return (get_uncompressed_data(a, buff, size, minimum)); } } else return (get_uncompressed_data(a, buff, size, minimum)); /* * Current pack stream has been consumed. */ if (zip->pack_stream_remaining == 0) { if (zip->header_is_being_read) { /* Invalid sequence. This might happen when * reading a malformed archive. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Malformed 7-Zip archive"); return (ARCHIVE_FATAL); } /* * All current folder's pack streams have been * consumed. Switch to next folder. */ if (zip->folder_index == 0 && (zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes || zip->folder_index != zip->entry->folderIndex)) { zip->folder_index = zip->entry->folderIndex; skip_bytes = zip->si.ci.folders[zip->folder_index].skipped_bytes; } if (zip->folder_index >= zip->si.ci.numFolders) { /* * We have consumed all folders and its pack streams. */ *buff = NULL; return (0); } r = setup_decode_folder(a, &(zip->si.ci.folders[zip->folder_index]), 0); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); zip->folder_index++; } /* * Switch to next pack stream. */ r = seek_pack(a); if (r < 0) return (r); /* Extract a new pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); /* * Skip the bytes we alrady has skipped in skip_stream(). */ while (skip_bytes) { ssize_t skipped; if (zip->uncompressed_buffer_bytes_remaining == 0) { if (zip->pack_stream_inbytes_remaining > 0) { r = extract_pack_stream(a, 0); if (r < 0) return (r); } else if (zip->folder_outbytes_remaining > 0) { /* Extract a remaining pack stream. */ r = extract_pack_stream(a, 0); if (r < 0) return (r); } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } } skipped = get_uncompressed_data( a, buff, (size_t)skip_bytes, 0); if (skipped < 0) return (skipped); skip_bytes -= skipped; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } return (get_uncompressed_data(a, buff, size, minimum)); } static int setup_decode_folder(struct archive_read *a, struct _7z_folder *folder, int header) { struct _7zip *zip = (struct _7zip *)a->format->data; const struct _7z_coder *coder1, *coder2; const char *cname = (header)?"archive header":"file content"; unsigned i; int r, found_bcj2 = 0; /* * Release the memory which the previous folder used for BCJ2. */ for (i = 0; i < 3; i++) { if (zip->sub_stream_buff[i] != NULL) free(zip->sub_stream_buff[i]); zip->sub_stream_buff[i] = NULL; } /* * Initialize a stream reader. */ zip->pack_stream_remaining = (unsigned)folder->numPackedStreams; zip->pack_stream_index = (unsigned)folder->packIndex; zip->folder_outbytes_remaining = folder_uncompressed_size(folder); zip->uncompressed_buffer_bytes_remaining = 0; /* * Check coder types. */ for (i = 0; i < folder->numCoders; i++) { switch(folder->coders[i].codec) { case _7Z_CRYPTO_MAIN_ZIP: case _7Z_CRYPTO_RAR_29: case _7Z_CRYPTO_AES_256_SHA_256: { /* For entry that is associated with this folder, mark it as encrypted (data+metadata). */ zip->has_encrypted_entries = 1; if (a->entry) { archive_entry_set_is_data_encrypted(a->entry, 1); archive_entry_set_is_metadata_encrypted(a->entry, 1); } archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "The %s is encrypted, " "but currently not supported", cname); return (ARCHIVE_FATAL); } case _7Z_X86_BCJ2: { found_bcj2++; break; } } } /* Now that we've checked for encryption, if there were still no * encrypted entries found we can say for sure that there are none. */ if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { zip->has_encrypted_entries = 0; } if ((folder->numCoders > 2 && !found_bcj2) || found_bcj2 > 1) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "The %s is encoded with many filters, " "but currently not supported", cname); return (ARCHIVE_FATAL); } coder1 = &(folder->coders[0]); if (folder->numCoders == 2) coder2 = &(folder->coders[1]); else coder2 = NULL; if (found_bcj2) { /* * Preparation to decode BCJ2. * Decoding BCJ2 requires four sources. Those are at least, * as far as I know, two types of the storage form. */ const struct _7z_coder *fc = folder->coders; static const struct _7z_coder coder_copy = {0, 1, 1, 0, NULL}; const struct _7z_coder *scoder[3] = {&coder_copy, &coder_copy, &coder_copy}; const void *buff; ssize_t bytes; unsigned char *b[3] = {NULL, NULL, NULL}; uint64_t sunpack[3] ={-1, -1, -1}; size_t s[3] = {0, 0, 0}; int idx[3] = {0, 1, 2}; if (folder->numCoders == 4 && fc[3].codec == _7Z_X86_BCJ2 && folder->numInStreams == 7 && folder->numOutStreams == 4 && zip->pack_stream_remaining == 4) { /* Source type 1 made by 7zr or 7z with -m options. */ if (folder->bindPairs[0].inIndex == 5) { /* The form made by 7zr */ idx[0] = 1; idx[1] = 2; idx[2] = 0; scoder[1] = &(fc[1]); scoder[2] = &(fc[0]); sunpack[1] = folder->unPackSize[1]; sunpack[2] = folder->unPackSize[0]; coder1 = &(fc[2]); } else { /* * NOTE: Some patterns do not work. * work: * 7z a -m0=BCJ2 -m1=COPY -m2=COPY * -m3=(any) * 7z a -m0=BCJ2 -m1=COPY -m2=(any) * -m3=COPY * 7z a -m0=BCJ2 -m1=(any) -m2=COPY * -m3=COPY * not work: * other patterns. * * We have to handle this like `pipe' or * our libarchive7s filter frame work, * decoding the BCJ2 main stream sequentially, * m3 -> m2 -> m1 -> BCJ2. * */ if (fc[0].codec == _7Z_COPY && fc[1].codec == _7Z_COPY) coder1 = &(folder->coders[2]); else if (fc[0].codec == _7Z_COPY && fc[2].codec == _7Z_COPY) coder1 = &(folder->coders[1]); else if (fc[1].codec == _7Z_COPY && fc[2].codec == _7Z_COPY) coder1 = &(folder->coders[0]); else { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unsupported form of " "BCJ2 streams"); return (ARCHIVE_FATAL); } } coder2 = &(fc[3]); zip->main_stream_bytes_remaining = (size_t)folder->unPackSize[2]; } else if (coder2 != NULL && coder2->codec == _7Z_X86_BCJ2 && zip->pack_stream_remaining == 4 && folder->numInStreams == 5 && folder->numOutStreams == 2) { /* Source type 0 made by 7z */ zip->main_stream_bytes_remaining = (size_t)folder->unPackSize[0]; } else { /* We got an unexpected form. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unsupported form of BCJ2 streams"); return (ARCHIVE_FATAL); } /* Skip the main stream at this time. */ if ((r = seek_pack(a)) < 0) return (r); zip->pack_stream_bytes_unconsumed = (size_t)zip->pack_stream_inbytes_remaining; read_consume(a); /* Read following three sub streams. */ for (i = 0; i < 3; i++) { const struct _7z_coder *coder = scoder[i]; if ((r = seek_pack(a)) < 0) { free(b[0]); free(b[1]); free(b[2]); return (r); } if (sunpack[i] == (uint64_t)-1) zip->folder_outbytes_remaining = zip->pack_stream_inbytes_remaining; else zip->folder_outbytes_remaining = sunpack[i]; r = init_decompression(a, zip, coder, NULL); if (r != ARCHIVE_OK) { free(b[0]); free(b[1]); free(b[2]); return (ARCHIVE_FATAL); } /* Allocate memory for the decorded data of a sub * stream. */ b[i] = malloc((size_t)zip->folder_outbytes_remaining); if (b[i] == NULL) { free(b[0]); free(b[1]); free(b[2]); archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } /* Extract a sub stream. */ while (zip->pack_stream_inbytes_remaining > 0) { r = (int)extract_pack_stream(a, 0); if (r < 0) { free(b[0]); free(b[1]); free(b[2]); return (r); } bytes = get_uncompressed_data(a, &buff, zip->uncompressed_buffer_bytes_remaining, 0); if (bytes < 0) { free(b[0]); free(b[1]); free(b[2]); return ((int)bytes); } memcpy(b[i]+s[i], buff, bytes); s[i] += bytes; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } } /* Set the sub streams to the right place. */ for (i = 0; i < 3; i++) { zip->sub_stream_buff[i] = b[idx[i]]; zip->sub_stream_size[i] = s[idx[i]]; zip->sub_stream_bytes_remaining[i] = s[idx[i]]; } /* Allocate memory used for decoded main stream bytes. */ if (zip->tmp_stream_buff == NULL) { zip->tmp_stream_buff_size = 32 * 1024; zip->tmp_stream_buff = malloc(zip->tmp_stream_buff_size); if (zip->tmp_stream_buff == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for 7-Zip decompression"); return (ARCHIVE_FATAL); } } zip->tmp_stream_bytes_avail = 0; zip->tmp_stream_bytes_remaining = 0; zip->odd_bcj_size = 0; zip->bcj2_outPos = 0; /* * Reset a stream reader in order to read the main stream * of BCJ2. */ zip->pack_stream_remaining = 1; zip->pack_stream_index = (unsigned)folder->packIndex; zip->folder_outbytes_remaining = folder_uncompressed_size(folder); zip->uncompressed_buffer_bytes_remaining = 0; } /* * Initialize the decompressor for the new folder's pack streams. */ r = init_decompression(a, zip, coder1, coder2); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } static int64_t skip_stream(struct archive_read *a, size_t skip_bytes) { struct _7zip *zip = (struct _7zip *)a->format->data; const void *p; int64_t skipped_bytes; size_t bytes = skip_bytes; if (zip->folder_index == 0) { /* * Optimization for a list mode. * Avoid unncecessary decoding operations. */ zip->si.ci.folders[zip->entry->folderIndex].skipped_bytes += skip_bytes; return (skip_bytes); } while (bytes) { skipped_bytes = read_stream(a, &p, bytes, 0); if (skipped_bytes < 0) return (skipped_bytes); if (skipped_bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file body"); return (ARCHIVE_FATAL); } bytes -= (size_t)skipped_bytes; if (zip->pack_stream_bytes_unconsumed) read_consume(a); } return (skip_bytes); } /* * Brought from LZMA SDK. * * Bra86.c -- Converter for x86 code (BCJ) * 2008-10-04 : Igor Pavlov : Public domain * */ #define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) static void x86_Init(struct _7zip *zip) { zip->bcj_state = 0; zip->bcj_prevPosT = (size_t)0 - 1; zip->bcj_prevMask = 0; zip->bcj_ip = 5; } static size_t x86_Convert(struct _7zip *zip, uint8_t *data, size_t size) { static const uint8_t kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; static const uint8_t kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; size_t bufferPos, prevPosT; uint32_t ip, prevMask; if (size < 5) return 0; bufferPos = 0; prevPosT = zip->bcj_prevPosT; prevMask = zip->bcj_prevMask; ip = zip->bcj_ip; for (;;) { uint8_t *p = data + bufferPos; uint8_t *limit = data + size - 4; for (; p < limit; p++) if ((*p & 0xFE) == 0xE8) break; bufferPos = (size_t)(p - data); if (p >= limit) break; prevPosT = bufferPos - prevPosT; if (prevPosT > 3) prevMask = 0; else { prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; if (prevMask != 0) { unsigned char b = p[4 - kMaskToBitNumber[prevMask]]; if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) { prevPosT = bufferPos; prevMask = ((prevMask << 1) & 0x7) | 1; bufferPos++; continue; } } } prevPosT = bufferPos; if (Test86MSByte(p[4])) { uint32_t src = ((uint32_t)p[4] << 24) | ((uint32_t)p[3] << 16) | ((uint32_t)p[2] << 8) | ((uint32_t)p[1]); uint32_t dest; for (;;) { uint8_t b; int b_index; dest = src - (ip + (uint32_t)bufferPos); if (prevMask == 0) break; b_index = kMaskToBitNumber[prevMask] * 8; b = (uint8_t)(dest >> (24 - b_index)); if (!Test86MSByte(b)) break; src = dest ^ ((1 << (32 - b_index)) - 1); } p[4] = (uint8_t)(~(((dest >> 24) & 1) - 1)); p[3] = (uint8_t)(dest >> 16); p[2] = (uint8_t)(dest >> 8); p[1] = (uint8_t)dest; bufferPos += 5; } else { prevMask = ((prevMask << 1) & 0x7) | 1; bufferPos++; } } zip->bcj_prevPosT = prevPosT; zip->bcj_prevMask = prevMask; zip->bcj_ip += (uint32_t)bufferPos; return (bufferPos); } /* * Brought from LZMA SDK. * * Bcj2.c -- Converter for x86 code (BCJ2) * 2008-10-04 : Igor Pavlov : Public domain * */ #define SZ_ERROR_DATA ARCHIVE_FAILED #define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80) #define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)) #define kNumTopBits 24 #define kTopValue ((uint32_t)1 << kNumTopBits) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 #define RC_READ_BYTE (*buffer++) #define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; } #define RC_INIT2 zip->bcj2_code = 0; zip->bcj2_range = 0xFFFFFFFF; \ { int ii; for (ii = 0; ii < 5; ii++) { RC_TEST; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; }} #define NORMALIZE if (zip->bcj2_range < kTopValue) { RC_TEST; zip->bcj2_range <<= 8; zip->bcj2_code = (zip->bcj2_code << 8) | RC_READ_BYTE; } #define IF_BIT_0(p) ttt = *(p); bound = (zip->bcj2_range >> kNumBitModelTotalBits) * ttt; if (zip->bcj2_code < bound) #define UPDATE_0(p) zip->bcj2_range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE; #define UPDATE_1(p) zip->bcj2_range -= bound; zip->bcj2_code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE; static ssize_t Bcj2_Decode(struct _7zip *zip, uint8_t *outBuf, size_t outSize) { size_t inPos = 0, outPos = 0; const uint8_t *buf0, *buf1, *buf2, *buf3; size_t size0, size1, size2, size3; const uint8_t *buffer, *bufferLim; unsigned int i, j; size0 = zip->tmp_stream_bytes_remaining; buf0 = zip->tmp_stream_buff + zip->tmp_stream_bytes_avail - size0; size1 = zip->sub_stream_bytes_remaining[0]; buf1 = zip->sub_stream_buff[0] + zip->sub_stream_size[0] - size1; size2 = zip->sub_stream_bytes_remaining[1]; buf2 = zip->sub_stream_buff[1] + zip->sub_stream_size[1] - size2; size3 = zip->sub_stream_bytes_remaining[2]; buf3 = zip->sub_stream_buff[2] + zip->sub_stream_size[2] - size3; buffer = buf3; bufferLim = buffer + size3; if (zip->bcj_state == 0) { /* * Initialize. */ zip->bcj2_prevByte = 0; for (i = 0; i < sizeof(zip->bcj2_p) / sizeof(zip->bcj2_p[0]); i++) zip->bcj2_p[i] = kBitModelTotal >> 1; RC_INIT2; zip->bcj_state = 1; } /* * Gather the odd bytes of a previous call. */ for (i = 0; zip->odd_bcj_size > 0 && outPos < outSize; i++) { outBuf[outPos++] = zip->odd_bcj[i]; zip->odd_bcj_size--; } if (outSize == 0) { zip->bcj2_outPos += outPos; return (outPos); } for (;;) { uint8_t b; CProb *prob; uint32_t bound; uint32_t ttt; size_t limit = size0 - inPos; if (outSize - outPos < limit) limit = outSize - outPos; if (zip->bcj_state == 1) { while (limit != 0) { uint8_t bb = buf0[inPos]; outBuf[outPos++] = bb; if (IsJ(zip->bcj2_prevByte, bb)) { zip->bcj_state = 2; break; } inPos++; zip->bcj2_prevByte = bb; limit--; } } if (limit == 0 || outPos == outSize) break; zip->bcj_state = 1; b = buf0[inPos++]; if (b == 0xE8) prob = zip->bcj2_p + zip->bcj2_prevByte; else if (b == 0xE9) prob = zip->bcj2_p + 256; else prob = zip->bcj2_p + 257; IF_BIT_0(prob) { UPDATE_0(prob) zip->bcj2_prevByte = b; } else { uint32_t dest; const uint8_t *v; uint8_t out[4]; UPDATE_1(prob) if (b == 0xE8) { v = buf1; if (size1 < 4) return SZ_ERROR_DATA; buf1 += 4; size1 -= 4; } else { v = buf2; if (size2 < 4) return SZ_ERROR_DATA; buf2 += 4; size2 -= 4; } dest = (((uint32_t)v[0] << 24) | ((uint32_t)v[1] << 16) | ((uint32_t)v[2] << 8) | ((uint32_t)v[3])) - ((uint32_t)zip->bcj2_outPos + (uint32_t)outPos + 4); out[0] = (uint8_t)dest; out[1] = (uint8_t)(dest >> 8); out[2] = (uint8_t)(dest >> 16); out[3] = zip->bcj2_prevByte = (uint8_t)(dest >> 24); for (i = 0; i < 4 && outPos < outSize; i++) outBuf[outPos++] = out[i]; if (i < 4) { /* * Save odd bytes which we could not add into * the output buffer because of out of space. */ zip->odd_bcj_size = 4 -i; for (; i < 4; i++) { j = i - 4 + (unsigned)zip->odd_bcj_size; zip->odd_bcj[j] = out[i]; } break; } } } zip->tmp_stream_bytes_remaining -= inPos; zip->sub_stream_bytes_remaining[0] = size1; zip->sub_stream_bytes_remaining[1] = size2; zip->sub_stream_bytes_remaining[2] = bufferLim - buffer; zip->bcj2_outPos += outPos; return ((ssize_t)outPos); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5362_0
crossvul-cpp_data_good_351_14
/* * ef-atr.c: Stuff for handling EF(GDO) * * Copyright (C) 2017 Frank Morgner <frankmorgner@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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "asn1.h" #include "internal.h" #include <stdlib.h> #include <string.h> static int sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len, unsigned char *iccsn, size_t *iccsn_len, unsigned char *chn, size_t *chn_len) { int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0; const unsigned char *p = gdo; size_t left = gdo_len; while (left >= 2) { unsigned int cla, tag; size_t tag_len; r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len); if (r != SC_SUCCESS) { if (r == SC_ERROR_ASN1_END_OF_CONTENTS) { /* not enough data */ r = SC_SUCCESS; } break; } if (p == NULL) { /* done parsing */ break; } if (cla == SC_ASN1_TAG_APPLICATION) { switch (tag) { case 0x1A: iccsn_found = 1; if (iccsn && iccsn_len) { memcpy(iccsn, p, MIN(tag_len, *iccsn_len)); *iccsn_len = MIN(tag_len, *iccsn_len); } break; case 0x1F20: chn_found = 1; if (chn && chn_len) { memcpy(chn, p, MIN(tag_len, *chn_len)); *chn_len = MIN(tag_len, *chn_len); } break; } } p += tag_len; left = gdo_len - (p - gdo); } if (!iccsn_found && iccsn_len) *iccsn_len = 0; if (!chn_found && chn_len) *chn_len = 0; return r; } int sc_parse_ef_gdo(struct sc_card *card, unsigned char *iccsn, size_t *iccsn_len, unsigned char *chn, size_t *chn_len) { struct sc_context *ctx; struct sc_path path; struct sc_file *file; unsigned char *gdo = NULL; size_t gdo_len = 0; int r; if (!card) return SC_ERROR_INVALID_ARGUMENTS; ctx = card->ctx; LOG_FUNC_CALLED(ctx); sc_format_path("3F002F02", &path); r = sc_select_file(card, &path, &file); LOG_TEST_GOTO_ERR(ctx, r, "Cannot select EF(GDO) file"); if (file->size) { gdo_len = file->size; } else { gdo_len = 64; } gdo = malloc(gdo_len); if (!gdo) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } r = sc_read_binary(card, 0, gdo, gdo_len, 0); LOG_TEST_GOTO_ERR(ctx, r, "Cannot read EF(GDO) file"); r = sc_parse_ef_gdo_content(gdo, r, iccsn, iccsn_len, chn, chn_len); err: sc_file_free(file); free(gdo); LOG_FUNC_RETURN(ctx, r); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_14
crossvul-cpp_data_good_260_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Internet Control Message Protocol (ICMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "udp.h" #include "ipproto.h" #include "mpls.h" /* * Interface Control Message Protocol Definitions. * Per RFC 792, September 1981. */ /* * Structure of an icmp header. */ struct icmp { uint8_t icmp_type; /* type of message, see below */ uint8_t icmp_code; /* type sub code */ uint16_t icmp_cksum; /* ones complement cksum of struct */ union { uint8_t ih_pptr; /* ICMP_PARAMPROB */ struct in_addr ih_gwaddr; /* ICMP_REDIRECT */ struct ih_idseq { uint16_t icd_id; uint16_t icd_seq; } ih_idseq; uint32_t ih_void; } icmp_hun; #define icmp_pptr icmp_hun.ih_pptr #define icmp_gwaddr icmp_hun.ih_gwaddr #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq #define icmp_void icmp_hun.ih_void union { struct id_ts { uint32_t its_otime; uint32_t its_rtime; uint32_t its_ttime; } id_ts; struct id_ip { struct ip idi_ip; /* options and then 64 bits of data */ } id_ip; uint32_t id_mask; uint8_t id_data[1]; } icmp_dun; #define icmp_otime icmp_dun.id_ts.its_otime #define icmp_rtime icmp_dun.id_ts.its_rtime #define icmp_ttime icmp_dun.id_ts.its_ttime #define icmp_ip icmp_dun.id_ip.idi_ip #define icmp_mask icmp_dun.id_mask #define icmp_data icmp_dun.id_data }; #define ICMP_MPLS_EXT_EXTRACT_VERSION(x) (((x)&0xf0)>>4) #define ICMP_MPLS_EXT_VERSION 2 /* * Lower bounds on packet lengths for various types. * For the error advice packets must first insure that the * packet is large enought to contain the returned ip header. * Only then can we do the check to see if 64 bits of packet * data have been returned, since we need to check the returned * ip header length. */ #define ICMP_MINLEN 8 /* abs minimum */ #define ICMP_EXTD_MINLEN (156 - sizeof (struct ip)) /* draft-bonica-internet-icmp-08 */ #define ICMP_TSLEN (8 + 3 * sizeof (uint32_t)) /* timestamp */ #define ICMP_MASKLEN 12 /* address mask */ #define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */ #define ICMP_ADVLEN(p) (8 + (IP_HL(&(p)->icmp_ip) << 2) + 8) /* N.B.: must separately check that ip_hl >= 5 */ /* * Definition of type and code field values. */ #define ICMP_ECHOREPLY 0 /* echo reply */ #define ICMP_UNREACH 3 /* dest unreachable, codes: */ #define ICMP_UNREACH_NET 0 /* bad net */ #define ICMP_UNREACH_HOST 1 /* bad host */ #define ICMP_UNREACH_PROTOCOL 2 /* bad protocol */ #define ICMP_UNREACH_PORT 3 /* bad port */ #define ICMP_UNREACH_NEEDFRAG 4 /* IP_DF caused drop */ #define ICMP_UNREACH_SRCFAIL 5 /* src route failed */ #define ICMP_UNREACH_NET_UNKNOWN 6 /* unknown net */ #define ICMP_UNREACH_HOST_UNKNOWN 7 /* unknown host */ #define ICMP_UNREACH_ISOLATED 8 /* src host isolated */ #define ICMP_UNREACH_NET_PROHIB 9 /* prohibited access */ #define ICMP_UNREACH_HOST_PROHIB 10 /* ditto */ #define ICMP_UNREACH_TOSNET 11 /* bad tos for net */ #define ICMP_UNREACH_TOSHOST 12 /* bad tos for host */ #define ICMP_SOURCEQUENCH 4 /* packet lost, slow down */ #define ICMP_REDIRECT 5 /* shorter route, codes: */ #define ICMP_REDIRECT_NET 0 /* for network */ #define ICMP_REDIRECT_HOST 1 /* for host */ #define ICMP_REDIRECT_TOSNET 2 /* for tos and net */ #define ICMP_REDIRECT_TOSHOST 3 /* for tos and host */ #define ICMP_ECHO 8 /* echo service */ #define ICMP_ROUTERADVERT 9 /* router advertisement */ #define ICMP_ROUTERSOLICIT 10 /* router solicitation */ #define ICMP_TIMXCEED 11 /* time exceeded, code: */ #define ICMP_TIMXCEED_INTRANS 0 /* ttl==0 in transit */ #define ICMP_TIMXCEED_REASS 1 /* ttl==0 in reass */ #define ICMP_PARAMPROB 12 /* ip header bad */ #define ICMP_PARAMPROB_OPTABSENT 1 /* req. opt. absent */ #define ICMP_TSTAMP 13 /* timestamp request */ #define ICMP_TSTAMPREPLY 14 /* timestamp reply */ #define ICMP_IREQ 15 /* information request */ #define ICMP_IREQREPLY 16 /* information reply */ #define ICMP_MASKREQ 17 /* address mask request */ #define ICMP_MASKREPLY 18 /* address mask reply */ #define ICMP_MAXTYPE 18 #define ICMP_ERRTYPE(type) \ ((type) == ICMP_UNREACH || (type) == ICMP_SOURCEQUENCH || \ (type) == ICMP_REDIRECT || (type) == ICMP_TIMXCEED || \ (type) == ICMP_PARAMPROB) #define ICMP_MPLS_EXT_TYPE(type) \ ((type) == ICMP_UNREACH || \ (type) == ICMP_TIMXCEED || \ (type) == ICMP_PARAMPROB) /* rfc1700 */ #ifndef ICMP_UNREACH_NET_UNKNOWN #define ICMP_UNREACH_NET_UNKNOWN 6 /* destination net unknown */ #endif #ifndef ICMP_UNREACH_HOST_UNKNOWN #define ICMP_UNREACH_HOST_UNKNOWN 7 /* destination host unknown */ #endif #ifndef ICMP_UNREACH_ISOLATED #define ICMP_UNREACH_ISOLATED 8 /* source host isolated */ #endif #ifndef ICMP_UNREACH_NET_PROHIB #define ICMP_UNREACH_NET_PROHIB 9 /* admin prohibited net */ #endif #ifndef ICMP_UNREACH_HOST_PROHIB #define ICMP_UNREACH_HOST_PROHIB 10 /* admin prohibited host */ #endif #ifndef ICMP_UNREACH_TOSNET #define ICMP_UNREACH_TOSNET 11 /* tos prohibited net */ #endif #ifndef ICMP_UNREACH_TOSHOST #define ICMP_UNREACH_TOSHOST 12 /* tos prohibited host */ #endif /* rfc1716 */ #ifndef ICMP_UNREACH_FILTER_PROHIB #define ICMP_UNREACH_FILTER_PROHIB 13 /* admin prohibited filter */ #endif #ifndef ICMP_UNREACH_HOST_PRECEDENCE #define ICMP_UNREACH_HOST_PRECEDENCE 14 /* host precedence violation */ #endif #ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF #define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 /* precedence cutoff */ #endif /* Most of the icmp types */ static const struct tok icmp2str[] = { { ICMP_ECHOREPLY, "echo reply" }, { ICMP_SOURCEQUENCH, "source quench" }, { ICMP_ECHO, "echo request" }, { ICMP_ROUTERSOLICIT, "router solicitation" }, { ICMP_TSTAMP, "time stamp request" }, { ICMP_TSTAMPREPLY, "time stamp reply" }, { ICMP_IREQ, "information request" }, { ICMP_IREQREPLY, "information reply" }, { ICMP_MASKREQ, "address mask request" }, { 0, NULL } }; /* Formats for most of the ICMP_UNREACH codes */ static const struct tok unreach2str[] = { { ICMP_UNREACH_NET, "net %s unreachable" }, { ICMP_UNREACH_HOST, "host %s unreachable" }, { ICMP_UNREACH_SRCFAIL, "%s unreachable - source route failed" }, { ICMP_UNREACH_NET_UNKNOWN, "net %s unreachable - unknown" }, { ICMP_UNREACH_HOST_UNKNOWN, "host %s unreachable - unknown" }, { ICMP_UNREACH_ISOLATED, "%s unreachable - source host isolated" }, { ICMP_UNREACH_NET_PROHIB, "net %s unreachable - admin prohibited" }, { ICMP_UNREACH_HOST_PROHIB, "host %s unreachable - admin prohibited" }, { ICMP_UNREACH_TOSNET, "net %s unreachable - tos prohibited" }, { ICMP_UNREACH_TOSHOST, "host %s unreachable - tos prohibited" }, { ICMP_UNREACH_FILTER_PROHIB, "host %s unreachable - admin prohibited filter" }, { ICMP_UNREACH_HOST_PRECEDENCE, "host %s unreachable - host precedence violation" }, { ICMP_UNREACH_PRECEDENCE_CUTOFF, "host %s unreachable - precedence cutoff" }, { 0, NULL } }; /* Formats for the ICMP_REDIRECT codes */ static const struct tok type2str[] = { { ICMP_REDIRECT_NET, "redirect %s to net %s" }, { ICMP_REDIRECT_HOST, "redirect %s to host %s" }, { ICMP_REDIRECT_TOSNET, "redirect-tos %s to net %s" }, { ICMP_REDIRECT_TOSHOST, "redirect-tos %s to host %s" }, { 0, NULL } }; /* rfc1191 */ struct mtu_discovery { uint16_t unused; uint16_t nexthopmtu; }; /* rfc1256 */ struct ih_rdiscovery { uint8_t ird_addrnum; uint8_t ird_addrsiz; uint16_t ird_lifetime; }; struct id_rdiscovery { uint32_t ird_addr; uint32_t ird_pref; }; /* * draft-bonica-internet-icmp-08 * * The Destination Unreachable, Time Exceeded * and Parameter Problem messages are slighly changed as per * the above draft. A new Length field gets added to give * the caller an idea about the length of the piggypacked * IP packet before the MPLS extension header starts. * * The Length field represents length of the padded "original datagram" * field measured in 32-bit words. * * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Code | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | unused | Length | unused | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Internet Header + leading octets of original datagram | * | | * | // | * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct icmp_ext_t { uint8_t icmp_type; uint8_t icmp_code; uint8_t icmp_checksum[2]; uint8_t icmp_reserved; uint8_t icmp_length; uint8_t icmp_reserved2[2]; uint8_t icmp_ext_legacy_header[128]; /* extension header starts 128 bytes after ICMP header */ uint8_t icmp_ext_version_res[2]; uint8_t icmp_ext_checksum[2]; uint8_t icmp_ext_data[1]; }; struct icmp_mpls_ext_object_header_t { uint8_t length[2]; uint8_t class_num; uint8_t ctype; }; static const struct tok icmp_mpls_ext_obj_values[] = { { 1, "MPLS Stack Entry" }, { 2, "Extended Payload" }, { 0, NULL} }; /* prototypes */ const char *icmp_tstamp_print(u_int); /* print the milliseconds since midnight UTC */ const char * icmp_tstamp_print(u_int tstamp) { u_int msec,sec,min,hrs; static char buf[64]; msec = tstamp % 1000; sec = tstamp / 1000; min = sec / 60; sec -= min * 60; hrs = min / 60; min -= hrs * 60; snprintf(buf, sizeof(buf), "%02u:%02u:%02u.%03u",hrs,min,sec,msec); return buf; } void icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, int fragmented) { char *cp; const struct icmp *dp; const struct icmp_ext_t *ext_dp; const struct ip *ip; const char *str, *fmt; const struct ip *oip; const struct udphdr *ouh; const uint8_t *obj_tptr; uint32_t raw_label; const u_char *snapend_save; const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; char buf[MAXHOSTNAMELEN + 100]; struct cksum_vec vec[1]; dp = (const struct icmp *)bp; ext_dp = (const struct icmp_ext_t *)bp; ip = (const struct ip *)bp2; str = buf; ND_TCHECK(dp->icmp_code); switch (dp->icmp_type) { case ICMP_ECHO: case ICMP_ECHOREPLY: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u", dp->icmp_type == ICMP_ECHO ? "request" : "reply", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_UNREACH: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_UNREACH_PROTOCOL: ND_TCHECK(dp->icmp_ip.ip_p); (void)snprintf(buf, sizeof(buf), "%s protocol %d unreachable", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), dp->icmp_ip.ip_p); break; case ICMP_UNREACH_PORT: ND_TCHECK(dp->icmp_ip.ip_p); oip = &dp->icmp_ip; hlen = IP_HL(oip) * 4; ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); ND_TCHECK(ouh->uh_dport); dport = EXTRACT_16BITS(&ouh->uh_dport); switch (oip->ip_p) { case IPPROTO_TCP: (void)snprintf(buf, sizeof(buf), "%s tcp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), tcpport_string(ndo, dport)); break; case IPPROTO_UDP: (void)snprintf(buf, sizeof(buf), "%s udp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), udpport_string(ndo, dport)); break; default: (void)snprintf(buf, sizeof(buf), "%s protocol %u port %u unreachable", ipaddr_string(ndo, &oip->ip_dst), oip->ip_p, dport); break; } break; case ICMP_UNREACH_NEEDFRAG: { register const struct mtu_discovery *mp; mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; mtu = EXTRACT_16BITS(&mp->nexthopmtu); if (mtu) { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag (mtu %d)", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); } else { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag", ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); } } break; default: fmt = tok2str(unreach2str, "#%d %%s unreachable", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); break; } break; case ICMP_REDIRECT: ND_TCHECK(dp->icmp_ip.ip_dst); fmt = tok2str(type2str, "redirect-#%d %%s to net %%s", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst), ipaddr_string(ndo, &dp->icmp_gwaddr)); break; case ICMP_ROUTERADVERT: { register const struct ih_rdiscovery *ihp; register const struct id_rdiscovery *idp; u_int lifetime, num, size; (void)snprintf(buf, sizeof(buf), "router advertisement"); cp = buf + strlen(buf); ihp = (const struct ih_rdiscovery *)&dp->icmp_void; ND_TCHECK(*ihp); (void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf)); cp = buf + strlen(buf); lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); if (lifetime < 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u", lifetime); } else if (lifetime < 60 * 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u", lifetime / 60, lifetime % 60); } else { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u:%02u", lifetime / 3600, (lifetime % 3600) / 60, lifetime % 60); } cp = buf + strlen(buf); num = ihp->ird_addrnum; (void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num); cp = buf + strlen(buf); size = ihp->ird_addrsiz; if (size != 2) { (void)snprintf(cp, sizeof(buf) - (cp - buf), " [size %d]", size); break; } idp = (const struct id_rdiscovery *)&dp->icmp_data; while (num-- > 0) { ND_TCHECK(*idp); (void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}", ipaddr_string(ndo, &idp->ird_addr), EXTRACT_32BITS(&idp->ird_pref)); cp = buf + strlen(buf); ++idp; } } break; case ICMP_TIMXCEED: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_TIMXCEED_INTRANS: str = "time exceeded in-transit"; break; case ICMP_TIMXCEED_REASS: str = "ip reassembly time exceeded"; break; default: (void)snprintf(buf, sizeof(buf), "time exceeded-#%u", dp->icmp_code); break; } break; case ICMP_PARAMPROB: if (dp->icmp_code) (void)snprintf(buf, sizeof(buf), "parameter problem - code %u", dp->icmp_code); else { ND_TCHECK(dp->icmp_pptr); (void)snprintf(buf, sizeof(buf), "parameter problem - octet %u", dp->icmp_pptr); } break; case ICMP_MASKREPLY: ND_TCHECK(dp->icmp_mask); (void)snprintf(buf, sizeof(buf), "address mask is 0x%08x", EXTRACT_32BITS(&dp->icmp_mask)); break; case ICMP_TSTAMP: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "time stamp query id %u seq %u", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_TSTAMPREPLY: ND_TCHECK(dp->icmp_ttime); (void)snprintf(buf, sizeof(buf), "time stamp reply id %u seq %u: org %s", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq), icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); break; default: str = tok2str(icmp2str, "type-#%d", dp->icmp_type); break; } ND_PRINT((ndo, "ICMP %s, length %u", str, plen)); if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ if (ND_TTEST2(*bp, plen)) { uint16_t sum; vec[0].ptr = (const uint8_t *)(const void *)dp; vec[0].len = plen; sum = in_cksum(vec, 1); if (sum != 0) { ND_TCHECK_16BITS(&dp->icmp_cksum); uint16_t icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)", icmp_sum, in_cksum_shouldbe(icmp_sum, sum))); } } } /* * print the remnants of the IP packet. * save the snaplength as this may get overidden in the IP printer. */ if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { bp += 8; ND_PRINT((ndo, "\n\t")); ip = (const struct ip *)bp; ndo->ndo_snaplen = ndo->ndo_snapend - bp; snapend_save = ndo->ndo_snapend; ND_TCHECK_16BITS(&ip->ip_len); ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); ndo->ndo_snapend = snapend_save; } /* * Attempt to decode the MPLS extensions only for some ICMP types. */ if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { ND_TCHECK(*ext_dp); /* * Check first if the mpls extension header shows a non-zero length. * If the length field is not set then silently verify the checksum * to check if an extension header is present. This is expedient, * however not all implementations set the length field proper. */ if (!ext_dp->icmp_length && ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = plen - ICMP_EXTD_MINLEN; if (in_cksum(vec, 1)) { return; } } ND_PRINT((ndo, "\n\tMPLS extension v%u", ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); /* * Sanity checking of the header. */ if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != ICMP_MPLS_EXT_VERSION) { ND_PRINT((ndo, " packet not supported")); return; } hlen = plen - ICMP_EXTD_MINLEN; if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = hlen; ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u", EXTRACT_16BITS(ext_dp->icmp_ext_checksum), in_cksum(vec, 1) ? "in" : "", hlen)); } hlen -= 4; /* subtract common header size */ obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; ND_TCHECK(*icmp_mpls_ext_object_header); obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); obj_class_num = icmp_mpls_ext_object_header->class_num; obj_ctype = icmp_mpls_ext_object_header->ctype; obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u", tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num), obj_class_num, obj_ctype, obj_tlen)); hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ /* infinite loop protection */ if ((obj_class_num == 0) || (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { return; } obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); switch (obj_class_num) { case 1: switch(obj_ctype) { case 1: ND_TCHECK2(*obj_tptr, 4); raw_label = EXTRACT_32BITS(obj_tptr); ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); if (MPLS_STACK(raw_label)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label))); break; default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case 2: default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); break; } if (hlen < obj_tlen) break; hlen -= obj_tlen; obj_tptr += obj_tlen; } } return; trunc: ND_PRINT((ndo, "[|icmp]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_260_0
crossvul-cpp_data_good_486_7
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. RDP order processing Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008 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 "rdesktop.h" #include "orders.h" extern uint8 *g_next_packet; static RDP_ORDER_STATE g_order_state; extern RDP_VERSION g_rdp_version; /* Read field indicating which parameters are present */ static void rdp_in_present(STREAM s, uint32 * present, uint8 flags, int size) { uint8 bits; int i; if (flags & RDP_ORDER_SMALL) { size--; } if (flags & RDP_ORDER_TINY) { if (size < 2) size = 0; else size -= 2; } *present = 0; for (i = 0; i < size; i++) { in_uint8(s, bits); *present |= bits << (i * 8); } } /* Read a co-ordinate (16-bit, or 8-bit delta) */ static void rdp_in_coord(STREAM s, sint16 * coord, RD_BOOL delta) { sint8 change; if (delta) { in_uint8(s, change); *coord += change; } else { in_uint16_le(s, *coord); } } /* Parse a delta co-ordinate in polyline/polygon order form */ static int parse_delta(uint8 * buffer, int *offset) { int value = buffer[(*offset)++]; int two_byte = value & 0x80; if (value & 0x40) /* sign bit */ value |= ~0x3f; else value &= 0x3f; if (two_byte) value = (value << 8) | buffer[(*offset)++]; return value; } /* Read a colour entry */ static void rdp_in_colour(STREAM s, uint32 * colour) { uint32 i; in_uint8(s, i); *colour = i; in_uint8(s, i); *colour |= i << 8; in_uint8(s, i); *colour |= i << 16; } /* Parse bounds information */ static RD_BOOL rdp_parse_bounds(STREAM s, BOUNDS * bounds) { uint8 present; in_uint8(s, present); if (present & 1) rdp_in_coord(s, &bounds->left, False); else if (present & 16) rdp_in_coord(s, &bounds->left, True); if (present & 2) rdp_in_coord(s, &bounds->top, False); else if (present & 32) rdp_in_coord(s, &bounds->top, True); if (present & 4) rdp_in_coord(s, &bounds->right, False); else if (present & 64) rdp_in_coord(s, &bounds->right, True); if (present & 8) rdp_in_coord(s, &bounds->bottom, False); else if (present & 128) rdp_in_coord(s, &bounds->bottom, True); return s_check(s); } /* Parse a pen */ static RD_BOOL rdp_parse_pen(STREAM s, PEN * pen, uint32 present) { if (present & 1) in_uint8(s, pen->style); if (present & 2) in_uint8(s, pen->width); if (present & 4) rdp_in_colour(s, &pen->colour); return s_check(s); } static void setup_brush(BRUSH * out_brush, BRUSH * in_brush) { BRUSHDATA *brush_data; uint8 cache_idx; uint8 colour_code; memcpy(out_brush, in_brush, sizeof(BRUSH)); if (out_brush->style & 0x80) { colour_code = out_brush->style & 0x0f; cache_idx = out_brush->pattern[0]; brush_data = cache_get_brush_data(colour_code, cache_idx); if ((brush_data == NULL) || (brush_data->data == NULL)) { logger(Graphics, Error, "setup_brush(), error getting brush data, style %x", out_brush->style); out_brush->bd = NULL; memset(out_brush->pattern, 0, 8); } else { out_brush->bd = brush_data; } out_brush->style = 3; } } /* Parse a brush */ static RD_BOOL rdp_parse_brush(STREAM s, BRUSH * brush, uint32 present) { if (present & 1) in_uint8(s, brush->xorigin); if (present & 2) in_uint8(s, brush->yorigin); if (present & 4) in_uint8(s, brush->style); if (present & 8) in_uint8(s, brush->pattern[0]); if (present & 16) in_uint8a(s, &brush->pattern[1], 7); return s_check(s); } /* Process a destination blt order */ static void process_destblt(STREAM s, DESTBLT_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) rdp_in_coord(s, &os->cx, delta); if (present & 0x08) rdp_in_coord(s, &os->cy, delta); if (present & 0x10) in_uint8(s, os->opcode); logger(Graphics, Debug, "process_destblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d", os->opcode, os->x, os->y, os->cx, os->cy); ui_destblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy); } /* Process a pattern blt order */ static void process_patblt(STREAM s, PATBLT_ORDER * os, uint32 present, RD_BOOL delta) { BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) rdp_in_coord(s, &os->cx, delta); if (present & 0x0008) rdp_in_coord(s, &os->cy, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) rdp_in_colour(s, &os->bgcolour); if (present & 0x0040) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 7); logger(Graphics, Debug, "process_patblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, bs=%d, bg=0x%x, fg=0x%x)", os->opcode, os->x, os->y, os->cx, os->cy, os->brush.style, os->bgcolour, os->fgcolour); setup_brush(&brush, &os->brush); ui_patblt(ROP2_P(os->opcode), os->x, os->y, os->cx, os->cy, &brush, os->bgcolour, os->fgcolour); } /* Process a screen blt order */ static void process_screenblt(STREAM s, SCREENBLT_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) rdp_in_coord(s, &os->cx, delta); if (present & 0x0008) rdp_in_coord(s, &os->cy, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) rdp_in_coord(s, &os->srcx, delta); if (present & 0x0040) rdp_in_coord(s, &os->srcy, delta); logger(Graphics, Debug, "process_screenblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, srcx=%d, srcy=%d)", os->opcode, os->x, os->y, os->cx, os->cy, os->srcx, os->srcy); ui_screenblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy, os->srcx, os->srcy); } /* Process a line order */ static void process_line(STREAM s, LINE_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x0001) in_uint16_le(s, os->mixmode); if (present & 0x0002) rdp_in_coord(s, &os->startx, delta); if (present & 0x0004) rdp_in_coord(s, &os->starty, delta); if (present & 0x0008) rdp_in_coord(s, &os->endx, delta); if (present & 0x0010) rdp_in_coord(s, &os->endy, delta); if (present & 0x0020) rdp_in_colour(s, &os->bgcolour); if (present & 0x0040) in_uint8(s, os->opcode); rdp_parse_pen(s, &os->pen, present >> 7); logger(Graphics, Debug, "process_line(), op=0x%x, sx=%d, sy=%d, dx=%d, dy=%d, fg=0x%x)", os->opcode, os->startx, os->starty, os->endx, os->endy, os->pen.colour); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_line(), bad ROP2 0x%x", os->opcode); return; } ui_line(os->opcode - 1, os->startx, os->starty, os->endx, os->endy, &os->pen); } /* Process an opaque rectangle order */ static void process_rect(STREAM s, RECT_ORDER * os, uint32 present, RD_BOOL delta) { uint32 i; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) rdp_in_coord(s, &os->cx, delta); if (present & 0x08) rdp_in_coord(s, &os->cy, delta); if (present & 0x10) { in_uint8(s, i); os->colour = (os->colour & 0xffffff00) | i; } if (present & 0x20) { in_uint8(s, i); os->colour = (os->colour & 0xffff00ff) | (i << 8); } if (present & 0x40) { in_uint8(s, i); os->colour = (os->colour & 0xff00ffff) | (i << 16); } logger(Graphics, Debug, "process_rect(), x=%d, y=%d, cx=%d, cy=%d, fg=0x%x", os->x, os->y, os->cx, os->cy, os->colour); ui_rect(os->x, os->y, os->cx, os->cy, os->colour); } /* Process a desktop save order */ static void process_desksave(STREAM s, DESKSAVE_ORDER * os, uint32 present, RD_BOOL delta) { int width, height; if (present & 0x01) in_uint32_le(s, os->offset); if (present & 0x02) rdp_in_coord(s, &os->left, delta); if (present & 0x04) rdp_in_coord(s, &os->top, delta); if (present & 0x08) rdp_in_coord(s, &os->right, delta); if (present & 0x10) rdp_in_coord(s, &os->bottom, delta); if (present & 0x20) in_uint8(s, os->action); logger(Graphics, Debug, "process_desksave(), l=%d, t=%d, r=%d, b=%d, off=%d, op=%d", os->left, os->top, os->right, os->bottom, os->offset, os->action); width = os->right - os->left + 1; height = os->bottom - os->top + 1; if (os->action == 0) ui_desktop_save(os->offset, os->left, os->top, width, height); else ui_desktop_restore(os->offset, os->left, os->top, width, height); } /* Process a memory blt order */ static void process_memblt(STREAM s, MEMBLT_ORDER * os, uint32 present, RD_BOOL delta) { RD_HBITMAP bitmap; if (present & 0x0001) { in_uint8(s, os->cache_id); in_uint8(s, os->colour_table); } if (present & 0x0002) rdp_in_coord(s, &os->x, delta); if (present & 0x0004) rdp_in_coord(s, &os->y, delta); if (present & 0x0008) rdp_in_coord(s, &os->cx, delta); if (present & 0x0010) rdp_in_coord(s, &os->cy, delta); if (present & 0x0020) in_uint8(s, os->opcode); if (present & 0x0040) rdp_in_coord(s, &os->srcx, delta); if (present & 0x0080) rdp_in_coord(s, &os->srcy, delta); if (present & 0x0100) in_uint16_le(s, os->cache_idx); logger(Graphics, Debug, "process_memblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, id=%d, idx=%d", os->opcode, os->x, os->y, os->cx, os->cy, os->cache_id, os->cache_idx); bitmap = cache_get_bitmap(os->cache_id, os->cache_idx); if (bitmap == NULL) return; ui_memblt(ROP2_S(os->opcode), os->x, os->y, os->cx, os->cy, bitmap, os->srcx, os->srcy); } /* Process a 3-way blt order */ static void process_triblt(STREAM s, TRIBLT_ORDER * os, uint32 present, RD_BOOL delta) { RD_HBITMAP bitmap; BRUSH brush; if (present & 0x000001) { in_uint8(s, os->cache_id); in_uint8(s, os->colour_table); } if (present & 0x000002) rdp_in_coord(s, &os->x, delta); if (present & 0x000004) rdp_in_coord(s, &os->y, delta); if (present & 0x000008) rdp_in_coord(s, &os->cx, delta); if (present & 0x000010) rdp_in_coord(s, &os->cy, delta); if (present & 0x000020) in_uint8(s, os->opcode); if (present & 0x000040) rdp_in_coord(s, &os->srcx, delta); if (present & 0x000080) rdp_in_coord(s, &os->srcy, delta); if (present & 0x000100) rdp_in_colour(s, &os->bgcolour); if (present & 0x000200) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 10); if (present & 0x008000) in_uint16_le(s, os->cache_idx); if (present & 0x010000) in_uint16_le(s, os->unknown); logger(Graphics, Debug, "process_triblt(), op=0x%x, x=%d, y=%d, cx=%d, cy=%d, id=%d, idx=%d, bs=%d, bg=0x%x, fg=0x%x", os->opcode, os->x, os->y, os->cx, os->cy, os->cache_id, os->cache_idx, os->brush.style, os->bgcolour, os->fgcolour); bitmap = cache_get_bitmap(os->cache_id, os->cache_idx); if (bitmap == NULL) return; setup_brush(&brush, &os->brush); ui_triblt(os->opcode, os->x, os->y, os->cx, os->cy, bitmap, os->srcx, os->srcy, &brush, os->bgcolour, os->fgcolour); } /* Process a polygon order */ static void process_polygon(STREAM s, POLYGON_ORDER * os, uint32 present, RD_BOOL delta) { int index, data, next; uint8 flags = 0; RD_POINT *points; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) in_uint8(s, os->opcode); if (present & 0x08) in_uint8(s, os->fillmode); if (present & 0x10) rdp_in_colour(s, &os->fgcolour); if (present & 0x20) in_uint8(s, os->npoints); if (present & 0x40) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polygon(), x=%d, y=%d, op=0x%x, fm=%d, fg=0x%x, n=%d, sz=%d", os->x, os->y, os->opcode, os->fillmode, os->fgcolour, os->npoints, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polygon(), bad ROP2 0x%x", os->opcode); return; } points = (RD_POINT *) xmalloc((os->npoints + 1) * sizeof(RD_POINT)); memset(points, 0, (os->npoints + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; index = 0; data = ((os->npoints - 1) / 4) + 1; for (next = 1; (next <= os->npoints) && (next < 256) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->npoints) ui_polygon(os->opcode - 1, os->fillmode, points, os->npoints + 1, NULL, 0, os->fgcolour); else logger(Graphics, Error, "process_polygon(), polygon parse error"); xfree(points); } /* Process a polygon2 order */ static void process_polygon2(STREAM s, POLYGON2_ORDER * os, uint32 present, RD_BOOL delta) { int index, data, next; uint8 flags = 0; RD_POINT *points; BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->x, delta); if (present & 0x0002) rdp_in_coord(s, &os->y, delta); if (present & 0x0004) in_uint8(s, os->opcode); if (present & 0x0008) in_uint8(s, os->fillmode); if (present & 0x0010) rdp_in_colour(s, &os->bgcolour); if (present & 0x0020) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 6); if (present & 0x0800) in_uint8(s, os->npoints); if (present & 0x1000) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polygon2(), x=%d, y=%d, op=0x%x, fm=%d, bs=%d, bg=0x%x, fg=0x%x, n=%d, sz=%d)", os->x, os->y, os->opcode, os->fillmode, os->brush.style, os->bgcolour, os->fgcolour, os->npoints, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polygon2(), bad ROP2 0x%x", os->opcode); return; } setup_brush(&brush, &os->brush); points = (RD_POINT *) xmalloc((os->npoints + 1) * sizeof(RD_POINT)); memset(points, 0, (os->npoints + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; index = 0; data = ((os->npoints - 1) / 4) + 1; for (next = 1; (next <= os->npoints) && (next < 256) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->npoints) ui_polygon(os->opcode - 1, os->fillmode, points, os->npoints + 1, &brush, os->bgcolour, os->fgcolour); else logger(Graphics, Error, "process_polygon2(), polygon parse error"); xfree(points); } /* Process a polyline order */ static void process_polyline(STREAM s, POLYLINE_ORDER * os, uint32 present, RD_BOOL delta) { int index, next, data; uint8 flags = 0; PEN pen; RD_POINT *points; if (present & 0x01) rdp_in_coord(s, &os->x, delta); if (present & 0x02) rdp_in_coord(s, &os->y, delta); if (present & 0x04) in_uint8(s, os->opcode); if (present & 0x10) rdp_in_colour(s, &os->fgcolour); if (present & 0x20) in_uint8(s, os->lines); if (present & 0x40) { in_uint8(s, os->datasize); in_uint8a(s, os->data, os->datasize); } logger(Graphics, Debug, "process_polyline(), x=%d, y=%d, op=0x%x, fg=0x%x, n=%d, sz=%d)", os->x, os->y, os->opcode, os->fgcolour, os->lines, os->datasize); if (os->opcode < 0x01 || os->opcode > 0x10) { logger(Graphics, Error, "process_polyline(), bad ROP2 0x%x", os->opcode); return; } points = (RD_POINT *) xmalloc((os->lines + 1) * sizeof(RD_POINT)); memset(points, 0, (os->lines + 1) * sizeof(RD_POINT)); points[0].x = os->x; points[0].y = os->y; pen.style = pen.width = 0; pen.colour = os->fgcolour; index = 0; data = ((os->lines - 1) / 4) + 1; for (next = 1; (next <= os->lines) && (data < os->datasize); next++) { if ((next - 1) % 4 == 0) flags = os->data[index++]; if (~flags & 0x80) points[next].x = parse_delta(os->data, &data); if (~flags & 0x40) points[next].y = parse_delta(os->data, &data); flags <<= 2; } if (next - 1 == os->lines) ui_polyline(os->opcode - 1, points, os->lines + 1, &pen); else logger(Graphics, Error, "process_polyline(), parse error"); xfree(points); } /* Process an ellipse order */ static void process_ellipse(STREAM s, ELLIPSE_ORDER * os, uint32 present, RD_BOOL delta) { if (present & 0x01) rdp_in_coord(s, &os->left, delta); if (present & 0x02) rdp_in_coord(s, &os->top, delta); if (present & 0x04) rdp_in_coord(s, &os->right, delta); if (present & 0x08) rdp_in_coord(s, &os->bottom, delta); if (present & 0x10) in_uint8(s, os->opcode); if (present & 0x20) in_uint8(s, os->fillmode); if (present & 0x40) rdp_in_colour(s, &os->fgcolour); logger(Graphics, Debug, "process_ellipse(), l=%d, t=%d, r=%d, b=%d, op=0x%x, fm=%d, fg=0x%x", os->left, os->top, os->right, os->bottom, os->opcode, os->fillmode, os->fgcolour); ui_ellipse(os->opcode - 1, os->fillmode, os->left, os->top, os->right - os->left, os->bottom - os->top, NULL, 0, os->fgcolour); } /* Process an ellipse2 order */ static void process_ellipse2(STREAM s, ELLIPSE2_ORDER * os, uint32 present, RD_BOOL delta) { BRUSH brush; if (present & 0x0001) rdp_in_coord(s, &os->left, delta); if (present & 0x0002) rdp_in_coord(s, &os->top, delta); if (present & 0x0004) rdp_in_coord(s, &os->right, delta); if (present & 0x0008) rdp_in_coord(s, &os->bottom, delta); if (present & 0x0010) in_uint8(s, os->opcode); if (present & 0x0020) in_uint8(s, os->fillmode); if (present & 0x0040) rdp_in_colour(s, &os->bgcolour); if (present & 0x0080) rdp_in_colour(s, &os->fgcolour); rdp_parse_brush(s, &os->brush, present >> 8); logger(Graphics, Debug, "process_ellipse2(), l=%d, t=%d, r=%d, b=%d, op=0x%x, fm=%d, bs=%d, bg=0x%x, fg=0x%x", os->left, os->top, os->right, os->bottom, os->opcode, os->fillmode, os->brush.style, os->bgcolour, os->fgcolour); setup_brush(&brush, &os->brush); ui_ellipse(os->opcode - 1, os->fillmode, os->left, os->top, os->right - os->left, os->bottom - os->top, &brush, os->bgcolour, os->fgcolour); } /* Process a text order */ static void process_text2(STREAM s, TEXT2_ORDER * os, uint32 present, RD_BOOL delta) { UNUSED(delta); BRUSH brush; if (present & 0x000001) in_uint8(s, os->font); if (present & 0x000002) in_uint8(s, os->flags); if (present & 0x000004) in_uint8(s, os->opcode); if (present & 0x000008) in_uint8(s, os->mixmode); if (present & 0x000010) rdp_in_colour(s, &os->fgcolour); if (present & 0x000020) rdp_in_colour(s, &os->bgcolour); if (present & 0x000040) in_uint16_le(s, os->clipleft); if (present & 0x000080) in_uint16_le(s, os->cliptop); if (present & 0x000100) in_uint16_le(s, os->clipright); if (present & 0x000200) in_uint16_le(s, os->clipbottom); if (present & 0x000400) in_uint16_le(s, os->boxleft); if (present & 0x000800) in_uint16_le(s, os->boxtop); if (present & 0x001000) in_uint16_le(s, os->boxright); if (present & 0x002000) in_uint16_le(s, os->boxbottom); rdp_parse_brush(s, &os->brush, present >> 14); if (present & 0x080000) in_uint16_le(s, os->x); if (present & 0x100000) in_uint16_le(s, os->y); if (present & 0x200000) { in_uint8(s, os->length); in_uint8a(s, os->text, os->length); } logger(Graphics, Debug, "process_text2(), x=%d, y=%d, cl=%d, ct=%d, cr=%d, cb=%d, bl=%d, bt=%d, br=%d, bb=%d, bs=%d, bg=0x%x, fg=0x%x, font=%d, fl=0x%x, op=0x%x, mix=%d, n=%d", os->x, os->y, os->clipleft, os->cliptop, os->clipright, os->clipbottom, os->boxleft, os->boxtop, os->boxright, os->boxbottom, os->brush.style, os->bgcolour, os->fgcolour, os->font, os->flags, os->opcode, os->mixmode, os->length); setup_brush(&brush, &os->brush); ui_draw_text(os->font, os->flags, os->opcode - 1, os->mixmode, os->x, os->y, os->clipleft, os->cliptop, os->clipright - os->clipleft, os->clipbottom - os->cliptop, os->boxleft, os->boxtop, os->boxright - os->boxleft, os->boxbottom - os->boxtop, &brush, os->bgcolour, os->fgcolour, os->text, os->length); } /* Process a raw bitmap cache order */ static void process_raw_bmpcache(STREAM s) { RD_HBITMAP bitmap; uint16 cache_idx, bufsize; uint8 cache_id, width, height, bpp, Bpp; uint8 *data, *inverted; int y; in_uint8(s, cache_id); in_uint8s(s, 1); /* pad */ in_uint8(s, width); in_uint8(s, height); in_uint8(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, bufsize); in_uint16_le(s, cache_idx); in_uint8p(s, data, bufsize); logger(Graphics, Debug, "process_raw_bpmcache(), cx=%d, cy=%d, id=%d, idx=%d", width, height, cache_id, cache_idx); inverted = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { memcpy(&inverted[(height - y - 1) * (width * Bpp)], &data[y * (width * Bpp)], width * Bpp); } bitmap = ui_create_bitmap(width, height, inverted); xfree(inverted); cache_put_bitmap(cache_id, cache_idx, bitmap); } /* Process a bitmap cache order */ static void process_bmpcache(STREAM s) { RD_HBITMAP bitmap; uint16 cache_idx, size; uint8 cache_id, width, height, bpp, Bpp; uint8 *data, *bmpdata; uint16 bufsize, pad2, row_size, final_size; uint8 pad1; pad2 = row_size = final_size = 0xffff; /* Shut the compiler up */ in_uint8(s, cache_id); in_uint8(s, pad1); /* pad */ in_uint8(s, width); in_uint8(s, height); in_uint8(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, bufsize); /* bufsize */ in_uint16_le(s, cache_idx); if (g_rdp_version >= RDP_V5) { size = bufsize; } else { /* Begin compressedBitmapData */ in_uint16_le(s, pad2); /* pad */ in_uint16_le(s, size); /* in_uint8s(s, 4); *//* row_size, final_size */ in_uint16_le(s, row_size); in_uint16_le(s, final_size); } in_uint8p(s, data, size); logger(Graphics, Debug, "process_bmpcache(), cx=%d, cy=%d, id=%d, idx=%d, bpp=%d, size=%d, pad1=%d, bufsize=%d, pad2=%d, rs=%d, fs=%d", width, height, cache_id, cache_idx, bpp, size, pad1, bufsize, pad2, row_size, final_size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { bitmap = ui_create_bitmap(width, height, bmpdata); cache_put_bitmap(cache_id, cache_idx, bitmap); } else { logger(Graphics, Error, "process_bmpcache(), Failed to decompress bitmap data"); } xfree(bmpdata); } /* Process a bitmap cache v2 order */ static void process_bmpcache2(STREAM s, uint16 flags, RD_BOOL compressed) { RD_HBITMAP bitmap; int y; uint8 cache_id, cache_idx_low, width, height, Bpp; uint16 cache_idx, bufsize; uint8 *data, *bmpdata, *bitmap_id; bitmap_id = NULL; /* prevent compiler warning */ cache_id = flags & ID_MASK; Bpp = ((flags & MODE_MASK) >> MODE_SHIFT) - 2; if (flags & PERSIST) { in_uint8p(s, bitmap_id, 8); } if (flags & SQUARE) { in_uint8(s, width); height = width; } else { in_uint8(s, width); in_uint8(s, height); } in_uint16_be(s, bufsize); bufsize &= BUFSIZE_MASK; in_uint8(s, cache_idx); if (cache_idx & LONG_FORMAT) { in_uint8(s, cache_idx_low); cache_idx = ((cache_idx ^ LONG_FORMAT) << 8) + cache_idx_low; } in_uint8p(s, data, bufsize); logger(Graphics, Debug, "process_bmpcache2(), compr=%d, flags=%x, cx=%d, cy=%d, id=%d, idx=%d, Bpp=%d, bs=%d", compressed, flags, width, height, cache_id, cache_idx, Bpp, bufsize); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (compressed) { if (!bitmap_decompress(bmpdata, width, height, data, bufsize, Bpp)) { logger(Graphics, Error, "process_bmpcache2(), failed to decompress bitmap data"); xfree(bmpdata); return; } } else { for (y = 0; y < height; y++) memcpy(&bmpdata[(height - y - 1) * (width * Bpp)], &data[y * (width * Bpp)], width * Bpp); } bitmap = ui_create_bitmap(width, height, bmpdata); if (bitmap) { cache_put_bitmap(cache_id, cache_idx, bitmap); if (flags & PERSIST) pstcache_save_bitmap(cache_id, cache_idx, bitmap_id, width, height, width * height * Bpp, bmpdata); } else { logger(Graphics, Error, "process_bmpcache2(), ui_create_bitmap(), failed"); } xfree(bmpdata); } /* Process a colourmap cache order */ static void process_colcache(STREAM s) { COLOURENTRY *entry; COLOURMAP map; RD_HCOLOURMAP hmap; uint8 cache_id; int i; in_uint8(s, cache_id); in_uint16_le(s, map.ncolours); map.colours = (COLOURENTRY *) xmalloc(sizeof(COLOURENTRY) * map.ncolours); for (i = 0; i < map.ncolours; i++) { entry = &map.colours[i]; in_uint8(s, entry->blue); in_uint8(s, entry->green); in_uint8(s, entry->red); in_uint8s(s, 1); /* pad */ } logger(Graphics, Debug, "process_colcache(), id=%d, n=%d", cache_id, map.ncolours); hmap = ui_create_colourmap(&map); if (cache_id) ui_set_colourmap(hmap); xfree(map.colours); } /* Process a font cache order */ static void process_fontcache(STREAM s) { RD_HGLYPH bitmap; uint8 font, nglyphs; uint16 character, offset, baseline, width, height; int i, datasize; uint8 *data; in_uint8(s, font); in_uint8(s, nglyphs); logger(Graphics, Debug, "process_fontcache(), font=%d, n=%d", font, nglyphs); for (i = 0; i < nglyphs; i++) { in_uint16_le(s, character); in_uint16_le(s, offset); in_uint16_le(s, baseline); in_uint16_le(s, width); in_uint16_le(s, height); datasize = (height * ((width + 7) / 8) + 3) & ~3; in_uint8p(s, data, datasize); bitmap = ui_create_glyph(width, height, data); cache_put_font(font, character, offset, baseline, width, height, bitmap); } } static void process_compressed_8x8_brush_data(uint8 * in, uint8 * out, int Bpp) { int x, y, pal_index, in_index, shift, do2, i; uint8 *pal; in_index = 0; pal = in + 16; /* read it bottom up */ for (y = 7; y >= 0; y--) { /* 2 bytes per row */ x = 0; for (do2 = 0; do2 < 2; do2++) { /* 4 pixels per byte */ shift = 6; while (shift >= 0) { pal_index = (in[in_index] >> shift) & 3; /* size of palette entries depends on Bpp */ for (i = 0; i < Bpp; i++) { out[(y * 8 + x) * Bpp + i] = pal[pal_index * Bpp + i]; } x++; shift -= 2; } in_index++; } } } /* Process a brush cache order */ static void process_brushcache(STREAM s, uint16 flags) { UNUSED(flags); BRUSHDATA brush_data; uint8 cache_idx, colour_code, width, height, size, type; uint8 *comp_brush; int index; int Bpp; in_uint8(s, cache_idx); in_uint8(s, colour_code); in_uint8(s, width); in_uint8(s, height); in_uint8(s, type); /* type, 0x8x = cached */ in_uint8(s, size); logger(Graphics, Debug, "process_brushcache(), idx=%d, wd=%d, ht=%d, type=0x%x sz=%d", cache_idx, width, height, type, size); if ((width == 8) && (height == 8)) { if (colour_code == 1) { brush_data.colour_code = 1; brush_data.data_size = 8; brush_data.data = xmalloc(8); if (size == 8) { /* read it bottom up */ for (index = 7; index >= 0; index--) { in_uint8(s, brush_data.data[index]); } } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, colour_code %d size %d", colour_code, size); } cache_put_brush_data(1, cache_idx, &brush_data); } else if ((colour_code >= 3) && (colour_code <= 6)) { Bpp = colour_code - 2; brush_data.colour_code = colour_code; brush_data.data_size = 8 * 8 * Bpp; brush_data.data = xmalloc(8 * 8 * Bpp); if (size == 16 + 4 * Bpp) { in_uint8p(s, comp_brush, 16 + 4 * Bpp); process_compressed_8x8_brush_data(comp_brush, brush_data.data, Bpp); } else { in_uint8a(s, brush_data.data, 8 * 8 * Bpp); } cache_put_brush_data(colour_code, cache_idx, &brush_data); } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, colour_code %d size %d", colour_code, size); } } else { logger(Graphics, Warning, "process_brushcache(), incompatible brush, width height %d %d", width, height); } } /* Process a secondary order */ static void process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; struct stream packet = *s; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); if (!s_check_rem(s, length + 7)) { rdp_protocol_error("process_secondary_order(), next order pointer would overrun stream", &packet); } next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; } /* Process an order PDU */ void process_orders(STREAM s, uint16 num_orders) { RDP_ORDER_STATE *os = &g_order_state; uint32 present; uint8 order_flags; int size, processed = 0; RD_BOOL delta; while (processed < num_orders) { in_uint8(s, order_flags); if (!(order_flags & RDP_ORDER_STANDARD)) { logger(Graphics, Error, "process_orders(), order parsing failed"); break; } if (order_flags & RDP_ORDER_SECONDARY) { process_secondary_order(s); } else { if (order_flags & RDP_ORDER_CHANGE) { in_uint8(s, os->order_type); } switch (os->order_type) { case RDP_ORDER_TRIBLT: case RDP_ORDER_TEXT2: size = 3; break; case RDP_ORDER_PATBLT: case RDP_ORDER_MEMBLT: case RDP_ORDER_LINE: case RDP_ORDER_POLYGON2: case RDP_ORDER_ELLIPSE2: size = 2; break; default: size = 1; } rdp_in_present(s, &present, order_flags, size); if (order_flags & RDP_ORDER_BOUNDS) { if (!(order_flags & RDP_ORDER_LASTBOUNDS)) rdp_parse_bounds(s, &os->bounds); ui_set_clip(os->bounds.left, os->bounds.top, os->bounds.right - os->bounds.left + 1, os->bounds.bottom - os->bounds.top + 1); } delta = order_flags & RDP_ORDER_DELTA; switch (os->order_type) { case RDP_ORDER_DESTBLT: process_destblt(s, &os->destblt, present, delta); break; case RDP_ORDER_PATBLT: process_patblt(s, &os->patblt, present, delta); break; case RDP_ORDER_SCREENBLT: process_screenblt(s, &os->screenblt, present, delta); break; case RDP_ORDER_LINE: process_line(s, &os->line, present, delta); break; case RDP_ORDER_RECT: process_rect(s, &os->rect, present, delta); break; case RDP_ORDER_DESKSAVE: process_desksave(s, &os->desksave, present, delta); break; case RDP_ORDER_MEMBLT: process_memblt(s, &os->memblt, present, delta); break; case RDP_ORDER_TRIBLT: process_triblt(s, &os->triblt, present, delta); break; case RDP_ORDER_POLYGON: process_polygon(s, &os->polygon, present, delta); break; case RDP_ORDER_POLYGON2: process_polygon2(s, &os->polygon2, present, delta); break; case RDP_ORDER_POLYLINE: process_polyline(s, &os->polyline, present, delta); break; case RDP_ORDER_ELLIPSE: process_ellipse(s, &os->ellipse, present, delta); break; case RDP_ORDER_ELLIPSE2: process_ellipse2(s, &os->ellipse2, present, delta); break; case RDP_ORDER_TEXT2: process_text2(s, &os->text2, present, delta); break; default: logger(Graphics, Warning, "process_orders(), unhandled order type %d", os->order_type); return; } if (order_flags & RDP_ORDER_BOUNDS) ui_reset_clip(); } processed++; } #if 0 /* not true when RDP_COMPRESSION is set */ if (s->p != g_next_packet) logger(Graphics, Error, "process_orders(), %d bytes remaining", (int) (g_next_packet - s->p)); #endif } /* Reset order state */ void reset_order_state(void) { memset(&g_order_state, 0, sizeof(g_order_state)); g_order_state.order_type = RDP_ORDER_PATBLT; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_486_7
crossvul-cpp_data_bad_5303_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is: % % Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); return; } switch (type) { case -1: { SetPixelAlpha(image, pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.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); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5303_0
crossvul-cpp_data_good_3412_1
/********************************************************************* * * Linux multisound pinnacle/fiji driver for ALSA. * * 2002/06/30 Karsten Wiese: * for now this is only used to build a pinnacle / fiji driver. * the OSS parent of this code is designed to also support * the multisound classic via the file msnd_classic.c. * to make it easier for some brave heart to implemt classic * support in alsa, i left all the MSND_CLASSIC tokens in this file. * but for now this untested & undone. * * * ripped from linux kernel 2.4.18 by Karsten Wiese. * * the following is a copy of the 2.4.18 OSS FREE file-heading comment: * * Turtle Beach MultiSound Sound Card Driver for Linux * msnd_pinnacle.c / msnd_classic.c * * -- If MSND_CLASSIC is defined: * * -> driver for Turtle Beach Classic/Monterey/Tahiti * * -- Else * * -> driver for Turtle Beach Pinnacle/Fiji * * 12-3-2000 Modified IO port validation Steve Sycamore * * Copyright (C) 1998 Andrew Veliath * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * ********************************************************************/ #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/firmware.h> #include <linux/isa.h> #include <linux/isapnp.h> #include <linux/irq.h> #include <linux/io.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/asound.h> #include <sound/pcm.h> #include <sound/mpu401.h> #ifdef MSND_CLASSIC # ifndef __alpha__ # define SLOWIO # endif #endif #include "msnd.h" #ifdef MSND_CLASSIC # include "msnd_classic.h" # define LOGNAME "msnd_classic" # define DEV_NAME "msnd-classic" #else # include "msnd_pinnacle.h" # define LOGNAME "snd_msnd_pinnacle" # define DEV_NAME "msnd-pinnacle" #endif static void set_default_audio_parameters(struct snd_msnd *chip) { chip->play_sample_size = DEFSAMPLESIZE; chip->play_sample_rate = DEFSAMPLERATE; chip->play_channels = DEFCHANNELS; chip->capture_sample_size = DEFSAMPLESIZE; chip->capture_sample_rate = DEFSAMPLERATE; chip->capture_channels = DEFCHANNELS; } static void snd_msnd_eval_dsp_msg(struct snd_msnd *chip, u16 wMessage) { switch (HIBYTE(wMessage)) { case HIMT_PLAY_DONE: { if (chip->banksPlayed < 3) snd_printdd("%08X: HIMT_PLAY_DONE: %i\n", (unsigned)jiffies, LOBYTE(wMessage)); if (chip->last_playbank == LOBYTE(wMessage)) { snd_printdd("chip.last_playbank == LOBYTE(wMessage)\n"); break; } chip->banksPlayed++; if (test_bit(F_WRITING, &chip->flags)) snd_msnd_DAPQ(chip, 0); chip->last_playbank = LOBYTE(wMessage); chip->playDMAPos += chip->play_period_bytes; if (chip->playDMAPos > chip->playLimit) chip->playDMAPos = 0; snd_pcm_period_elapsed(chip->playback_substream); break; } case HIMT_RECORD_DONE: if (chip->last_recbank == LOBYTE(wMessage)) break; chip->last_recbank = LOBYTE(wMessage); chip->captureDMAPos += chip->capturePeriodBytes; if (chip->captureDMAPos > (chip->captureLimit)) chip->captureDMAPos = 0; if (test_bit(F_READING, &chip->flags)) snd_msnd_DARQ(chip, chip->last_recbank); snd_pcm_period_elapsed(chip->capture_substream); break; case HIMT_DSP: switch (LOBYTE(wMessage)) { #ifndef MSND_CLASSIC case HIDSP_PLAY_UNDER: #endif case HIDSP_INT_PLAY_UNDER: snd_printd(KERN_WARNING LOGNAME ": Play underflow %i\n", chip->banksPlayed); if (chip->banksPlayed > 2) clear_bit(F_WRITING, &chip->flags); break; case HIDSP_INT_RECORD_OVER: snd_printd(KERN_WARNING LOGNAME ": Record overflow\n"); clear_bit(F_READING, &chip->flags); break; default: snd_printd(KERN_WARNING LOGNAME ": DSP message %d 0x%02x\n", LOBYTE(wMessage), LOBYTE(wMessage)); break; } break; case HIMT_MIDI_IN_UCHAR: if (chip->msndmidi_mpu) snd_msndmidi_input_read(chip->msndmidi_mpu); break; default: snd_printd(KERN_WARNING LOGNAME ": HIMT message %d 0x%02x\n", HIBYTE(wMessage), HIBYTE(wMessage)); break; } } static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; u16 head, tail, size; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ head = readw(chip->DSPQ + JQS_wHead); tail = readw(chip->DSPQ + JQS_wTail); size = readw(chip->DSPQ + JQS_wSize); if (head > size || tail > size) goto out; while (head != tail) { snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * head)); if (++head > size) head = 0; writew(head, chip->DSPQ + JQS_wHead); } out: /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; } static int snd_msnd_reset_dsp(long io, unsigned char *info) { int timeout = 100; outb(HPDSPRESET_ON, io + HP_DSPR); msleep(1); #ifndef MSND_CLASSIC if (info) *info = inb(io + HP_INFO); #endif outb(HPDSPRESET_OFF, io + HP_DSPR); msleep(1); while (timeout-- > 0) { if (inb(io + HP_CVR) == HP_CVR_DEF) return 0; msleep(1); } snd_printk(KERN_ERR LOGNAME ": Cannot reset DSP\n"); return -EIO; } static int snd_msnd_probe(struct snd_card *card) { struct snd_msnd *chip = card->private_data; unsigned char info; #ifndef MSND_CLASSIC char *xv, *rev = NULL; char *pin = "TB Pinnacle", *fiji = "TB Fiji"; char *pinfiji = "TB Pinnacle/Fiji"; #endif if (!request_region(chip->io, DSP_NUMIO, "probing")) { snd_printk(KERN_ERR LOGNAME ": I/O port conflict\n"); return -ENODEV; } if (snd_msnd_reset_dsp(chip->io, &info) < 0) { release_region(chip->io, DSP_NUMIO); return -ENODEV; } #ifdef MSND_CLASSIC strcpy(card->shortname, "Classic/Tahiti/Monterey"); strcpy(card->longname, "Turtle Beach Multisound"); printk(KERN_INFO LOGNAME ": %s, " "I/O 0x%lx-0x%lx, IRQ %d, memory mapped to 0x%lX-0x%lX\n", card->shortname, chip->io, chip->io + DSP_NUMIO - 1, chip->irq, chip->base, chip->base + 0x7fff); #else switch (info >> 4) { case 0xf: xv = "<= 1.15"; break; case 0x1: xv = "1.18/1.2"; break; case 0x2: xv = "1.3"; break; case 0x3: xv = "1.4"; break; default: xv = "unknown"; break; } switch (info & 0x7) { case 0x0: rev = "I"; strcpy(card->shortname, pin); break; case 0x1: rev = "F"; strcpy(card->shortname, pin); break; case 0x2: rev = "G"; strcpy(card->shortname, pin); break; case 0x3: rev = "H"; strcpy(card->shortname, pin); break; case 0x4: rev = "E"; strcpy(card->shortname, fiji); break; case 0x5: rev = "C"; strcpy(card->shortname, fiji); break; case 0x6: rev = "D"; strcpy(card->shortname, fiji); break; case 0x7: rev = "A-B (Fiji) or A-E (Pinnacle)"; strcpy(card->shortname, pinfiji); break; } strcpy(card->longname, "Turtle Beach Multisound Pinnacle"); printk(KERN_INFO LOGNAME ": %s revision %s, Xilinx version %s, " "I/O 0x%lx-0x%lx, IRQ %d, memory mapped to 0x%lX-0x%lX\n", card->shortname, rev, xv, chip->io, chip->io + DSP_NUMIO - 1, chip->irq, chip->base, chip->base + 0x7fff); #endif release_region(chip->io, DSP_NUMIO); return 0; } static int snd_msnd_init_sma(struct snd_msnd *chip) { static int initted; u16 mastVolLeft, mastVolRight; unsigned long flags; #ifdef MSND_CLASSIC outb(chip->memid, chip->io + HP_MEMM); #endif outb(HPBLKSEL_0, chip->io + HP_BLKS); /* Motorola 56k shared memory base */ chip->SMA = chip->mappedbase + SMA_STRUCT_START; if (initted) { mastVolLeft = readw(chip->SMA + SMA_wCurrMastVolLeft); mastVolRight = readw(chip->SMA + SMA_wCurrMastVolRight); } else mastVolLeft = mastVolRight = 0; memset_io(chip->mappedbase, 0, 0x8000); /* Critical section: bank 1 access */ spin_lock_irqsave(&chip->lock, flags); outb(HPBLKSEL_1, chip->io + HP_BLKS); memset_io(chip->mappedbase, 0, 0x8000); outb(HPBLKSEL_0, chip->io + HP_BLKS); spin_unlock_irqrestore(&chip->lock, flags); /* Digital audio play queue */ chip->DAPQ = chip->mappedbase + DAPQ_OFFSET; snd_msnd_init_queue(chip->DAPQ, DAPQ_DATA_BUFF, DAPQ_BUFF_SIZE); /* Digital audio record queue */ chip->DARQ = chip->mappedbase + DARQ_OFFSET; snd_msnd_init_queue(chip->DARQ, DARQ_DATA_BUFF, DARQ_BUFF_SIZE); /* MIDI out queue */ chip->MODQ = chip->mappedbase + MODQ_OFFSET; snd_msnd_init_queue(chip->MODQ, MODQ_DATA_BUFF, MODQ_BUFF_SIZE); /* MIDI in queue */ chip->MIDQ = chip->mappedbase + MIDQ_OFFSET; snd_msnd_init_queue(chip->MIDQ, MIDQ_DATA_BUFF, MIDQ_BUFF_SIZE); /* DSP -> host message queue */ chip->DSPQ = chip->mappedbase + DSPQ_OFFSET; snd_msnd_init_queue(chip->DSPQ, DSPQ_DATA_BUFF, DSPQ_BUFF_SIZE); /* Setup some DSP values */ #ifndef MSND_CLASSIC writew(1, chip->SMA + SMA_wCurrPlayFormat); writew(chip->play_sample_size, chip->SMA + SMA_wCurrPlaySampleSize); writew(chip->play_channels, chip->SMA + SMA_wCurrPlayChannels); writew(chip->play_sample_rate, chip->SMA + SMA_wCurrPlaySampleRate); #endif writew(chip->play_sample_rate, chip->SMA + SMA_wCalFreqAtoD); writew(mastVolLeft, chip->SMA + SMA_wCurrMastVolLeft); writew(mastVolRight, chip->SMA + SMA_wCurrMastVolRight); #ifndef MSND_CLASSIC writel(0x00010000, chip->SMA + SMA_dwCurrPlayPitch); writel(0x00000001, chip->SMA + SMA_dwCurrPlayRate); #endif writew(0x303, chip->SMA + SMA_wCurrInputTagBits); initted = 1; return 0; } static int upload_dsp_code(struct snd_card *card) { struct snd_msnd *chip = card->private_data; const struct firmware *init_fw = NULL, *perm_fw = NULL; int err; outb(HPBLKSEL_0, chip->io + HP_BLKS); err = request_firmware(&init_fw, INITCODEFILE, card->dev); if (err < 0) { printk(KERN_ERR LOGNAME ": Error loading " INITCODEFILE); goto cleanup1; } err = request_firmware(&perm_fw, PERMCODEFILE, card->dev); if (err < 0) { printk(KERN_ERR LOGNAME ": Error loading " PERMCODEFILE); goto cleanup; } memcpy_toio(chip->mappedbase, perm_fw->data, perm_fw->size); if (snd_msnd_upload_host(chip, init_fw->data, init_fw->size) < 0) { printk(KERN_WARNING LOGNAME ": Error uploading to DSP\n"); err = -ENODEV; goto cleanup; } printk(KERN_INFO LOGNAME ": DSP firmware uploaded\n"); err = 0; cleanup: release_firmware(perm_fw); cleanup1: release_firmware(init_fw); return err; } #ifdef MSND_CLASSIC static void reset_proteus(struct snd_msnd *chip) { outb(HPPRORESET_ON, chip->io + HP_PROR); msleep(TIME_PRO_RESET); outb(HPPRORESET_OFF, chip->io + HP_PROR); msleep(TIME_PRO_RESET_DONE); } #endif static int snd_msnd_initialize(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int err, timeout; #ifdef MSND_CLASSIC outb(HPWAITSTATE_0, chip->io + HP_WAIT); outb(HPBITMODE_16, chip->io + HP_BITM); reset_proteus(chip); #endif err = snd_msnd_init_sma(chip); if (err < 0) { printk(KERN_WARNING LOGNAME ": Cannot initialize SMA\n"); return err; } err = snd_msnd_reset_dsp(chip->io, NULL); if (err < 0) return err; err = upload_dsp_code(card); if (err < 0) { printk(KERN_WARNING LOGNAME ": Cannot upload DSP code\n"); return err; } timeout = 200; while (readw(chip->mappedbase)) { msleep(1); if (!timeout--) { snd_printd(KERN_ERR LOGNAME ": DSP reset timeout\n"); return -EIO; } } snd_msndmix_setup(chip); return 0; } static int snd_msnd_dsp_full_reset(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int rv; if (test_bit(F_RESETTING, &chip->flags) || ++chip->nresets > 10) return 0; set_bit(F_RESETTING, &chip->flags); snd_msnd_dsp_halt(chip, NULL); /* Unconditionally halt */ rv = snd_msnd_initialize(card); if (rv) printk(KERN_WARNING LOGNAME ": DSP reset failed\n"); snd_msndmix_force_recsrc(chip, 0); clear_bit(F_RESETTING, &chip->flags); return rv; } static int snd_msnd_dev_free(struct snd_device *device) { snd_printdd("snd_msnd_chip_free()\n"); return 0; } static int snd_msnd_send_dsp_cmd_chk(struct snd_msnd *chip, u8 cmd) { if (snd_msnd_send_dsp_cmd(chip, cmd) == 0) return 0; snd_msnd_dsp_full_reset(chip->card); return snd_msnd_send_dsp_cmd(chip, cmd); } static int snd_msnd_calibrate_adc(struct snd_msnd *chip, u16 srate) { snd_printdd("snd_msnd_calibrate_adc(%i)\n", srate); writew(srate, chip->SMA + SMA_wCalFreqAtoD); if (chip->calibrate_signal == 0) writew(readw(chip->SMA + SMA_wCurrHostStatusFlags) | 0x0001, chip->SMA + SMA_wCurrHostStatusFlags); else writew(readw(chip->SMA + SMA_wCurrHostStatusFlags) & ~0x0001, chip->SMA + SMA_wCurrHostStatusFlags); if (snd_msnd_send_word(chip, 0, 0, HDEXAR_CAL_A_TO_D) == 0 && snd_msnd_send_dsp_cmd_chk(chip, HDEX_AUX_REQ) == 0) { schedule_timeout_interruptible(msecs_to_jiffies(333)); return 0; } printk(KERN_WARNING LOGNAME ": ADC calibration failed\n"); return -EIO; } /* * ALSA callback function, called when attempting to open the MIDI device. */ static int snd_msnd_mpu401_open(struct snd_mpu401 *mpu) { snd_msnd_enable_irq(mpu->private_data); snd_msnd_send_dsp_cmd(mpu->private_data, HDEX_MIDI_IN_START); return 0; } static void snd_msnd_mpu401_close(struct snd_mpu401 *mpu) { snd_msnd_send_dsp_cmd(mpu->private_data, HDEX_MIDI_IN_STOP); snd_msnd_disable_irq(mpu->private_data); } static long mpu_io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static int snd_msnd_attach(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int err; static struct snd_device_ops ops = { .dev_free = snd_msnd_dev_free, }; err = request_irq(chip->irq, snd_msnd_interrupt, 0, card->shortname, chip); if (err < 0) { printk(KERN_ERR LOGNAME ": Couldn't grab IRQ %d\n", chip->irq); return err; } if (request_region(chip->io, DSP_NUMIO, card->shortname) == NULL) { free_irq(chip->irq, chip); return -EBUSY; } if (!request_mem_region(chip->base, BUFFSIZE, card->shortname)) { printk(KERN_ERR LOGNAME ": unable to grab memory region 0x%lx-0x%lx\n", chip->base, chip->base + BUFFSIZE - 1); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); return -EBUSY; } chip->mappedbase = ioremap_nocache(chip->base, 0x8000); if (!chip->mappedbase) { printk(KERN_ERR LOGNAME ": unable to map memory region 0x%lx-0x%lx\n", chip->base, chip->base + BUFFSIZE - 1); err = -EIO; goto err_release_region; } err = snd_msnd_dsp_full_reset(card); if (err < 0) goto err_release_region; /* Register device */ err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops); if (err < 0) goto err_release_region; err = snd_msnd_pcm(card, 0); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new PCM device\n"); goto err_release_region; } err = snd_msndmix_new(card); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new Mixer device\n"); goto err_release_region; } if (mpu_io[0] != SNDRV_AUTO_PORT) { struct snd_mpu401 *mpu; err = snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, mpu_io[0], MPU401_MODE_INPUT | MPU401_MODE_OUTPUT, mpu_irq[0], &chip->rmidi); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new Midi device\n"); goto err_release_region; } mpu = chip->rmidi->private_data; mpu->open_input = snd_msnd_mpu401_open; mpu->close_input = snd_msnd_mpu401_close; mpu->private_data = chip; } disable_irq(chip->irq); snd_msnd_calibrate_adc(chip, chip->play_sample_rate); snd_msndmix_force_recsrc(chip, 0); err = snd_card_register(card); if (err < 0) goto err_release_region; return 0; err_release_region: iounmap(chip->mappedbase); release_mem_region(chip->base, BUFFSIZE); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); return err; } static void snd_msnd_unload(struct snd_card *card) { struct snd_msnd *chip = card->private_data; iounmap(chip->mappedbase); release_mem_region(chip->base, BUFFSIZE); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); snd_card_free(card); } #ifndef MSND_CLASSIC /* Pinnacle/Fiji Logical Device Configuration */ static int snd_msnd_write_cfg(int cfg, int reg, int value) { outb(reg, cfg); outb(value, cfg + 1); if (value != inb(cfg + 1)) { printk(KERN_ERR LOGNAME ": snd_msnd_write_cfg: I/O error\n"); return -EIO; } return 0; } static int snd_msnd_write_cfg_io0(int cfg, int num, u16 io) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO0_BASEHI, HIBYTE(io))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO0_BASELO, LOBYTE(io))) return -EIO; return 0; } static int snd_msnd_write_cfg_io1(int cfg, int num, u16 io) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO1_BASEHI, HIBYTE(io))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO1_BASELO, LOBYTE(io))) return -EIO; return 0; } static int snd_msnd_write_cfg_irq(int cfg, int num, u16 irq) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_NUMBER, LOBYTE(irq))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_TYPE, IRQTYPE_EDGE)) return -EIO; return 0; } static int snd_msnd_write_cfg_mem(int cfg, int num, int mem) { u16 wmem; mem >>= 8; wmem = (u16)(mem & 0xfff); if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_MEMBASEHI, HIBYTE(wmem))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_MEMBASELO, LOBYTE(wmem))) return -EIO; if (wmem && snd_msnd_write_cfg(cfg, IREG_MEMCONTROL, MEMTYPE_HIADDR | MEMTYPE_16BIT)) return -EIO; return 0; } static int snd_msnd_activate_logical(int cfg, int num) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_ACTIVATE, LD_ACTIVATE)) return -EIO; return 0; } static int snd_msnd_write_cfg_logical(int cfg, int num, u16 io0, u16 io1, u16 irq, int mem) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg_io0(cfg, num, io0)) return -EIO; if (snd_msnd_write_cfg_io1(cfg, num, io1)) return -EIO; if (snd_msnd_write_cfg_irq(cfg, num, irq)) return -EIO; if (snd_msnd_write_cfg_mem(cfg, num, mem)) return -EIO; if (snd_msnd_activate_logical(cfg, num)) return -EIO; return 0; } static int snd_msnd_pinnacle_cfg_reset(int cfg) { int i; /* Reset devices if told to */ printk(KERN_INFO LOGNAME ": Resetting all devices\n"); for (i = 0; i < 4; ++i) if (snd_msnd_write_cfg_logical(cfg, i, 0, 0, 0, 0)) return -EIO; return 0; } #endif static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ module_param_array(index, int, NULL, S_IRUGO); MODULE_PARM_DESC(index, "Index value for msnd_pinnacle soundcard."); module_param_array(id, charp, NULL, S_IRUGO); MODULE_PARM_DESC(id, "ID string for msnd_pinnacle soundcard."); static long io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static long mem[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; #ifndef MSND_CLASSIC static long cfg[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* Extra Peripheral Configuration (Default: Disable) */ static long ide_io0[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static long ide_io1[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int ide_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static long joystick_io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* If we have the digital daugherboard... */ static int digital[SNDRV_CARDS]; /* Extra Peripheral Configuration */ static int reset[SNDRV_CARDS]; #endif static int write_ndelay[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = 1 }; static int calibrate_signal; #ifdef CONFIG_PNP static bool isapnp[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(isapnp, bool, NULL, 0444); MODULE_PARM_DESC(isapnp, "ISA PnP detection for specified soundcard."); #define has_isapnp(x) isapnp[x] #else #define has_isapnp(x) 0 #endif MODULE_AUTHOR("Karsten Wiese <annabellesgarden@yahoo.de>"); MODULE_DESCRIPTION("Turtle Beach " LONGNAME " Linux Driver"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(INITCODEFILE); MODULE_FIRMWARE(PERMCODEFILE); module_param_hw_array(io, long, ioport, NULL, S_IRUGO); MODULE_PARM_DESC(io, "IO port #"); module_param_hw_array(irq, int, irq, NULL, S_IRUGO); module_param_hw_array(mem, long, iomem, NULL, S_IRUGO); module_param_array(write_ndelay, int, NULL, S_IRUGO); module_param(calibrate_signal, int, S_IRUGO); #ifndef MSND_CLASSIC module_param_array(digital, int, NULL, S_IRUGO); module_param_hw_array(cfg, long, ioport, NULL, S_IRUGO); module_param_array(reset, int, 0, S_IRUGO); module_param_hw_array(mpu_io, long, ioport, NULL, S_IRUGO); module_param_hw_array(mpu_irq, int, irq, NULL, S_IRUGO); module_param_hw_array(ide_io0, long, ioport, NULL, S_IRUGO); module_param_hw_array(ide_io1, long, ioport, NULL, S_IRUGO); module_param_hw_array(ide_irq, int, irq, NULL, S_IRUGO); module_param_hw_array(joystick_io, long, ioport, NULL, S_IRUGO); #endif static int snd_msnd_isa_match(struct device *pdev, unsigned int i) { if (io[i] == SNDRV_AUTO_PORT) return 0; if (irq[i] == SNDRV_AUTO_PORT || mem[i] == SNDRV_AUTO_PORT) { printk(KERN_WARNING LOGNAME ": io, irq and mem must be set\n"); return 0; } #ifdef MSND_CLASSIC if (!(io[i] == 0x290 || io[i] == 0x260 || io[i] == 0x250 || io[i] == 0x240 || io[i] == 0x230 || io[i] == 0x220 || io[i] == 0x210 || io[i] == 0x3e0)) { printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must be set " " to 0x210, 0x220, 0x230, 0x240, 0x250, 0x260, 0x290, " "or 0x3E0\n"); return 0; } #else if (io[i] < 0x100 || io[i] > 0x3e0 || (io[i] % 0x10) != 0) { printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must within the range 0x100 " "to 0x3E0 and must be evenly divisible by 0x10\n"); return 0; } #endif /* MSND_CLASSIC */ if (!(irq[i] == 5 || irq[i] == 7 || irq[i] == 9 || irq[i] == 10 || irq[i] == 11 || irq[i] == 12)) { printk(KERN_ERR LOGNAME ": \"irq\" - must be set to 5, 7, 9, 10, 11 or 12\n"); return 0; } if (!(mem[i] == 0xb0000 || mem[i] == 0xc8000 || mem[i] == 0xd0000 || mem[i] == 0xd8000 || mem[i] == 0xe0000 || mem[i] == 0xe8000)) { printk(KERN_ERR LOGNAME ": \"mem\" - must be set to " "0xb0000, 0xc8000, 0xd0000, 0xd8000, 0xe0000 or " "0xe8000\n"); return 0; } #ifndef MSND_CLASSIC if (cfg[i] == SNDRV_AUTO_PORT) { printk(KERN_INFO LOGNAME ": Assuming PnP mode\n"); } else if (cfg[i] != 0x250 && cfg[i] != 0x260 && cfg[i] != 0x270) { printk(KERN_INFO LOGNAME ": Config port must be 0x250, 0x260 or 0x270 " "(or unspecified for PnP mode)\n"); return 0; } #endif /* MSND_CLASSIC */ return 1; } static int snd_msnd_isa_probe(struct device *pdev, unsigned int idx) { int err; struct snd_card *card; struct snd_msnd *chip; if (has_isapnp(idx) #ifndef MSND_CLASSIC || cfg[idx] == SNDRV_AUTO_PORT #endif ) { printk(KERN_INFO LOGNAME ": Assuming PnP mode\n"); return -ENODEV; } err = snd_card_new(pdev, index[idx], id[idx], THIS_MODULE, sizeof(struct snd_msnd), &card); if (err < 0) return err; chip = card->private_data; chip->card = card; #ifdef MSND_CLASSIC switch (irq[idx]) { case 5: chip->irqid = HPIRQ_5; break; case 7: chip->irqid = HPIRQ_7; break; case 9: chip->irqid = HPIRQ_9; break; case 10: chip->irqid = HPIRQ_10; break; case 11: chip->irqid = HPIRQ_11; break; case 12: chip->irqid = HPIRQ_12; break; } switch (mem[idx]) { case 0xb0000: chip->memid = HPMEM_B000; break; case 0xc8000: chip->memid = HPMEM_C800; break; case 0xd0000: chip->memid = HPMEM_D000; break; case 0xd8000: chip->memid = HPMEM_D800; break; case 0xe0000: chip->memid = HPMEM_E000; break; case 0xe8000: chip->memid = HPMEM_E800; break; } #else printk(KERN_INFO LOGNAME ": Non-PnP mode: configuring at port 0x%lx\n", cfg[idx]); if (!request_region(cfg[idx], 2, "Pinnacle/Fiji Config")) { printk(KERN_ERR LOGNAME ": Config port 0x%lx conflict\n", cfg[idx]); snd_card_free(card); return -EIO; } if (reset[idx]) if (snd_msnd_pinnacle_cfg_reset(cfg[idx])) { err = -EIO; goto cfg_error; } /* DSP */ err = snd_msnd_write_cfg_logical(cfg[idx], 0, io[idx], 0, irq[idx], mem[idx]); if (err) goto cfg_error; /* The following are Pinnacle specific */ /* MPU */ if (mpu_io[idx] != SNDRV_AUTO_PORT && mpu_irq[idx] != SNDRV_AUTO_IRQ) { printk(KERN_INFO LOGNAME ": Configuring MPU to I/O 0x%lx IRQ %d\n", mpu_io[idx], mpu_irq[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 1, mpu_io[idx], 0, mpu_irq[idx], 0); if (err) goto cfg_error; } /* IDE */ if (ide_io0[idx] != SNDRV_AUTO_PORT && ide_io1[idx] != SNDRV_AUTO_PORT && ide_irq[idx] != SNDRV_AUTO_IRQ) { printk(KERN_INFO LOGNAME ": Configuring IDE to I/O 0x%lx, 0x%lx IRQ %d\n", ide_io0[idx], ide_io1[idx], ide_irq[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 2, ide_io0[idx], ide_io1[idx], ide_irq[idx], 0); if (err) goto cfg_error; } /* Joystick */ if (joystick_io[idx] != SNDRV_AUTO_PORT) { printk(KERN_INFO LOGNAME ": Configuring joystick to I/O 0x%lx\n", joystick_io[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 3, joystick_io[idx], 0, 0, 0); if (err) goto cfg_error; } release_region(cfg[idx], 2); #endif /* MSND_CLASSIC */ set_default_audio_parameters(chip); #ifdef MSND_CLASSIC chip->type = msndClassic; #else chip->type = msndPinnacle; #endif chip->io = io[idx]; chip->irq = irq[idx]; chip->base = mem[idx]; chip->calibrate_signal = calibrate_signal ? 1 : 0; chip->recsrc = 0; chip->dspq_data_buff = DSPQ_DATA_BUFF; chip->dspq_buff_size = DSPQ_BUFF_SIZE; if (write_ndelay[idx]) clear_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); else set_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); #ifndef MSND_CLASSIC if (digital[idx]) set_bit(F_HAVEDIGITAL, &chip->flags); #endif spin_lock_init(&chip->lock); err = snd_msnd_probe(card); if (err < 0) { printk(KERN_ERR LOGNAME ": Probe failed\n"); snd_card_free(card); return err; } err = snd_msnd_attach(card); if (err < 0) { printk(KERN_ERR LOGNAME ": Attach failed\n"); snd_card_free(card); return err; } dev_set_drvdata(pdev, card); return 0; #ifndef MSND_CLASSIC cfg_error: release_region(cfg[idx], 2); snd_card_free(card); return err; #endif } static int snd_msnd_isa_remove(struct device *pdev, unsigned int dev) { snd_msnd_unload(dev_get_drvdata(pdev)); return 0; } static struct isa_driver snd_msnd_driver = { .match = snd_msnd_isa_match, .probe = snd_msnd_isa_probe, .remove = snd_msnd_isa_remove, /* FIXME: suspend, resume */ .driver = { .name = DEV_NAME }, }; #ifdef CONFIG_PNP static int snd_msnd_pnp_detect(struct pnp_card_link *pcard, const struct pnp_card_device_id *pid) { static int idx; struct pnp_dev *pnp_dev; struct pnp_dev *mpu_dev; struct snd_card *card; struct snd_msnd *chip; int ret; for ( ; idx < SNDRV_CARDS; idx++) { if (has_isapnp(idx)) break; } if (idx >= SNDRV_CARDS) return -ENODEV; /* * Check that we still have room for another sound card ... */ pnp_dev = pnp_request_card_device(pcard, pid->devs[0].id, NULL); if (!pnp_dev) return -ENODEV; mpu_dev = pnp_request_card_device(pcard, pid->devs[1].id, NULL); if (!mpu_dev) return -ENODEV; if (!pnp_is_active(pnp_dev) && pnp_activate_dev(pnp_dev) < 0) { printk(KERN_INFO "msnd_pinnacle: device is inactive\n"); return -EBUSY; } if (!pnp_is_active(mpu_dev) && pnp_activate_dev(mpu_dev) < 0) { printk(KERN_INFO "msnd_pinnacle: MPU device is inactive\n"); return -EBUSY; } /* * Create a new ALSA sound card entry, in anticipation * of detecting our hardware ... */ ret = snd_card_new(&pcard->card->dev, index[idx], id[idx], THIS_MODULE, sizeof(struct snd_msnd), &card); if (ret < 0) return ret; chip = card->private_data; chip->card = card; /* * Read the correct parameters off the ISA PnP bus ... */ io[idx] = pnp_port_start(pnp_dev, 0); irq[idx] = pnp_irq(pnp_dev, 0); mem[idx] = pnp_mem_start(pnp_dev, 0); mpu_io[idx] = pnp_port_start(mpu_dev, 0); mpu_irq[idx] = pnp_irq(mpu_dev, 0); set_default_audio_parameters(chip); #ifdef MSND_CLASSIC chip->type = msndClassic; #else chip->type = msndPinnacle; #endif chip->io = io[idx]; chip->irq = irq[idx]; chip->base = mem[idx]; chip->calibrate_signal = calibrate_signal ? 1 : 0; chip->recsrc = 0; chip->dspq_data_buff = DSPQ_DATA_BUFF; chip->dspq_buff_size = DSPQ_BUFF_SIZE; if (write_ndelay[idx]) clear_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); else set_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); #ifndef MSND_CLASSIC if (digital[idx]) set_bit(F_HAVEDIGITAL, &chip->flags); #endif spin_lock_init(&chip->lock); ret = snd_msnd_probe(card); if (ret < 0) { printk(KERN_ERR LOGNAME ": Probe failed\n"); goto _release_card; } ret = snd_msnd_attach(card); if (ret < 0) { printk(KERN_ERR LOGNAME ": Attach failed\n"); goto _release_card; } pnp_set_card_drvdata(pcard, card); ++idx; return 0; _release_card: snd_card_free(card); return ret; } static void snd_msnd_pnp_remove(struct pnp_card_link *pcard) { snd_msnd_unload(pnp_get_card_drvdata(pcard)); pnp_set_card_drvdata(pcard, NULL); } static int isa_registered; static int pnp_registered; static struct pnp_card_device_id msnd_pnpids[] = { /* Pinnacle PnP */ { .id = "BVJ0440", .devs = { { "TBS0000" }, { "TBS0001" } } }, { .id = "" } /* end */ }; MODULE_DEVICE_TABLE(pnp_card, msnd_pnpids); static struct pnp_card_driver msnd_pnpc_driver = { .flags = PNP_DRIVER_RES_DO_NOT_CHANGE, .name = "msnd_pinnacle", .id_table = msnd_pnpids, .probe = snd_msnd_pnp_detect, .remove = snd_msnd_pnp_remove, }; #endif /* CONFIG_PNP */ static int __init snd_msnd_init(void) { int err; err = isa_register_driver(&snd_msnd_driver, SNDRV_CARDS); #ifdef CONFIG_PNP if (!err) isa_registered = 1; err = pnp_register_card_driver(&msnd_pnpc_driver); if (!err) pnp_registered = 1; if (isa_registered) err = 0; #endif return err; } static void __exit snd_msnd_exit(void) { #ifdef CONFIG_PNP if (pnp_registered) pnp_unregister_card_driver(&msnd_pnpc_driver); if (isa_registered) #endif isa_unregister_driver(&snd_msnd_driver); } module_init(snd_msnd_init); module_exit(snd_msnd_exit);
./CrossVul/dataset_final_sorted/CWE-125/c/good_3412_1
crossvul-cpp_data_bad_5492_1
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 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__ */ /* * Tier-2 Coding Library * * $Id$ */ #include "jasper/jas_math.h" #include "jasper/jas_malloc.h" #include "jpc_cs.h" #include "jpc_t2cod.h" #include "jpc_math.h" static int jpc_pi_nextlrcp(jpc_pi_t *pi); static int jpc_pi_nextrlcp(jpc_pi_t *pi); static int jpc_pi_nextrpcl(jpc_pi_t *pi); static int jpc_pi_nextpcrl(jpc_pi_t *pi); static int jpc_pi_nextcprl(jpc_pi_t *pi); int jpc_pi_next(jpc_pi_t *pi) { jpc_pchg_t *pchg; int ret; for (;;) { pi->valid = false; if (!pi->pchg) { ++pi->pchgno; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->prgvolfirst = true; if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno); } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = &pi->defaultpchg; } else { return 1; } } pchg = pi->pchg; switch (pchg->prgord) { case JPC_COD_LRCPPRG: ret = jpc_pi_nextlrcp(pi); break; case JPC_COD_RLCPPRG: ret = jpc_pi_nextrlcp(pi); break; case JPC_COD_RPCLPRG: ret = jpc_pi_nextrpcl(pi); break; case JPC_COD_PCRLPRG: ret = jpc_pi_nextpcrl(pi); break; case JPC_COD_CPRLPRG: ret = jpc_pi_nextcprl(pi); break; default: ret = -1; break; } if (!ret) { pi->valid = true; ++pi->pktno; return 0; } pi->pchg = 0; } } static int jpc_pi_nextlrcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = false; } for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextpcrl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static void pirlvl_destroy(jpc_pirlvl_t *rlvl) { if (rlvl->prclyrnos) { jas_free(rlvl->prclyrnos); } } static void jpc_picomp_destroy(jpc_picomp_t *picomp) { int rlvlno; jpc_pirlvl_t *pirlvl; if (picomp->pirlvls) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl_destroy(pirlvl); } jas_free(picomp->pirlvls); } } void jpc_pi_destroy(jpc_pi_t *pi) { jpc_picomp_t *picomp; int compno; if (pi->picomps) { for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { jpc_picomp_destroy(picomp); } jas_free(pi->picomps); } if (pi->pchglist) { jpc_pchglist_destroy(pi->pchglist); } jas_free(pi); } jpc_pi_t *jpc_pi_create0() { jpc_pi_t *pi; if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) { return 0; } pi->picomps = 0; pi->pchgno = 0; if (!(pi->pchglist = jpc_pchglist_create())) { jas_free(pi); return 0; } return pi; } int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg) { return jpc_pchglist_insert(pi->pchglist, -1, pchg); } jpc_pchglist_t *jpc_pchglist_create() { jpc_pchglist_t *pchglist; if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) { return 0; } pchglist->numpchgs = 0; pchglist->maxpchgs = 0; pchglist->pchgs = 0; return pchglist; } int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) { int i; int newmaxpchgs; jpc_pchg_t **newpchgs; if (pchgno < 0) { pchgno = pchglist->numpchgs; } if (pchglist->numpchgs >= pchglist->maxpchgs) { newmaxpchgs = pchglist->maxpchgs + 128; if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs, sizeof(jpc_pchg_t *)))) { return -1; } pchglist->maxpchgs = newmaxpchgs; pchglist->pchgs = newpchgs; } for (i = pchglist->numpchgs; i > pchgno; --i) { pchglist->pchgs[i] = pchglist->pchgs[i - 1]; } pchglist->pchgs[pchgno] = pchg; ++pchglist->numpchgs; return 0; } jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno) { int i; jpc_pchg_t *pchg; assert(pchgno < pchglist->numpchgs); pchg = pchglist->pchgs[pchgno]; for (i = pchgno + 1; i < pchglist->numpchgs; ++i) { pchglist->pchgs[i - 1] = pchglist->pchgs[i]; } --pchglist->numpchgs; return pchg; } jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg) { jpc_pchg_t *newpchg; if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) { return 0; } *newpchg = *pchg; return newpchg; } jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist) { jpc_pchglist_t *newpchglist; jpc_pchg_t *newpchg; int pchgno; if (!(newpchglist = jpc_pchglist_create())) { return 0; } for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) || jpc_pchglist_insert(newpchglist, -1, newpchg)) { jpc_pchglist_destroy(newpchglist); return 0; } } return newpchglist; } void jpc_pchglist_destroy(jpc_pchglist_t *pchglist) { int pchgno; if (pchglist->pchgs) { for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { jpc_pchg_destroy(pchglist->pchgs[pchgno]); } jas_free(pchglist->pchgs); } jas_free(pchglist); } void jpc_pchg_destroy(jpc_pchg_t *pchg) { jas_free(pchg); } jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno) { return pchglist->pchgs[pchgno]; } int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist) { return pchglist->numpchgs; } int jpc_pi_init(jpc_pi_t *pi) { int compno; int rlvlno; int prcno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; int *prclyrno; pi->prgvolfirst = 0; pi->valid = 0; pi->pktno = -1; pi->pchgno = -1; pi->pchg = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } } } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5492_1
crossvul-cpp_data_good_113_0
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "delta.h" /* maximum hash entry list for the same hash bucket */ #define HASH_LIMIT 64 #define RABIN_SHIFT 23 #define RABIN_WINDOW 16 static const unsigned int T[256] = { 0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344, 0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259, 0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85, 0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2, 0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a, 0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db, 0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753, 0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964, 0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8, 0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5, 0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81, 0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6, 0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e, 0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77, 0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff, 0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8, 0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc, 0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1, 0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d, 0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a, 0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2, 0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02, 0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a, 0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd, 0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61, 0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c, 0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08, 0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f, 0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7, 0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe, 0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76, 0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141, 0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65, 0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78, 0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4, 0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93, 0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b, 0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa, 0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872, 0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645, 0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99, 0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84, 0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811 }; static const unsigned int U[256] = { 0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a, 0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48, 0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511, 0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d, 0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8, 0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe, 0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb, 0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937, 0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e, 0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c, 0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d, 0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1, 0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4, 0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa, 0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef, 0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263, 0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302, 0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000, 0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59, 0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5, 0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90, 0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7, 0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2, 0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e, 0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467, 0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765, 0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604, 0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88, 0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd, 0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3, 0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996, 0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a, 0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b, 0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609, 0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50, 0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc, 0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99, 0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf, 0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa, 0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176, 0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f, 0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d, 0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a }; struct index_entry { const unsigned char *ptr; unsigned int val; struct index_entry *next; }; struct git_delta_index { unsigned long memsize; const void *src_buf; size_t src_size; unsigned int hash_mask; struct index_entry *hash[GIT_FLEX_ARRAY]; }; static int lookup_index_alloc( void **out, unsigned long *out_len, size_t entries, size_t hash_count) { size_t entries_len, hash_len, index_len; GITERR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry)); GITERR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *)); GITERR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len); GITERR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len); if (!git__is_ulong(index_len)) { giterr_set(GITERR_NOMEMORY, "overly large delta"); return -1; } *out = git__malloc(index_len); GITERR_CHECK_ALLOC(*out); *out_len = index_len; return 0; } int git_delta_index_init( git_delta_index **out, const void *buf, size_t bufsize) { unsigned int i, hsize, hmask, entries, prev_val, *hash_count; const unsigned char *data, *buffer = buf; struct git_delta_index *index; struct index_entry *entry, **hash; void *mem; unsigned long memsize; *out = NULL; if (!buf || !bufsize) return 0; /* Determine index hash size. Note that indexing skips the first byte to allow for optimizing the rabin polynomial initialization in create_delta(). */ entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW; if (bufsize >= 0xffffffffUL) { /* * Current delta format can't encode offsets into * reference buffer with more than 32 bits. */ entries = 0xfffffffeU / RABIN_WINDOW; } hsize = entries / 4; for (i = 4; i < 31 && (1u << i) < hsize; i++); hsize = 1 << i; hmask = hsize - 1; if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0) return -1; index = mem; mem = index->hash; hash = mem; mem = hash + hsize; entry = mem; index->memsize = memsize; index->src_buf = buf; index->src_size = bufsize; index->hash_mask = hmask; memset(hash, 0, hsize * sizeof(*hash)); /* allocate an array to count hash entries */ hash_count = git__calloc(hsize, sizeof(*hash_count)); if (!hash_count) { git__free(index); return -1; } /* then populate the index */ prev_val = ~0; for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW; data >= buffer; data -= RABIN_WINDOW) { unsigned int val = 0; for (i = 1; i <= RABIN_WINDOW; i++) val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT]; if (val == prev_val) { /* keep the lowest of consecutive identical blocks */ entry[-1].ptr = data + RABIN_WINDOW; } else { prev_val = val; i = val & hmask; entry->ptr = data + RABIN_WINDOW; entry->val = val; entry->next = hash[i]; hash[i] = entry++; hash_count[i]++; } } /* * Determine a limit on the number of entries in the same hash * bucket. This guard us against patological data sets causing * really bad hash distribution with most entries in the same hash * bucket that would bring us to O(m*n) computing costs (m and n * corresponding to reference and target buffer sizes). * * Make sure none of the hash buckets has more entries than * we're willing to test. Otherwise we cull the entry list * uniformly to still preserve a good repartition across * the reference buffer. */ for (i = 0; i < hsize; i++) { if (hash_count[i] < HASH_LIMIT) continue; entry = hash[i]; do { struct index_entry *keep = entry; int skip = hash_count[i] / HASH_LIMIT / 2; do { entry = entry->next; } while(--skip && entry); keep->next = entry; } while (entry); } git__free(hash_count); *out = index; return 0; } void git_delta_index_free(git_delta_index *index) { git__free(index); } size_t git_delta_index_size(git_delta_index *index) { assert(index); return index->memsize; } /* * The maximum size for any opcode sequence, including the initial header * plus rabin window plus biggest copy. */ #define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7) int git_delta_create_from_index( void **out, size_t *out_len, const struct git_delta_index *index, const void *trg_buf, size_t trg_size, size_t max_size) { unsigned int i, bufpos, bufsize, moff, msize, val; int inscnt; const unsigned char *ref_data, *ref_top, *data, *top; unsigned char *buf; *out = NULL; *out_len = 0; if (!trg_buf || !trg_size) return 0; bufpos = 0; bufsize = 8192; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); buf = git__malloc(bufsize); GITERR_CHECK_ALLOC(buf); /* store reference buffer size */ i = index->src_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; /* store target buffer size */ i = trg_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; ref_data = index->src_buf; ref_top = ref_data + index->src_size; data = trg_buf; top = (const unsigned char *) trg_buf + trg_size; bufpos++; val = 0; for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) { buf[bufpos++] = *data; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; } inscnt = i; moff = 0; msize = 0; while (data < top) { if (msize < 4096) { struct index_entry *entry; val ^= U[data[-RABIN_WINDOW]]; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; i = val & index->hash_mask; for (entry = index->hash[i]; entry; entry = entry->next) { const unsigned char *ref = entry->ptr; const unsigned char *src = data; unsigned int ref_size = (unsigned int)(ref_top - ref); if (entry->val != val) continue; if (ref_size > (unsigned int)(top - src)) ref_size = (unsigned int)(top - src); if (ref_size <= msize) break; while (ref_size-- && *src++ == *ref) ref++; if (msize < (unsigned int)(ref - entry->ptr)) { /* this is our best match so far */ msize = (unsigned int)(ref - entry->ptr); moff = (unsigned int)(entry->ptr - ref_data); if (msize >= 4096) /* good enough */ break; } } } if (msize < 4) { if (!inscnt) bufpos++; buf[bufpos++] = *data++; inscnt++; if (inscnt == 0x7f) { buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } msize = 0; } else { unsigned int left; unsigned char *op; if (inscnt) { while (moff && ref_data[moff-1] == data[-1]) { /* we can match one byte back */ msize++; moff--; data--; bufpos--; if (--inscnt) continue; bufpos--; /* remove count slot */ inscnt--; /* make it -1 */ break; } buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } /* A copy op is currently limited to 64KB (pack v2) */ left = (msize < 0x10000) ? 0 : (msize - 0x10000); msize -= left; op = buf + bufpos++; i = 0x80; if (moff & 0x000000ff) buf[bufpos++] = moff >> 0, i |= 0x01; if (moff & 0x0000ff00) buf[bufpos++] = moff >> 8, i |= 0x02; if (moff & 0x00ff0000) buf[bufpos++] = moff >> 16, i |= 0x04; if (moff & 0xff000000) buf[bufpos++] = moff >> 24, i |= 0x08; if (msize & 0x00ff) buf[bufpos++] = msize >> 0, i |= 0x10; if (msize & 0xff00) buf[bufpos++] = msize >> 8, i |= 0x20; *op = i; data += msize; moff += msize; msize = left; if (msize < 4096) { int j; val = 0; for (j = -RABIN_WINDOW; j < 0; j++) val = ((val << 8) | data[j]) ^ T[val >> RABIN_SHIFT]; } } if (bufpos >= bufsize - MAX_OP_SIZE) { void *tmp = buf; bufsize = bufsize * 3 / 2; if (max_size && bufsize >= max_size) bufsize = max_size + MAX_OP_SIZE + 1; if (max_size && bufpos > max_size) break; buf = git__realloc(buf, bufsize); if (!buf) { git__free(tmp); return -1; } } } if (inscnt) buf[bufpos - inscnt - 1] = inscnt; if (max_size && bufpos > max_size) { giterr_set(GITERR_NOMEMORY, "delta would be larger than maximum size"); git__free(buf); return GIT_EBUFS; } *out_len = bufpos; *out = buf; return 0; } /* * Delta application was heavily cribbed from BinaryDelta.java in JGit, which * itself was heavily cribbed from <code>patch-delta.c</code> in the * GIT project. The original delta patching code was written by * Nicolas Pitre <nico@cam.org>. */ static int hdr_sz( size_t *size, const unsigned char **delta, const unsigned char *end) { const unsigned char *d = *delta; size_t r = 0; unsigned int c, shift = 0; do { if (d == end) { giterr_set(GITERR_INVALID, "truncated delta"); return -1; } c = *d++; r |= (c & 0x7f) << shift; shift += 7; } while (c & 0x80); *delta = d; *size = r; return 0; } int git_delta_read_header( size_t *base_out, size_t *result_out, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; if ((hdr_sz(base_out, &delta, delta_end) < 0) || (hdr_sz(result_out, &delta, delta_end) < 0)) return -1; return 0; } #define DELTA_HEADER_BUFFER_LEN 16 int git_delta_read_header_fromstream( size_t *base_sz, size_t *res_sz, git_packfile_stream *stream) { static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN; unsigned char buffer[DELTA_HEADER_BUFFER_LEN]; const unsigned char *delta, *delta_end; size_t len; ssize_t read; len = read = 0; while (len < buffer_len) { read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len); if (read == 0) break; if (read == GIT_EBUFS) continue; len += read; } delta = buffer; delta_end = delta + len; if ((hdr_sz(base_sz, &delta, delta_end) < 0) || (hdr_sz(res_sz, &delta, delta_end) < 0)) return -1; return 0; } int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_113_0
crossvul-cpp_data_good_1056_0
/* * fs/cifs/smb2pdu.c * * Copyright (C) International Business Machines Corp., 2009, 2013 * Etersoft, 2012 * Author(s): Steve French (sfrench@us.ibm.com) * Pavel Shilovsky (pshilovsky@samba.org) 2012 * * Contains the routines for constructing the SMB2 PDUs themselves * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */ /* Note that there are handle based routines which must be */ /* treated slightly differently for reconnection purposes since we never */ /* want to reuse a stale file handle and only the caller knows the file info */ #include <linux/fs.h> #include <linux/kernel.h> #include <linux/vfs.h> #include <linux/task_io_accounting_ops.h> #include <linux/uaccess.h> #include <linux/uuid.h> #include <linux/pagemap.h> #include <linux/xattr.h> #include "smb2pdu.h" #include "cifsglob.h" #include "cifsacl.h" #include "cifsproto.h" #include "smb2proto.h" #include "cifs_unicode.h" #include "cifs_debug.h" #include "ntlmssp.h" #include "smb2status.h" #include "smb2glob.h" #include "cifspdu.h" #include "cifs_spnego.h" #include "smbdirect.h" #include "trace.h" #ifdef CONFIG_CIFS_DFS_UPCALL #include "dfs_cache.h" #endif /* * The following table defines the expected "StructureSize" of SMB2 requests * in order by SMB2 command. This is similar to "wct" in SMB/CIFS requests. * * Note that commands are defined in smb2pdu.h in le16 but the array below is * indexed by command in host byte order. */ static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = { /* SMB2_NEGOTIATE */ 36, /* SMB2_SESSION_SETUP */ 25, /* SMB2_LOGOFF */ 4, /* SMB2_TREE_CONNECT */ 9, /* SMB2_TREE_DISCONNECT */ 4, /* SMB2_CREATE */ 57, /* SMB2_CLOSE */ 24, /* SMB2_FLUSH */ 24, /* SMB2_READ */ 49, /* SMB2_WRITE */ 49, /* SMB2_LOCK */ 48, /* SMB2_IOCTL */ 57, /* SMB2_CANCEL */ 4, /* SMB2_ECHO */ 4, /* SMB2_QUERY_DIRECTORY */ 33, /* SMB2_CHANGE_NOTIFY */ 32, /* SMB2_QUERY_INFO */ 41, /* SMB2_SET_INFO */ 33, /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */ }; int smb3_encryption_required(const struct cifs_tcon *tcon) { if (!tcon) return 0; if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) || (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA)) return 1; if (tcon->seal && (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)) return 1; return 0; } static void smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd, const struct cifs_tcon *tcon) { shdr->ProtocolId = SMB2_PROTO_NUMBER; shdr->StructureSize = cpu_to_le16(64); shdr->Command = smb2_cmd; if (tcon && tcon->ses && tcon->ses->server) { struct TCP_Server_Info *server = tcon->ses->server; spin_lock(&server->req_lock); /* Request up to 10 credits but don't go over the limit. */ if (server->credits >= server->max_credits) shdr->CreditRequest = cpu_to_le16(0); else shdr->CreditRequest = cpu_to_le16( min_t(int, server->max_credits - server->credits, 10)); spin_unlock(&server->req_lock); } else { shdr->CreditRequest = cpu_to_le16(2); } shdr->ProcessId = cpu_to_le32((__u16)current->tgid); if (!tcon) goto out; /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */ /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */ if ((tcon->ses) && (tcon->ses->server) && (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU)) shdr->CreditCharge = cpu_to_le16(1); /* else CreditCharge MBZ */ shdr->TreeId = tcon->tid; /* Uid is not converted */ if (tcon->ses) shdr->SessionId = tcon->ses->Suid; /* * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have * to pass the path on the Open SMB prefixed by \\server\share. * Not sure when we would need to do the augmented path (if ever) and * setting this flag breaks the SMB2 open operation since it is * illegal to send an empty path name (without \\server\share prefix) * when the DFS flag is set in the SMB open header. We could * consider setting the flag on all operations other than open * but it is safer to net set it for now. */ /* if (tcon->share_flags & SHI1005_FLAGS_DFS) shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */ if (tcon->ses && tcon->ses->server && tcon->ses->server->sign && !smb3_encryption_required(tcon)) shdr->Flags |= SMB2_FLAGS_SIGNED; out: return; } #ifdef CONFIG_CIFS_DFS_UPCALL static int __smb2_reconnect(const struct nls_table *nlsc, struct cifs_tcon *tcon) { int rc; struct dfs_cache_tgt_list tl; struct dfs_cache_tgt_iterator *it = NULL; char *tree; const char *tcp_host; size_t tcp_host_len; const char *dfs_host; size_t dfs_host_len; tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL); if (!tree) return -ENOMEM; if (tcon->ipc) { scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", tcon->ses->server->hostname); rc = SMB2_tcon(0, tcon->ses, tree, tcon, nlsc); goto out; } if (!tcon->dfs_path) { rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nlsc); goto out; } rc = dfs_cache_noreq_find(tcon->dfs_path + 1, NULL, &tl); if (rc) goto out; extract_unc_hostname(tcon->ses->server->hostname, &tcp_host, &tcp_host_len); for (it = dfs_cache_get_tgt_iterator(&tl); it; it = dfs_cache_get_next_tgt(&tl, it)) { const char *tgt = dfs_cache_get_tgt_name(it); extract_unc_hostname(tgt, &dfs_host, &dfs_host_len); if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) { cifs_dbg(FYI, "%s: skipping %.*s, doesn't match %.*s", __func__, (int)dfs_host_len, dfs_host, (int)tcp_host_len, tcp_host); continue; } scnprintf(tree, MAX_TREE_SIZE, "\\%s", tgt); rc = SMB2_tcon(0, tcon->ses, tree, tcon, nlsc); if (!rc) break; if (rc == -EREMOTE) break; } if (!rc) { if (it) rc = dfs_cache_noreq_update_tgthint(tcon->dfs_path + 1, it); else rc = -ENOENT; } dfs_cache_free_tgts(&tl); out: kfree(tree); return rc; } #else static inline int __smb2_reconnect(const struct nls_table *nlsc, struct cifs_tcon *tcon) { return SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nlsc); } #endif static int smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon) { int rc; struct nls_table *nls_codepage; struct cifs_ses *ses; struct TCP_Server_Info *server; int retries; /* * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so * check for tcp and smb session status done differently * for those three - in the calling routine. */ if (tcon == NULL) return 0; if (smb2_command == SMB2_TREE_CONNECT) return 0; if (tcon->tidStatus == CifsExiting) { /* * only tree disconnect, open, and write, * (and ulogoff which does not have tcon) * are allowed as we start force umount. */ if ((smb2_command != SMB2_WRITE) && (smb2_command != SMB2_CREATE) && (smb2_command != SMB2_TREE_DISCONNECT)) { cifs_dbg(FYI, "can not send cmd %d while umounting\n", smb2_command); return -ENODEV; } } if ((!tcon->ses) || (tcon->ses->status == CifsExiting) || (!tcon->ses->server)) return -EIO; ses = tcon->ses; server = ses->server; retries = server->nr_targets; /* * Give demultiplex thread up to 10 seconds to each target available for * reconnect -- should be greater than cifs socket timeout which is 7 * seconds. */ while (server->tcpStatus == CifsNeedReconnect) { /* * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE * here since they are implicitly done when session drops. */ switch (smb2_command) { /* * BB Should we keep oplock break and add flush to exceptions? */ case SMB2_TREE_DISCONNECT: case SMB2_CANCEL: case SMB2_CLOSE: case SMB2_OPLOCK_BREAK: return -EAGAIN; } rc = wait_event_interruptible_timeout(server->response_q, (server->tcpStatus != CifsNeedReconnect), 10 * HZ); if (rc < 0) { cifs_dbg(FYI, "%s: aborting reconnect due to a received" " signal by the process\n", __func__); return -ERESTARTSYS; } /* are we still trying to reconnect? */ if (server->tcpStatus != CifsNeedReconnect) break; if (--retries) continue; /* * on "soft" mounts we wait once. Hard mounts keep * retrying until process is killed or server comes * back on-line */ if (!tcon->retry) { cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n"); return -EHOSTDOWN; } retries = server->nr_targets; } if (!tcon->ses->need_reconnect && !tcon->need_reconnect) return 0; nls_codepage = load_nls_default(); /* * need to prevent multiple threads trying to simultaneously reconnect * the same SMB session */ mutex_lock(&tcon->ses->session_mutex); /* * Recheck after acquire mutex. If another thread is negotiating * and the server never sends an answer the socket will be closed * and tcpStatus set to reconnect. */ if (server->tcpStatus == CifsNeedReconnect) { rc = -EHOSTDOWN; mutex_unlock(&tcon->ses->session_mutex); goto out; } rc = cifs_negotiate_protocol(0, tcon->ses); if (!rc && tcon->ses->need_reconnect) rc = cifs_setup_session(0, tcon->ses, nls_codepage); if (rc || !tcon->need_reconnect) { mutex_unlock(&tcon->ses->session_mutex); goto out; } cifs_mark_open_files_invalid(tcon); if (tcon->use_persistent) tcon->need_reopen_files = true; rc = __smb2_reconnect(nls_codepage, tcon); mutex_unlock(&tcon->ses->session_mutex); cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc); if (rc) { /* If sess reconnected but tcon didn't, something strange ... */ printk_once(KERN_WARNING "reconnect tcon failed rc = %d\n", rc); goto out; } if (smb2_command != SMB2_INTERNAL_CMD) queue_delayed_work(cifsiod_wq, &server->reconnect, 0); atomic_inc(&tconInfoReconnectCount); out: /* * Check if handle based operation so we know whether we can continue * or not without returning to caller to reset file handle. */ /* * BB Is flush done by server on drop of tcp session? Should we special * case it and skip above? */ switch (smb2_command) { case SMB2_FLUSH: case SMB2_READ: case SMB2_WRITE: case SMB2_LOCK: case SMB2_IOCTL: case SMB2_QUERY_DIRECTORY: case SMB2_CHANGE_NOTIFY: case SMB2_QUERY_INFO: case SMB2_SET_INFO: rc = -EAGAIN; } unload_nls(nls_codepage); return rc; } static void fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf, unsigned int *total_len) { struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf; /* lookup word count ie StructureSize from table */ __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)]; /* * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of * largest operations (Create) */ memset(buf, 0, 256); smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon); spdu->StructureSize2 = cpu_to_le16(parmsize); *total_len = parmsize + sizeof(struct smb2_sync_hdr); } /* * Allocate and return pointer to an SMB request hdr, and set basic * SMB information in the SMB header. If the return code is zero, this * function must have filled in request_buf pointer. */ static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon, void **request_buf, unsigned int *total_len) { int rc; rc = smb2_reconnect(smb2_command, tcon); if (rc) return rc; /* BB eventually switch this to SMB2 specific small buf size */ if (smb2_command == SMB2_SET_INFO) *request_buf = cifs_buf_get(); else *request_buf = cifs_small_buf_get(); if (*request_buf == NULL) { /* BB should we add a retry in here if not a writepage? */ return -ENOMEM; } fill_small_buf(smb2_command, tcon, (struct smb2_sync_hdr *)(*request_buf), total_len); if (tcon != NULL) { uint16_t com_code = le16_to_cpu(smb2_command); cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]); cifs_stats_inc(&tcon->num_smbs_sent); } return rc; } #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES cpu_to_le16(1) #define SMB2_ENCRYPTION_CAPABILITIES cpu_to_le16(2) #define SMB2_POSIX_EXTENSIONS_AVAILABLE cpu_to_le16(0x100) static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(38); pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1); pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE); get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE); pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512; } static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES; pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + le16 cipher */ pneg_ctxt->CipherCount = cpu_to_le16(1); /* pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;*/ /* not supported yet */ pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_CCM; } static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt) { pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE; pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN); /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */ pneg_ctxt->Name[0] = 0x93; pneg_ctxt->Name[1] = 0xAD; pneg_ctxt->Name[2] = 0x25; pneg_ctxt->Name[3] = 0x50; pneg_ctxt->Name[4] = 0x9C; pneg_ctxt->Name[5] = 0xB4; pneg_ctxt->Name[6] = 0x11; pneg_ctxt->Name[7] = 0xE7; pneg_ctxt->Name[8] = 0xB4; pneg_ctxt->Name[9] = 0x23; pneg_ctxt->Name[10] = 0x83; pneg_ctxt->Name[11] = 0xDE; pneg_ctxt->Name[12] = 0x96; pneg_ctxt->Name[13] = 0x8B; pneg_ctxt->Name[14] = 0xCD; pneg_ctxt->Name[15] = 0x7C; } static void assemble_neg_contexts(struct smb2_negotiate_req *req, unsigned int *total_len) { char *pneg_ctxt = (char *)req; unsigned int ctxt_len; if (*total_len > 200) { /* In case length corrupted don't want to overrun smb buffer */ cifs_dbg(VFS, "Bad frame length assembling neg contexts\n"); return; } /* * round up total_len of fixed part of SMB3 negotiate request to 8 * byte boundary before adding negotiate contexts */ *total_len = roundup(*total_len, 8); pneg_ctxt = (*total_len) + (char *)req; req->NegotiateContextOffset = cpu_to_le32(*total_len); build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt); ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_preauth_neg_context), 8) * 8; *total_len += ctxt_len; pneg_ctxt += ctxt_len; build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt); ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_encryption_neg_context), 8) * 8; *total_len += ctxt_len; pneg_ctxt += ctxt_len; build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt); *total_len += sizeof(struct smb2_posix_neg_context); req->NegotiateContextCount = cpu_to_le16(3); } static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt) { unsigned int len = le16_to_cpu(ctxt->DataLength); /* If invalid preauth context warn but use what we requested, SHA-512 */ if (len < MIN_PREAUTH_CTXT_DATA_LEN) { printk_once(KERN_WARNING "server sent bad preauth context\n"); return; } if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1) printk_once(KERN_WARNING "illegal SMB3 hash algorithm count\n"); if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512) printk_once(KERN_WARNING "unknown SMB3 hash algorithm\n"); } static int decode_encrypt_ctx(struct TCP_Server_Info *server, struct smb2_encryption_neg_context *ctxt) { unsigned int len = le16_to_cpu(ctxt->DataLength); cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len); if (len < MIN_ENCRYPT_CTXT_DATA_LEN) { printk_once(KERN_WARNING "server sent bad crypto ctxt len\n"); return -EINVAL; } if (le16_to_cpu(ctxt->CipherCount) != 1) { printk_once(KERN_WARNING "illegal SMB3.11 cipher count\n"); return -EINVAL; } cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0])); if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) && (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM)) { printk_once(KERN_WARNING "invalid SMB3.11 cipher returned\n"); return -EINVAL; } server->cipher_type = ctxt->Ciphers[0]; server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION; return 0; } static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp, struct TCP_Server_Info *server, unsigned int len_of_smb) { struct smb2_neg_context *pctx; unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset); unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount); unsigned int len_of_ctxts, i; int rc = 0; cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt); if (len_of_smb <= offset) { cifs_dbg(VFS, "Invalid response: negotiate context offset\n"); return -EINVAL; } len_of_ctxts = len_of_smb - offset; for (i = 0; i < ctxt_cnt; i++) { int clen; /* check that offset is not beyond end of SMB */ if (len_of_ctxts == 0) break; if (len_of_ctxts < sizeof(struct smb2_neg_context)) break; pctx = (struct smb2_neg_context *)(offset + (char *)rsp); clen = le16_to_cpu(pctx->DataLength); if (clen > len_of_ctxts) break; if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) decode_preauth_context( (struct smb2_preauth_neg_context *)pctx); else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) rc = decode_encrypt_ctx(server, (struct smb2_encryption_neg_context *)pctx); else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) server->posix_ext_supported = true; else cifs_dbg(VFS, "unknown negcontext of type %d ignored\n", le16_to_cpu(pctx->ContextType)); if (rc) break; /* offsets must be 8 byte aligned */ clen = (clen + 7) & ~0x7; offset += clen + sizeof(struct smb2_neg_context); len_of_ctxts -= clen; } return rc; } static struct create_posix * create_posix_buf(umode_t mode) { struct create_posix *buf; buf = kzalloc(sizeof(struct create_posix), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct create_posix, Mode)); buf->ccontext.DataLength = cpu_to_le32(4); buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct create_posix, Name)); buf->ccontext.NameLength = cpu_to_le16(16); /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */ buf->Name[0] = 0x93; buf->Name[1] = 0xAD; buf->Name[2] = 0x25; buf->Name[3] = 0x50; buf->Name[4] = 0x9C; buf->Name[5] = 0xB4; buf->Name[6] = 0x11; buf->Name[7] = 0xE7; buf->Name[8] = 0xB4; buf->Name[9] = 0x23; buf->Name[10] = 0x83; buf->Name[11] = 0xDE; buf->Name[12] = 0x96; buf->Name[13] = 0x8B; buf->Name[14] = 0xCD; buf->Name[15] = 0x7C; buf->Mode = cpu_to_le32(mode); cifs_dbg(FYI, "mode on posix create 0%o", mode); return buf; } static int add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = create_posix_buf(mode); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_posix); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32( sizeof(struct smb2_create_req) + iov[num - 1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix)); *num_iovec = num + 1; return 0; } /* * * SMB2 Worker functions follow: * * The general structure of the worker functions is: * 1) Call smb2_init (assembles SMB2 header) * 2) Initialize SMB2 command specific fields in fixed length area of SMB * 3) Call smb_sendrcv2 (sends request on socket and waits for response) * 4) Decode SMB2 command specific fields in the fixed length area * 5) Decode variable length data area (if any for this SMB2 command type) * 6) Call free smb buffer * 7) return * */ int SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses) { struct smb_rqst rqst; struct smb2_negotiate_req *req; struct smb2_negotiate_rsp *rsp; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server = ses->server; int blob_offset, blob_length; char *security_blob; int flags = CIFS_NEG_OP; unsigned int total_len; cifs_dbg(FYI, "Negotiate protocol\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len); if (rc) return rc; req->sync_hdr.SessionId = 0; memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID); req->DialectCount = cpu_to_le16(2); total_len += 4; } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID); req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID); req->DialectCount = cpu_to_le16(4); total_len += 8; } else { /* otherwise send specific dialect */ req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id); req->DialectCount = cpu_to_le16(1); total_len += 2; } /* only one of SMB2 signing flags may be set in SMB2 request */ if (ses->sign) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else req->SecurityMode = 0; req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities); /* ClientGUID must be zero for SMB2.02 dialect */ if (ses->server->vals->protocol_id == SMB20_PROT_ID) memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE); else { memcpy(req->ClientGUID, server->client_guid, SMB2_CLIENT_GUID_SIZE); if ((ses->server->vals->protocol_id == SMB311_PROT_ID) || (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0)) assemble_neg_contexts(req, &total_len); } iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base; /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ if (rc == -EOPNOTSUPP) { cifs_dbg(VFS, "Dialect not supported by server. Consider " "specifying vers=1.0 or vers=2.0 on mount for accessing" " older servers\n"); goto neg_exit; } else if (rc != 0) goto neg_exit; if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, "SMB2 dialect returned but not requested\n"); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { cifs_dbg(VFS, "SMB2.1 dialect returned but not requested\n"); return -EIO; } } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, "SMB2 dialect returned but not requested\n"); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { /* ops set to 3.0 by default for default so update */ ses->server->ops = &smb21_operations; ses->server->vals = &smb21_values; } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) { ses->server->ops = &smb311_operations; ses->server->vals = &smb311_values; } } else if (le16_to_cpu(rsp->DialectRevision) != ses->server->vals->protocol_id) { /* if requested single dialect ensure returned dialect matched */ cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n", le16_to_cpu(rsp->DialectRevision)); return -EIO; } cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode); if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) cifs_dbg(FYI, "negotiated smb2.1 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.0 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.02 dialect\n"); else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n"); else { cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n", le16_to_cpu(rsp->DialectRevision)); rc = -EIO; goto neg_exit; } server->dialect = le16_to_cpu(rsp->DialectRevision); /* * Keep a copy of the hash after negprot. This hash will be * the starting hash value for all sessions made from this * server. */ memcpy(server->preauth_sha_hash, ses->preauth_sha_hash, SMB2_PREAUTH_HASH_SIZE); /* SMB2 only has an extended negflavor */ server->negflavor = CIFS_NEGFLAVOR_EXTENDED; /* set it to the maximum buffer size value we can send with 1 credit */ server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize), SMB2_MAX_BUFFER_SIZE); server->max_read = le32_to_cpu(rsp->MaxReadSize); server->max_write = le32_to_cpu(rsp->MaxWriteSize); server->sec_mode = le16_to_cpu(rsp->SecurityMode); if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode) cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n", server->sec_mode); server->capabilities = le32_to_cpu(rsp->Capabilities); /* Internal types */ server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES; security_blob = smb2_get_data_area_len(&blob_offset, &blob_length, (struct smb2_sync_hdr *)rsp); /* * See MS-SMB2 section 2.2.4: if no blob, client picks default which * for us will be * ses->sectype = RawNTLMSSP; * but for time being this is our only auth choice so doesn't matter. * We just found a server which sets blob length to zero expecting raw. */ if (blob_length == 0) { cifs_dbg(FYI, "missing security blob on negprot\n"); server->sec_ntlmssp = true; } rc = cifs_enable_signing(server, ses->sign); if (rc) goto neg_exit; if (blob_length) { rc = decode_negTokenInit(security_blob, blob_length, server); if (rc == 1) rc = 0; else if (rc == 0) rc = -EIO; } if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) { if (rsp->NegotiateContextCount) rc = smb311_decode_neg_context(rsp, server, rsp_iov.iov_len); else cifs_dbg(VFS, "Missing expected negotiate contexts\n"); } neg_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon) { int rc; struct validate_negotiate_info_req *pneg_inbuf; struct validate_negotiate_info_rsp *pneg_rsp = NULL; u32 rsplen; u32 inbuflen; /* max of 4 dialects */ cifs_dbg(FYI, "validate negotiate\n"); /* In SMB3.11 preauth integrity supersedes validate negotiate */ if (tcon->ses->server->dialect == SMB311_PROT_ID) return 0; /* * validation ioctl must be signed, so no point sending this if we * can not sign it (ie are not known user). Even if signing is not * required (enabled but not negotiated), in those cases we selectively * sign just this, the first and only signed request on a connection. * Having validation of negotiate info helps reduce attack vectors. */ if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) return 0; /* validation requires signing */ if (tcon->ses->user_name == NULL) { cifs_dbg(FYI, "Can't validate negotiate: null user mount\n"); return 0; /* validation requires signing */ } if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL) cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n"); pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS); if (!pneg_inbuf) return -ENOMEM; pneg_inbuf->Capabilities = cpu_to_le32(tcon->ses->server->vals->req_capabilities); memcpy(pneg_inbuf->Guid, tcon->ses->server->client_guid, SMB2_CLIENT_GUID_SIZE); if (tcon->ses->sign) pneg_inbuf->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) pneg_inbuf->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else pneg_inbuf->SecurityMode = 0; if (strcmp(tcon->ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID); pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID); pneg_inbuf->DialectCount = cpu_to_le16(2); /* structure is big enough for 3 dialects, sending only 2 */ inbuflen = sizeof(*pneg_inbuf) - (2 * sizeof(pneg_inbuf->Dialects[0])); } else if (strcmp(tcon->ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID); pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID); pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID); pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID); pneg_inbuf->DialectCount = cpu_to_le16(4); /* structure is big enough for 3 dialects */ inbuflen = sizeof(*pneg_inbuf); } else { /* otherwise specific dialect was requested */ pneg_inbuf->Dialects[0] = cpu_to_le16(tcon->ses->server->vals->protocol_id); pneg_inbuf->DialectCount = cpu_to_le16(1); /* structure is big enough for 3 dialects, sending only 1 */ inbuflen = sizeof(*pneg_inbuf) - sizeof(pneg_inbuf->Dialects[0]) * 2; } rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID, FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */, (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize, (char **)&pneg_rsp, &rsplen); if (rc == -EOPNOTSUPP) { /* * Old Windows versions or Netapp SMB server can return * not supported error. Client should accept it. */ cifs_dbg(VFS, "Server does not support validate negotiate\n"); return 0; } else if (rc != 0) { cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc); rc = -EIO; goto out_free_inbuf; } rc = -EIO; if (rsplen != sizeof(*pneg_rsp)) { cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n", rsplen); /* relax check since Mac returns max bufsize allowed on ioctl */ if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp)) goto out_free_rsp; } /* check validate negotiate info response matches what we got earlier */ if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->dialect)) goto vneg_out; if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode)) goto vneg_out; /* do not validate server guid because not saved at negprot time yet */ if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND | SMB2_LARGE_FILES) != tcon->ses->server->capabilities) goto vneg_out; /* validate negotiate successful */ rc = 0; cifs_dbg(FYI, "validate negotiate info successful\n"); goto out_free_rsp; vneg_out: cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n"); out_free_rsp: kfree(pneg_rsp); out_free_inbuf: kfree(pneg_inbuf); return rc; } enum securityEnum smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested) { switch (requested) { case Kerberos: case RawNTLMSSP: return requested; case NTLMv2: return RawNTLMSSP; case Unspecified: if (server->sec_ntlmssp && (global_secflags & CIFSSEC_MAY_NTLMSSP)) return RawNTLMSSP; if ((server->sec_kerberos || server->sec_mskerberos) && (global_secflags & CIFSSEC_MAY_KRB5)) return Kerberos; /* Fallthrough */ default: return Unspecified; } } struct SMB2_sess_data { unsigned int xid; struct cifs_ses *ses; struct nls_table *nls_cp; void (*func)(struct SMB2_sess_data *); int result; u64 previous_session; /* we will send the SMB in three pieces: * a fixed length beginning part, an optional * SPNEGO blob (which can be zero length), and a * last part which will include the strings * and rest of bcc area. This allows us to avoid * a large buffer 17K allocation */ int buf0_type; struct kvec iov[2]; }; static int SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct TCP_Server_Info *server = ses->server; unsigned int total_len; rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, (void **) &req, &total_len); if (rc) return rc; /* First session, not a reauthenticate */ req->sync_hdr.SessionId = 0; /* if reconnect, we need to send previous sess id, otherwise it is 0 */ req->PreviousSessionId = sess_data->previous_session; req->Flags = 0; /* MBZ */ /* enough to enable echos and oplocks and one max size write */ req->sync_hdr.CreditRequest = cpu_to_le16(130); /* only one of SMB2 signing flags may be set in SMB2 request */ if (server->sign) req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED; else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */ req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED; else req->SecurityMode = 0; req->Capabilities = 0; req->Channel = 0; /* MBZ */ sess_data->iov[0].iov_base = (char *)req; /* 1 for pad */ sess_data->iov[0].iov_len = total_len - 1; /* * This variable will be used to clear the buffer * allocated above in case of any error in the calling function. */ sess_data->buf0_type = CIFS_SMALL_BUFFER; return 0; } static void SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data) { free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base); sess_data->buf0_type = CIFS_NO_BUFFER; } static int SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data) { int rc; struct smb_rqst rqst; struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base; struct kvec rsp_iov = { NULL, 0 }; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->SecurityBufferOffset = cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */); req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len); memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = sess_data->iov; rqst.rq_nvec = 2; /* BB add code to build os and lm fields */ rc = cifs_send_recv(sess_data->xid, sess_data->ses, &rqst, &sess_data->buf0_type, CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov); cifs_small_buf_release(sess_data->iov[0].iov_base); memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec)); return rc; } static int SMB2_sess_establish_session(struct SMB2_sess_data *sess_data) { int rc = 0; struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (ses->server->ops->generate_signingkey) { rc = ses->server->ops->generate_signingkey(ses); if (rc) { cifs_dbg(FYI, "SMB3 session key generation failed\n"); mutex_unlock(&ses->server->srv_mutex); return rc; } } if (!ses->server->session_estab) { ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "SMB2/3 session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); return rc; } #ifdef CONFIG_CIFS_UPCALL static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct cifs_spnego_msg *msg; struct key *spnego_key = NULL; struct smb2_sess_setup_rsp *rsp = NULL; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; spnego_key = cifs_get_spnego_key(ses); if (IS_ERR(spnego_key)) { rc = PTR_ERR(spnego_key); spnego_key = NULL; goto out; } msg = spnego_key->payload.data[0]; /* * check version field to make sure that cifs.upcall is * sending us a response in an expected form */ if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) { cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d", CIFS_SPNEGO_UPCALL_VERSION, msg->version); rc = -EKEYREJECTED; goto out_put_spnego_key; } ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len, GFP_KERNEL); if (!ses->auth_key.response) { cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory", msg->sesskey_len); rc = -ENOMEM; goto out_put_spnego_key; } ses->auth_key.len = msg->sesskey_len; sess_data->iov[1].iov_base = msg->data + msg->sesskey_len; sess_data->iov[1].iov_len = msg->secblob_len; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out_put_spnego_key; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); rc = SMB2_sess_establish_session(sess_data); out_put_spnego_key: key_invalidate(spnego_key); key_put(spnego_key); out: sess_data->result = rc; sess_data->func = NULL; SMB2_sess_free_buffer(sess_data); } #else static void SMB2_auth_kerberos(struct SMB2_sess_data *sess_data) { cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n"); sess_data->result = -EOPNOTSUPP; sess_data->func = NULL; } #endif static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data); static void SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_rsp *rsp = NULL; char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; /* * If memory allocation is successful, caller of this function * frees it. */ ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL); if (!ses->ntlmssp) { rc = -ENOMEM; goto out_err; } ses->ntlmssp->sesskey_per_smbsess = true; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out_err; ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE), GFP_KERNEL); if (ntlmssp_blob == NULL) { rc = -ENOMEM; goto out; } build_ntlmssp_negotiate_blob(ntlmssp_blob, ses); if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } else { blob_length = sizeof(struct _NEGOTIATE_MESSAGE); /* with raw NTLMSSP we don't encapsulate in SPNEGO */ } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; /* If true, rc here is expected and not an error */ if (sess_data->buf0_type != CIFS_NO_BUFFER && rsp->sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED) rc = 0; if (rc) goto out; if (offsetof(struct smb2_sess_setup_rsp, Buffer) != le16_to_cpu(rsp->SecurityBufferOffset)) { cifs_dbg(VFS, "Invalid security buffer offset %d\n", le16_to_cpu(rsp->SecurityBufferOffset)); rc = -EIO; goto out; } rc = decode_ntlmssp_challenge(rsp->Buffer, le16_to_cpu(rsp->SecurityBufferLength), ses); if (rc) goto out; cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n"); ses->Suid = rsp->sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); if (!rc) { sess_data->result = 0; sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate; return; } out_err: kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static void SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct smb2_sess_setup_rsp *rsp = NULL; unsigned char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base; req->sync_hdr.SessionId = ses->Suid; rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses, sess_data->nls_cp); if (rc) { cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc); goto out; } if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); rc = SMB2_sess_establish_session(sess_data); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } static int SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data) { int type; type = smb2_select_sectype(ses->server, ses->sectype); cifs_dbg(FYI, "sess setup type %d\n", type); if (type == Unspecified) { cifs_dbg(VFS, "Unable to select appropriate authentication method!"); return -EINVAL; } switch (type) { case Kerberos: sess_data->func = SMB2_auth_kerberos; break; case RawNTLMSSP: sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate; break; default: cifs_dbg(VFS, "secType %d not supported!\n", type); return -EOPNOTSUPP; } return 0; } int SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses, const struct nls_table *nls_cp) { int rc = 0; struct TCP_Server_Info *server = ses->server; struct SMB2_sess_data *sess_data; cifs_dbg(FYI, "Session Setup\n"); if (!server) { WARN(1, "%s: server is NULL!\n", __func__); return -EIO; } sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL); if (!sess_data) return -ENOMEM; rc = SMB2_select_sec(ses, sess_data); if (rc) goto out; sess_data->xid = xid; sess_data->ses = ses; sess_data->buf0_type = CIFS_NO_BUFFER; sess_data->nls_cp = (struct nls_table *) nls_cp; sess_data->previous_session = ses->Suid; /* * Initialize the session hash with the server one. */ memcpy(ses->preauth_sha_hash, ses->server->preauth_sha_hash, SMB2_PREAUTH_HASH_SIZE); while (sess_data->func) sess_data->func(sess_data); if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign)) cifs_dbg(VFS, "signing requested but authenticated as guest\n"); rc = sess_data->result; out: kfree(sess_data); return rc; } int SMB2_logoff(const unsigned int xid, struct cifs_ses *ses) { struct smb_rqst rqst; struct smb2_logoff_req *req; /* response is also trivial struct */ int rc = 0; struct TCP_Server_Info *server; int flags = 0; unsigned int total_len; struct kvec iov[1]; struct kvec rsp_iov; int resp_buf_type; cifs_dbg(FYI, "disconnect session %p\n", ses); if (ses && (ses->server)) server = ses->server; else return -EIO; /* no need to send SMB logoff if uid already closed due to reconnect */ if (ses->need_reconnect) goto smb2_session_already_dead; rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, (void **) &req, &total_len); if (rc) return rc; /* since no tcon, smb2_init can not do this, so do here */ req->sync_hdr.SessionId = ses->Suid; if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) flags |= CIFS_TRANSFORM_REQ; else if (server->sign) req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED; flags |= CIFS_NO_RESP; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ smb2_session_already_dead: return rc; } static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code) { cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]); } #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */) /* These are similar values to what Windows uses */ static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon) { tcon->max_chunks = 256; tcon->max_bytes_chunk = 1048576; tcon->max_bytes_copy = 16777216; } int SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb_rqst rqst; struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov = { NULL, 0 }; int rc = 0; int resp_buftype; int unc_path_len; __le16 *unc_path = NULL; int flags = 0; unsigned int total_len; cifs_dbg(FYI, "TCON\n"); if (!(ses->server) || !tree) return -EIO; unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */ tcon->tid = 0; atomic_set(&tcon->num_remote_opens, 0); rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, (void **) &req, &total_len); if (rc) { kfree(unc_path); return rc; } if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; /* 1 for pad */ iov[0].iov_len = total_len - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; /* * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1 * (Samba servers don't always set the flag so also check if null user) */ if ((ses->server->dialect == SMB311_PROT_ID) && !smb3_encryption_required(tcon) && !(ses->session_flags & (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) && ((ses->user_name != NULL) || (ses->sectype == Kerberos))) req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 2; /* Need 64 for max size write so ask for more in case not there yet */ req->sync_hdr.CreditRequest = cpu_to_le16(64); rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base; trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc); if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } switch (rsp->ShareType) { case SMB2_SHARE_TYPE_DISK: cifs_dbg(FYI, "connection to disk share\n"); break; case SMB2_SHARE_TYPE_PIPE: tcon->pipe = true; cifs_dbg(FYI, "connection to pipe share\n"); break; case SMB2_SHARE_TYPE_PRINT: tcon->print = true; cifs_dbg(FYI, "connection to printer\n"); break; default: cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->sync_hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); if (tcon->seal && !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)) cifs_dbg(VFS, "Encryption is requested but not supported\n"); init_copy_chunk_defaults(tcon); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp && rsp->sync_hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); } goto tcon_exit; } int SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon) { struct smb_rqst rqst; struct smb2_tree_disconnect_req *req; /* response is trivial */ int rc = 0; struct cifs_ses *ses = tcon->ses; int flags = 0; unsigned int total_len; struct kvec iov[1]; struct kvec rsp_iov; int resp_buf_type; cifs_dbg(FYI, "Tree Disconnect\n"); if (!ses || !(ses->server)) return -EIO; if ((tcon->need_reconnect) || (tcon->ses->need_reconnect)) return 0; rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; flags |= CIFS_NO_RESP; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); if (rc) cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE); return rc; } static struct create_durable * create_durable_buf(void) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'Q'; return buf; } static struct create_durable * create_reconnect_durable_buf(struct cifs_fid *fid) { struct create_durable *buf; buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable, Data)); buf->ccontext.DataLength = cpu_to_le32(16); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->Data.Fid.PersistentFileId = fid->persistent_fid; buf->Data.Fid.VolatileFileId = fid->volatile_fid; /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = 'n'; buf->Name[3] = 'C'; return buf; } __u8 smb2_parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp, unsigned int *epoch, char *lease_key) { char *data_offset; struct create_context *cc; unsigned int next; unsigned int remaining; char *name; data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset); remaining = le32_to_cpu(rsp->CreateContextsLength); cc = (struct create_context *)data_offset; while (remaining >= sizeof(struct create_context)) { name = le16_to_cpu(cc->NameOffset) + (char *)cc; if (le16_to_cpu(cc->NameLength) == 4 && strncmp(name, "RqLs", 4) == 0) return server->ops->parse_lease_buf(cc, epoch, lease_key); next = le32_to_cpu(cc->Next); if (!next) break; remaining -= next; cc = (struct create_context *)((char *)cc + next); } return 0; } static int add_lease_context(struct TCP_Server_Info *server, struct kvec *iov, unsigned int *num_iovec, u8 *lease_key, __u8 *oplock) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = server->vals->create_lease_size; req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE; if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32( sizeof(struct smb2_create_req) + iov[num - 1].iov_len); le32_add_cpu(&req->CreateContextsLength, server->vals->create_lease_size); *num_iovec = num + 1; return 0; } static struct create_durable_v2 * create_durable_v2_buf(struct cifs_open_parms *oparms) { struct cifs_fid *pfid = oparms->fid; struct create_durable_v2 *buf; buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct create_durable_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct create_durable_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); /* * NB: Handle timeout defaults to 0, which allows server to choose * (most servers default to 120 seconds) and most clients default to 0. * This can be overridden at mount ("handletimeout=") if the user wants * a different persistent (or resilient) handle timeout for all opens * opens on a particular SMB3 mount. */ buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout); buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); generate_random_uuid(buf->dcontext.CreateGuid); memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16); /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'Q'; return buf; } static struct create_durable_handle_reconnect_v2 * create_reconnect_durable_v2_buf(struct cifs_fid *fid) { struct create_durable_handle_reconnect_v2 *buf; buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, dcontext)); buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_reconnect_context_v2)); buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2, Name)); buf->ccontext.NameLength = cpu_to_le16(4); buf->dcontext.Fid.PersistentFileId = fid->persistent_fid; buf->dcontext.Fid.VolatileFileId = fid->volatile_fid; buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT); memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16); /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */ buf->Name[0] = 'D'; buf->Name[1] = 'H'; buf->Name[2] = '2'; buf->Name[3] = 'C'; return buf; } static int add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = create_durable_v2_buf(oparms); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2)); *num_iovec = num + 1; return 0; } static int add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; /* indicate that we don't need to relock the file */ oparms->reconnect = false; iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_handle_reconnect_v2)); *num_iovec = num + 1; return 0; } static int add_durable_context(struct kvec *iov, unsigned int *num_iovec, struct cifs_open_parms *oparms, bool use_persistent) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; if (use_persistent) { if (oparms->reconnect) return add_durable_reconnect_v2_context(iov, num_iovec, oparms); else return add_durable_v2_context(iov, num_iovec, oparms); } if (oparms->reconnect) { iov[num].iov_base = create_reconnect_durable_buf(oparms->fid); /* indicate that we don't need to relock the file */ oparms->reconnect = false; } else iov[num].iov_base = create_durable_buf(); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct create_durable); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32(sizeof(struct smb2_create_req) + iov[1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable)); *num_iovec = num + 1; return 0; } /* See MS-SMB2 2.2.13.2.7 */ static struct crt_twarp_ctxt * create_twarp_buf(__u64 timewarp) { struct crt_twarp_ctxt *buf; buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL); if (!buf) return NULL; buf->ccontext.DataOffset = cpu_to_le16(offsetof (struct crt_twarp_ctxt, Timestamp)); buf->ccontext.DataLength = cpu_to_le32(8); buf->ccontext.NameOffset = cpu_to_le16(offsetof (struct crt_twarp_ctxt, Name)); buf->ccontext.NameLength = cpu_to_le16(4); /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */ buf->Name[0] = 'T'; buf->Name[1] = 'W'; buf->Name[2] = 'r'; buf->Name[3] = 'p'; buf->Timestamp = cpu_to_le64(timewarp); return buf; } /* See MS-SMB2 2.2.13.2.7 */ static int add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp) { struct smb2_create_req *req = iov[0].iov_base; unsigned int num = *num_iovec; iov[num].iov_base = create_twarp_buf(timewarp); if (iov[num].iov_base == NULL) return -ENOMEM; iov[num].iov_len = sizeof(struct crt_twarp_ctxt); if (!req->CreateContextsOffset) req->CreateContextsOffset = cpu_to_le32( sizeof(struct smb2_create_req) + iov[num - 1].iov_len); le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt)); *num_iovec = num + 1; return 0; } static int alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len, const char *treename, const __le16 *path) { int treename_len, path_len; struct nls_table *cp; const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)}; /* * skip leading "\\" */ treename_len = strlen(treename); if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\')) return -EINVAL; treename += 2; treename_len -= 2; path_len = UniStrnlen((wchar_t *)path, PATH_MAX); /* * make room for one path separator between the treename and * path */ *out_len = treename_len + 1 + path_len; /* * final path needs to be null-terminated UTF16 with a * size aligned to 8 */ *out_size = roundup((*out_len+1)*2, 8); *out_path = kzalloc(*out_size, GFP_KERNEL); if (!*out_path) return -ENOMEM; cp = load_nls_default(); cifs_strtoUTF16(*out_path, treename, treename_len, cp); UniStrcat(*out_path, sep); UniStrcat(*out_path, path); unload_nls(cp); return 0; } int smb311_posix_mkdir(const unsigned int xid, struct inode *inode, umode_t mode, struct cifs_tcon *tcon, const char *full_path, struct cifs_sb_info *cifs_sb) { struct smb_rqst rqst; struct smb2_create_req *req; struct smb2_create_rsp *rsp = NULL; struct cifs_ses *ses = tcon->ses; struct kvec iov[3]; /* make sure at least one for each open context */ struct kvec rsp_iov = {NULL, 0}; int resp_buftype; int uni_path_len; __le16 *copy_path = NULL; int copy_size; int rc = 0; unsigned int n_iov = 2; __u32 file_attributes = 0; char *pc_buf = NULL; int flags = 0; unsigned int total_len; __le16 *utf16_path = NULL; cifs_dbg(FYI, "mkdir\n"); /* resource #1: path allocation */ utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb); if (!utf16_path) return -ENOMEM; if (!ses || !(ses->server)) { rc = -EIO; goto err_free_path; } /* resource #2: request */ rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len); if (rc) goto err_free_path; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->ImpersonationLevel = IL_IMPERSONATION; req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES); /* File attributes ignored on open (used in create though) */ req->FileAttributes = cpu_to_le32(file_attributes); req->ShareAccess = FILE_SHARE_ALL_LE; req->CreateDisposition = cpu_to_le32(FILE_CREATE); req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE); iov[0].iov_base = (char *)req; /* -1 since last byte is buf[0] which is sent below (path) */ iov[0].iov_len = total_len - 1; req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req)); /* [MS-SMB2] 2.2.13 NameOffset: * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of * the SMB2 header, the file name includes a prefix that will * be processed during DFS name normalization as specified in * section 3.3.5.9. Otherwise, the file name is relative to * the share that is identified by the TreeId in the SMB2 * header. */ if (tcon->share_flags & SHI1005_FLAGS_DFS) { int name_len; req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS; rc = alloc_path_with_tree_prefix(&copy_path, &copy_size, &name_len, tcon->treeName, utf16_path); if (rc) goto err_free_req; req->NameLength = cpu_to_le16(name_len * 2); uni_path_len = copy_size; /* free before overwriting resource */ kfree(utf16_path); utf16_path = copy_path; } else { uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2; /* MUST set path len (NameLength) to 0 opening root of share */ req->NameLength = cpu_to_le16(uni_path_len - 2); if (uni_path_len % 8 != 0) { copy_size = roundup(uni_path_len, 8); copy_path = kzalloc(copy_size, GFP_KERNEL); if (!copy_path) { rc = -ENOMEM; goto err_free_req; } memcpy((char *)copy_path, (const char *)utf16_path, uni_path_len); uni_path_len = copy_size; /* free before overwriting resource */ kfree(utf16_path); utf16_path = copy_path; } } iov[1].iov_len = uni_path_len; iov[1].iov_base = utf16_path; req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE; if (tcon->posix_extensions) { /* resource #3: posix buf */ rc = add_posix_context(iov, &n_iov, mode); if (rc) goto err_free_req; pc_buf = iov[n_iov-1].iov_base; } memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_iov; trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES); /* resource #4: response buffer */ rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); if (rc) { cifs_stats_fail_inc(tcon, SMB2_CREATE_HE); trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES, rc); goto err_free_rsp_buf; } rsp = (struct smb2_create_rsp *)rsp_iov.iov_base; trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid, CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES); SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId); /* Eventually save off posix specific response info and timestaps */ err_free_rsp_buf: free_rsp_buf(resp_buftype, rsp); kfree(pc_buf); err_free_req: cifs_small_buf_release(req); err_free_path: kfree(utf16_path); return rc; } int SMB2_open_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, __u8 *oplock, struct cifs_open_parms *oparms, __le16 *path) { struct TCP_Server_Info *server = tcon->ses->server; struct smb2_create_req *req; unsigned int n_iov = 2; __u32 file_attributes = 0; int copy_size; int uni_path_len; unsigned int total_len; struct kvec *iov = rqst->rq_iov; __le16 *copy_path; int rc; rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len); if (rc) return rc; iov[0].iov_base = (char *)req; /* -1 since last byte is buf[0] which is sent below (path) */ iov[0].iov_len = total_len - 1; if (oparms->create_options & CREATE_OPTION_READONLY) file_attributes |= ATTR_READONLY; if (oparms->create_options & CREATE_OPTION_SPECIAL) file_attributes |= ATTR_SYSTEM; req->ImpersonationLevel = IL_IMPERSONATION; req->DesiredAccess = cpu_to_le32(oparms->desired_access); /* File attributes ignored on open (used in create though) */ req->FileAttributes = cpu_to_le32(file_attributes); req->ShareAccess = FILE_SHARE_ALL_LE; req->CreateDisposition = cpu_to_le32(oparms->disposition); req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK); req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req)); /* [MS-SMB2] 2.2.13 NameOffset: * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of * the SMB2 header, the file name includes a prefix that will * be processed during DFS name normalization as specified in * section 3.3.5.9. Otherwise, the file name is relative to * the share that is identified by the TreeId in the SMB2 * header. */ if (tcon->share_flags & SHI1005_FLAGS_DFS) { int name_len; req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS; rc = alloc_path_with_tree_prefix(&copy_path, &copy_size, &name_len, tcon->treeName, path); if (rc) return rc; req->NameLength = cpu_to_le16(name_len * 2); uni_path_len = copy_size; path = copy_path; } else { uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2; /* MUST set path len (NameLength) to 0 opening root of share */ req->NameLength = cpu_to_le16(uni_path_len - 2); copy_size = uni_path_len; if (copy_size % 8 != 0) copy_size = roundup(copy_size, 8); copy_path = kzalloc(copy_size, GFP_KERNEL); if (!copy_path) return -ENOMEM; memcpy((char *)copy_path, (const char *)path, uni_path_len); uni_path_len = copy_size; path = copy_path; } iov[1].iov_len = uni_path_len; iov[1].iov_base = path; if (!server->oplocks) *oplock = SMB2_OPLOCK_LEVEL_NONE; if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) || *oplock == SMB2_OPLOCK_LEVEL_NONE) req->RequestedOplockLevel = *oplock; else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) && (oparms->create_options & CREATE_NOT_FILE)) req->RequestedOplockLevel = *oplock; /* no srv lease support */ else { rc = add_lease_context(server, iov, &n_iov, oparms->fid->lease_key, oplock); if (rc) return rc; } if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) { /* need to set Next field of lease context if we request it */ if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) { struct create_context *ccontext = (struct create_context *)iov[n_iov-1].iov_base; ccontext->Next = cpu_to_le32(server->vals->create_lease_size); } rc = add_durable_context(iov, &n_iov, oparms, tcon->use_persistent); if (rc) return rc; } if (tcon->posix_extensions) { if (n_iov > 2) { struct create_context *ccontext = (struct create_context *)iov[n_iov-1].iov_base; ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len); } rc = add_posix_context(iov, &n_iov, oparms->mode); if (rc) return rc; } if (tcon->snapshot_time) { cifs_dbg(FYI, "adding snapshot context\n"); if (n_iov > 2) { struct create_context *ccontext = (struct create_context *)iov[n_iov-1].iov_base; ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len); } rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time); if (rc) return rc; } rqst->rq_nvec = n_iov; return 0; } /* rq_iov[0] is the request and is released by cifs_small_buf_release(). * All other vectors are freed by kfree(). */ void SMB2_open_free(struct smb_rqst *rqst) { int i; if (rqst && rqst->rq_iov) { cifs_small_buf_release(rqst->rq_iov[0].iov_base); for (i = 1; i < rqst->rq_nvec; i++) if (rqst->rq_iov[i].iov_base != smb2_padding) kfree(rqst->rq_iov[i].iov_base); } } int SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path, __u8 *oplock, struct smb2_file_all_info *buf, struct kvec *err_iov, int *buftype) { struct smb_rqst rqst; struct smb2_create_rsp *rsp = NULL; struct TCP_Server_Info *server; struct cifs_tcon *tcon = oparms->tcon; struct cifs_ses *ses = tcon->ses; struct kvec iov[SMB2_CREATE_IOV_SIZE]; struct kvec rsp_iov = {NULL, 0}; int resp_buftype = CIFS_NO_BUFFER; int rc = 0; int flags = 0; cifs_dbg(FYI, "create/open\n"); if (ses && (ses->server)) server = ses->server; else return -EIO; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); memset(&iov, 0, sizeof(iov)); rqst.rq_iov = iov; rqst.rq_nvec = SMB2_CREATE_IOV_SIZE; rc = SMB2_open_init(tcon, &rqst, oplock, oparms, path); if (rc) goto creat_exit; trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->create_options, oparms->desired_access); rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_create_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CREATE_HE); if (err_iov && rsp) { *err_iov = rsp_iov; *buftype = resp_buftype; resp_buftype = CIFS_NO_BUFFER; rsp = NULL; } trace_smb3_open_err(xid, tcon->tid, ses->Suid, oparms->create_options, oparms->desired_access, rc); goto creat_exit; } else trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid, oparms->create_options, oparms->desired_access); atomic_inc(&tcon->num_remote_opens); oparms->fid->persistent_fid = rsp->PersistentFileId; oparms->fid->volatile_fid = rsp->VolatileFileId; #ifdef CONFIG_CIFS_DEBUG2 oparms->fid->mid = le64_to_cpu(rsp->sync_hdr.MessageId); #endif /* CIFS_DEBUG2 */ if (buf) { memcpy(buf, &rsp->CreationTime, 32); buf->AllocationSize = rsp->AllocationSize; buf->EndOfFile = rsp->EndofFile; buf->Attributes = rsp->FileAttributes; buf->NumberOfLinks = cpu_to_le32(1); buf->DeletePending = 0; } if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE) *oplock = smb2_parse_lease_state(server, rsp, &oparms->fid->epoch, oparms->fid->lease_key); else *oplock = rsp->OplockLevel; creat_exit: SMB2_open_free(&rqst); free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_ioctl_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, u64 persistent_fid, u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data, u32 indatalen, __u32 max_response_size) { struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; unsigned int total_len; int rc; rc = smb2_plain_req_init(SMB2_IOCTL, tcon, (void **) &req, &total_len); if (rc) return rc; req->CtlCode = cpu_to_le32(opcode); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; /* * If no input data, the size of ioctl struct in * protocol spec still includes a 1 byte data buffer, * but if input data passed to ioctl, we do not * want to double count this, so we do not send * the dummy one byte of data in iovec[0] if sending * input data (in iovec[1]). */ if (indatalen) { req->InputCount = cpu_to_le32(indatalen); /* do not set InputOffset if no input data */ req->InputOffset = cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer)); rqst->rq_nvec = 2; iov[0].iov_len = total_len - 1; iov[1].iov_base = in_data; iov[1].iov_len = indatalen; } else { rqst->rq_nvec = 1; iov[0].iov_len = total_len; } req->OutputOffset = 0; req->OutputCount = 0; /* MBZ */ /* * In most cases max_response_size is set to 16K (CIFSMaxBufSize) * We Could increase default MaxOutputResponse, but that could require * more credits. Windows typically sets this smaller, but for some * ioctls it may be useful to allow server to send more. No point * limiting what the server can send as long as fits in one credit * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want * to increase this limit up in the future. * Note that for snapshot queries that servers like Azure expect that * the first query be minimal size (and just used to get the number/size * of previous versions) so response size must be specified as EXACTLY * sizeof(struct snapshot_array) which is 16 when rounded up to multiple * of eight bytes. Currently that is the only case where we set max * response size smaller. */ req->MaxOutputResponse = cpu_to_le32(max_response_size); if (is_fsctl) req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL); else req->Flags = 0; /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */ if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED; return 0; } void SMB2_ioctl_free(struct smb_rqst *rqst) { if (rqst && rqst->rq_iov) cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */ } /* * SMB2 IOCTL is used for both IOCTLs and FSCTLs */ int SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 opcode, bool is_fsctl, char *in_data, u32 indatalen, u32 max_out_data_len, char **out_data, u32 *plen /* returned data len */) { struct smb_rqst rqst; struct smb2_ioctl_rsp *rsp = NULL; struct cifs_ses *ses; struct kvec iov[SMB2_IOCTL_IOV_SIZE]; struct kvec rsp_iov = {NULL, 0}; int resp_buftype = CIFS_NO_BUFFER; int rc = 0; int flags = 0; cifs_dbg(FYI, "SMB2 IOCTL\n"); if (out_data != NULL) *out_data = NULL; /* zero out returned data len, in case of error */ if (plen) *plen = 0; if (tcon) ses = tcon->ses; else return -EIO; if (!ses || !(ses->server)) return -EIO; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); memset(&iov, 0, sizeof(iov)); rqst.rq_iov = iov; rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE; rc = SMB2_ioctl_init(tcon, &rqst, persistent_fid, volatile_fid, opcode, is_fsctl, in_data, indatalen, max_out_data_len); if (rc) goto ioctl_exit; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base; if (rc != 0) trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid, ses->Suid, 0, opcode, rc); if ((rc != 0) && (rc != -EINVAL)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } else if (rc == -EINVAL) { if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) && (opcode != FSCTL_SRV_COPYCHUNK)) { cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE); goto ioctl_exit; } } /* check if caller wants to look at return data or just return rc */ if ((plen == NULL) || (out_data == NULL)) goto ioctl_exit; *plen = le32_to_cpu(rsp->OutputCount); /* We check for obvious errors in the output buffer length and offset */ if (*plen == 0) goto ioctl_exit; /* server returned no data */ else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) { cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen); *plen = 0; rc = -EIO; goto ioctl_exit; } if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) { cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen, le32_to_cpu(rsp->OutputOffset)); *plen = 0; rc = -EIO; goto ioctl_exit; } *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset), *plen, GFP_KERNEL); if (*out_data == NULL) { rc = -ENOMEM; goto ioctl_exit; } ioctl_exit: SMB2_ioctl_free(&rqst); free_rsp_buf(resp_buftype, rsp); return rc; } /* * Individual callers to ioctl worker function follow */ int SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { int rc; struct compress_ioctl fsctl_input; char *ret_data = NULL; fsctl_input.CompressionState = cpu_to_le16(COMPRESSION_FORMAT_DEFAULT); rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid, FSCTL_SET_COMPRESSION, true /* is_fsctl */, (char *)&fsctl_input /* data input */, 2 /* in data len */, CIFSMaxBufSize /* max out data */, &ret_data /* out data */, NULL); cifs_dbg(FYI, "set compression rc %d\n", rc); return rc; } int SMB2_close_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, u64 persistent_fid, u64 volatile_fid) { struct smb2_close_req *req; struct kvec *iov = rqst->rq_iov; unsigned int total_len; int rc; rc = smb2_plain_req_init(SMB2_CLOSE, tcon, (void **) &req, &total_len); if (rc) return rc; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; return 0; } void SMB2_close_free(struct smb_rqst *rqst) { if (rqst && rqst->rq_iov) cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */ } int SMB2_close_flags(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int flags) { struct smb_rqst rqst; struct smb2_close_rsp *rsp = NULL; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype = CIFS_NO_BUFFER; int rc = 0; cifs_dbg(FYI, "Close\n"); if (!ses || !(ses->server)) return -EIO; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); memset(&iov, 0, sizeof(iov)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = SMB2_close_init(tcon, &rqst, persistent_fid, volatile_fid); if (rc) goto close_exit; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_close_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE); trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid, rc); goto close_exit; } atomic_dec(&tcon->num_remote_opens); /* BB FIXME - decode close response, update inode for caching */ close_exit: SMB2_close_free(&rqst); free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_close(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { return SMB2_close_flags(xid, tcon, persistent_fid, volatile_fid, 0); } int smb2_validate_iov(unsigned int offset, unsigned int buffer_length, struct kvec *iov, unsigned int min_buf_size) { unsigned int smb_len = iov->iov_len; char *end_of_smb = smb_len + (char *)iov->iov_base; char *begin_of_buf = offset + (char *)iov->iov_base; char *end_of_buf = begin_of_buf + buffer_length; if (buffer_length < min_buf_size) { cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n", buffer_length, min_buf_size); return -EINVAL; } /* check if beyond RFC1001 maximum length */ if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) { cifs_dbg(VFS, "buffer length %d or smb length %d too large\n", buffer_length, smb_len); return -EINVAL; } if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) { cifs_dbg(VFS, "illegal server response, bad offset to data\n"); return -EINVAL; } return 0; } /* * If SMB buffer fields are valid, copy into temporary buffer to hold result. * Caller must free buffer. */ int smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length, struct kvec *iov, unsigned int minbufsize, char *data) { char *begin_of_buf = offset + (char *)iov->iov_base; int rc; if (!data) return -EINVAL; rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize); if (rc) return rc; memcpy(data, begin_of_buf, buffer_length); return 0; } int SMB2_query_info_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type, u32 additional_info, size_t output_len, size_t input_len, void *input) { struct smb2_query_info_req *req; struct kvec *iov = rqst->rq_iov; unsigned int total_len; int rc; rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req, &total_len); if (rc) return rc; req->InfoType = info_type; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; req->AdditionalInformation = cpu_to_le32(additional_info); req->OutputBufferLength = cpu_to_le32(output_len); if (input_len) { req->InputBufferLength = cpu_to_le32(input_len); /* total_len for smb query request never close to le16 max */ req->InputBufferOffset = cpu_to_le16(total_len - 1); memcpy(req->Buffer, input, input_len); } iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1 + input_len; return 0; } void SMB2_query_info_free(struct smb_rqst *rqst) { if (rqst && rqst->rq_iov) cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */ } static int query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type, u32 additional_info, size_t output_len, size_t min_len, void **data, u32 *dlen) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype = CIFS_NO_BUFFER; struct cifs_ses *ses = tcon->ses; int flags = 0; bool allocated = false; cifs_dbg(FYI, "Query Info\n"); if (!ses || !(ses->server)) return -EIO; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); memset(&iov, 0, sizeof(iov)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = SMB2_query_info_init(tcon, &rqst, persistent_fid, volatile_fid, info_class, info_type, additional_info, output_len, 0, NULL); if (rc) goto qinf_exit; trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid, ses->Suid, info_class, (__u32)info_type); rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); trace_smb3_query_info_err(xid, persistent_fid, tcon->tid, ses->Suid, info_class, (__u32)info_type, rc); goto qinf_exit; } trace_smb3_query_info_done(xid, persistent_fid, tcon->tid, ses->Suid, info_class, (__u32)info_type); if (dlen) { *dlen = le32_to_cpu(rsp->OutputBufferLength); if (!*data) { *data = kmalloc(*dlen, GFP_KERNEL); if (!*data) { cifs_dbg(VFS, "Error %d allocating memory for acl\n", rc); *dlen = 0; rc = -ENOMEM; goto qinf_exit; } allocated = true; } } rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, min_len, *data); if (rc && allocated) { kfree(*data); *data = NULL; *dlen = 0; } qinf_exit: SMB2_query_info_free(&rqst); free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0, sizeof(struct smb2_file_all_info) + PATH_MAX * 2, sizeof(struct smb2_file_all_info), (void **)&data, NULL); } int SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, void **data, u32 *plen) { __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO; *plen = 0; return query_info(xid, tcon, persistent_fid, volatile_fid, 0, SMB2_O_INFO_SECURITY, additional_info, SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen); } int SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid) { return query_info(xid, tcon, persistent_fid, volatile_fid, FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0, sizeof(struct smb2_file_internal_info), sizeof(struct smb2_file_internal_info), (void **)&uniqueid, NULL); } /* * This is a no-op for now. We're not really interested in the reply, but * rather in the fact that the server sent one and that server->lstrp * gets updated. * * FIXME: maybe we should consider checking that the reply matches request? */ static void smb2_echo_callback(struct mid_q_entry *mid) { struct TCP_Server_Info *server = mid->callback_data; struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf; struct cifs_credits credits = { .value = 0, .instance = 0 }; if (mid->mid_state == MID_RESPONSE_RECEIVED || mid->mid_state == MID_RESPONSE_MALFORMED) { credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest); credits.instance = server->reconnect_instance; } DeleteMidQEntry(mid); add_credits(server, &credits, CIFS_ECHO_OP); } void smb2_reconnect_server(struct work_struct *work) { struct TCP_Server_Info *server = container_of(work, struct TCP_Server_Info, reconnect.work); struct cifs_ses *ses; struct cifs_tcon *tcon, *tcon2; struct list_head tmp_list; int tcon_exist = false; int rc; int resched = false; /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */ mutex_lock(&server->reconnect_mutex); INIT_LIST_HEAD(&tmp_list); cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n"); spin_lock(&cifs_tcp_ses_lock); list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) { list_for_each_entry(tcon, &ses->tcon_list, tcon_list) { if (tcon->need_reconnect || tcon->need_reopen_files) { tcon->tc_count++; list_add_tail(&tcon->rlist, &tmp_list); tcon_exist = true; } } if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) { list_add_tail(&ses->tcon_ipc->rlist, &tmp_list); tcon_exist = true; } } /* * Get the reference to server struct to be sure that the last call of * cifs_put_tcon() in the loop below won't release the server pointer. */ if (tcon_exist) server->srv_count++; spin_unlock(&cifs_tcp_ses_lock); list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) { rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon); if (!rc) cifs_reopen_persistent_handles(tcon); else resched = true; list_del_init(&tcon->rlist); cifs_put_tcon(tcon); } cifs_dbg(FYI, "Reconnecting tcons finished\n"); if (resched) queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ); mutex_unlock(&server->reconnect_mutex); /* now we can safely release srv struct */ if (tcon_exist) cifs_put_tcp_session(server, 1); } int SMB2_echo(struct TCP_Server_Info *server) { struct smb2_echo_req *req; int rc = 0; struct kvec iov[1]; struct smb_rqst rqst = { .rq_iov = iov, .rq_nvec = 1 }; unsigned int total_len; cifs_dbg(FYI, "In echo request\n"); if (server->tcpStatus == CifsNeedNegotiate) { /* No need to send echo on newly established connections */ queue_delayed_work(cifsiod_wq, &server->reconnect, 0); return rc; } rc = smb2_plain_req_init(SMB2_ECHO, NULL, (void **)&req, &total_len); if (rc) return rc; req->sync_hdr.CreditRequest = cpu_to_le16(1); iov[0].iov_len = total_len; iov[0].iov_base = (char *)req; rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL, server, CIFS_ECHO_OP, NULL); if (rc) cifs_dbg(FYI, "Echo request failed: %d\n", rc); cifs_small_buf_release(req); return rc; } int SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb_rqst rqst; struct smb2_flush_req *req; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; unsigned int total_len; cifs_dbg(FYI, "Flush\n"); if (!ses || !(ses->server)) return -EIO; rc = smb2_plain_req_init(SMB2_FLUSH, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE); trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid, rc); } free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } /* * To form a chain of read requests, any read requests after the first should * have the end_of_chain boolean set to true. */ static int smb2_new_read_req(void **buf, unsigned int *total_len, struct cifs_io_parms *io_parms, struct cifs_readdata *rdata, unsigned int remaining_bytes, int request_type) { int rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_sync_hdr *shdr; struct TCP_Server_Info *server; rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req, total_len); if (rc) return rc; server = io_parms->tcon->ses->server; if (server == NULL) return -ECONNABORTED; shdr = &req->sync_hdr; shdr->ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->ReadChannelInfoOffset = 0; /* reserved */ req->ReadChannelInfoLength = 0; /* reserved */ req->Channel = 0; /* reserved */ req->MinimumCount = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); trace_smb3_read_enter(0 /* xid */, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); #ifdef CONFIG_CIFS_SMB_DIRECT /* * If we want to do a RDMA write, fill in and append * smbd_buffer_descriptor_v1 to the end of read request */ if (server->rdma && rdata && !server->sign && rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) { struct smbd_buffer_descriptor_v1 *v1; bool need_invalidate = io_parms->tcon->ses->server->dialect == SMB30_PROT_ID; rdata->mr = smbd_register_mr( server->smbd_conn, rdata->pages, rdata->nr_pages, rdata->page_offset, rdata->tailsz, true, need_invalidate); if (!rdata->mr) return -ENOBUFS; req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE; if (need_invalidate) req->Channel = SMB2_CHANNEL_RDMA_V1; req->ReadChannelInfoOffset = cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer)); req->ReadChannelInfoLength = cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1)); v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0]; v1->offset = cpu_to_le64(rdata->mr->mr->iova); v1->token = cpu_to_le32(rdata->mr->mr->rkey); v1->length = cpu_to_le32(rdata->mr->mr->length); *total_len += sizeof(*v1) - 1; } #endif if (request_type & CHAINED_REQUEST) { if (!(request_type & END_OF_CHAIN)) { /* next 8-byte aligned request */ *total_len = DIV_ROUND_UP(*total_len, 8) * 8; shdr->NextCommand = cpu_to_le32(*total_len); } else /* END_OF_CHAIN */ shdr->NextCommand = 0; if (request_type & RELATED_REQUEST) { shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS; /* * Related requests use info from previous read request * in chain. */ shdr->SessionId = 0xFFFFFFFF; shdr->TreeId = 0xFFFFFFFF; req->PersistentFileId = 0xFFFFFFFF; req->VolatileFileId = 0xFFFFFFFF; } } if (remaining_bytes > io_parms->length) req->RemainingBytes = cpu_to_le32(remaining_bytes); else req->RemainingBytes = 0; *buf = req; return rc; } static void smb2_readv_callback(struct mid_q_entry *mid) { struct cifs_readdata *rdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)rdata->iov[0].iov_base; struct cifs_credits credits = { .value = 0, .instance = 0 }; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2, .rq_pages = rdata->pages, .rq_offset = rdata->page_offset, .rq_npages = rdata->nr_pages, .rq_pagesz = rdata->pagesz, .rq_tailsz = rdata->tailsz }; cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n", __func__, mid->mid, mid->mid_state, rdata->result, rdata->bytes); switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits.value = le16_to_cpu(shdr->CreditRequest); credits.instance = server->reconnect_instance; /* result already set, check signature */ if (server->sign && !mid->decrypted) { int rc; rc = smb2_verify_signature(&rqst, server); if (rc) cifs_dbg(VFS, "SMB signature verification returned error = %d\n", rc); } /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: rdata->result = -EAGAIN; if (server->sign && rdata->got_bytes) /* reset bytes number since we can not check a sign */ rdata->got_bytes = 0; /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; case MID_RESPONSE_MALFORMED: credits.value = le16_to_cpu(shdr->CreditRequest); credits.instance = server->reconnect_instance; /* fall through */ default: rdata->result = -EIO; } #ifdef CONFIG_CIFS_SMB_DIRECT /* * If this rdata has a memmory registered, the MR can be freed * MR needs to be freed as soon as I/O finishes to prevent deadlock * because they have limited number and are used for future I/Os */ if (rdata->mr) { smbd_deregister_mr(rdata->mr); rdata->mr = NULL; } #endif if (rdata->result && rdata->result != -ENODATA) { cifs_stats_fail_inc(tcon, SMB2_READ_HE); trace_smb3_read_err(0 /* xid */, rdata->cfile->fid.persistent_fid, tcon->tid, tcon->ses->Suid, rdata->offset, rdata->bytes, rdata->result); } else trace_smb3_read_done(0 /* xid */, rdata->cfile->fid.persistent_fid, tcon->tid, tcon->ses->Suid, rdata->offset, rdata->got_bytes); queue_work(cifsiod_wq, &rdata->work); DeleteMidQEntry(mid); add_credits(server, &credits, 0); } /* smb2_async_readv - send an async read, and set up mid to handle result */ int smb2_async_readv(struct cifs_readdata *rdata) { int rc, flags = 0; char *buf; struct smb2_sync_hdr *shdr; struct cifs_io_parms io_parms; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 1 }; struct TCP_Server_Info *server; unsigned int total_len; cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n", __func__, rdata->offset, rdata->bytes); io_parms.tcon = tlink_tcon(rdata->cfile->tlink); io_parms.offset = rdata->offset; io_parms.length = rdata->bytes; io_parms.persistent_fid = rdata->cfile->fid.persistent_fid; io_parms.volatile_fid = rdata->cfile->fid.volatile_fid; io_parms.pid = rdata->pid; server = io_parms.tcon->ses->server; rc = smb2_new_read_req( (void **) &buf, &total_len, &io_parms, rdata, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms.tcon)) flags |= CIFS_TRANSFORM_REQ; rdata->iov[0].iov_base = buf; rdata->iov[0].iov_len = total_len; shdr = (struct smb2_sync_hdr *)buf; if (rdata->credits.value > 0) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1); rc = adjust_credits(server, &rdata->credits, rdata->bytes); if (rc) goto async_readv_out; flags |= CIFS_HAS_CREDITS; } kref_get(&rdata->refcount); rc = cifs_call_async(io_parms.tcon->ses->server, &rqst, cifs_readv_receive, smb2_readv_callback, smb3_handle_read_data, rdata, flags, &rdata->credits); if (rc) { kref_put(&rdata->refcount, cifs_readdata_release); cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE); trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid, io_parms.tcon->tid, io_parms.tcon->ses->Suid, io_parms.offset, io_parms.length, rc); } async_readv_out: cifs_small_buf_release(buf); return rc; } int SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { struct smb_rqst rqst; int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; unsigned int total_len; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, "Send error in read = %d\n", rc); trace_smb3_read_err(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length, rc); } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, 0); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length); cifs_small_buf_release(req); *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, "bad length %d for count %d\n", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } if (*buf) { memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; } /* * Check the mid_state and signature on received buffer (if any), and queue the * workqueue completion task. */ static void smb2_writev_callback(struct mid_q_entry *mid) { struct cifs_writedata *wdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; unsigned int written; struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf; struct cifs_credits credits = { .value = 0, .instance = 0 }; switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest); credits.instance = server->reconnect_instance; wdata->result = smb2_check_receive(mid, server, 0); if (wdata->result != 0) break; written = le32_to_cpu(rsp->DataLength); /* * Mask off high 16 bits when bytes written as returned * by the server is greater than bytes requested by the * client. OS/2 servers are known to set incorrect * CountHigh values. */ if (written > wdata->bytes) written &= 0xFFFF; if (written < wdata->bytes) wdata->result = -ENOSPC; else wdata->bytes = written; break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: wdata->result = -EAGAIN; break; case MID_RESPONSE_MALFORMED: credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest); credits.instance = server->reconnect_instance; /* fall through */ default: wdata->result = -EIO; break; } #ifdef CONFIG_CIFS_SMB_DIRECT /* * If this wdata has a memory registered, the MR can be freed * The number of MRs available is limited, it's important to recover * used MR as soon as I/O is finished. Hold MR longer in the later * I/O process can possibly result in I/O deadlock due to lack of MR * to send request on I/O retry */ if (wdata->mr) { smbd_deregister_mr(wdata->mr); wdata->mr = NULL; } #endif if (wdata->result) { cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); trace_smb3_write_err(0 /* no xid */, wdata->cfile->fid.persistent_fid, tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes, wdata->result); } else trace_smb3_write_done(0 /* no xid */, wdata->cfile->fid.persistent_fid, tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes); queue_work(cifsiod_wq, &wdata->work); DeleteMidQEntry(mid); add_credits(server, &credits, 0); } /* smb2_async_writev - send an async write, and set up mid to handle result */ int smb2_async_writev(struct cifs_writedata *wdata, void (*release)(struct kref *kref)) { int rc = -EACCES, flags = 0; struct smb2_write_req *req = NULL; struct smb2_sync_hdr *shdr; struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct kvec iov[1]; struct smb_rqst rqst = { }; unsigned int total_len; rc = smb2_plain_req_init(SMB2_WRITE, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; shdr = (struct smb2_sync_hdr *)req; shdr->ProcessId = cpu_to_le32(wdata->cfile->pid); req->PersistentFileId = wdata->cfile->fid.persistent_fid; req->VolatileFileId = wdata->cfile->fid.volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Offset = cpu_to_le64(wdata->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid, tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes); #ifdef CONFIG_CIFS_SMB_DIRECT /* * If we want to do a server RDMA read, fill in and append * smbd_buffer_descriptor_v1 to the end of write request */ if (server->rdma && !server->sign && wdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) { struct smbd_buffer_descriptor_v1 *v1; bool need_invalidate = server->dialect == SMB30_PROT_ID; wdata->mr = smbd_register_mr( server->smbd_conn, wdata->pages, wdata->nr_pages, wdata->page_offset, wdata->tailsz, false, need_invalidate); if (!wdata->mr) { rc = -ENOBUFS; goto async_writev_out; } req->Length = 0; req->DataOffset = 0; if (wdata->nr_pages > 1) req->RemainingBytes = cpu_to_le32( (wdata->nr_pages - 1) * wdata->pagesz - wdata->page_offset + wdata->tailsz ); else req->RemainingBytes = cpu_to_le32(wdata->tailsz); req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE; if (need_invalidate) req->Channel = SMB2_CHANNEL_RDMA_V1; req->WriteChannelInfoOffset = cpu_to_le16(offsetof(struct smb2_write_req, Buffer)); req->WriteChannelInfoLength = cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1)); v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0]; v1->offset = cpu_to_le64(wdata->mr->mr->iova); v1->token = cpu_to_le32(wdata->mr->mr->rkey); v1->length = cpu_to_le32(wdata->mr->mr->length); } #endif iov[0].iov_len = total_len - 1; iov[0].iov_base = (char *)req; rqst.rq_iov = iov; rqst.rq_nvec = 1; rqst.rq_pages = wdata->pages; rqst.rq_offset = wdata->page_offset; rqst.rq_npages = wdata->nr_pages; rqst.rq_pagesz = wdata->pagesz; rqst.rq_tailsz = wdata->tailsz; #ifdef CONFIG_CIFS_SMB_DIRECT if (wdata->mr) { iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1); rqst.rq_npages = 0; } #endif cifs_dbg(FYI, "async write at %llu %u bytes\n", wdata->offset, wdata->bytes); #ifdef CONFIG_CIFS_SMB_DIRECT /* For RDMA read, I/O size is in RemainingBytes not in Length */ if (!wdata->mr) req->Length = cpu_to_le32(wdata->bytes); #else req->Length = cpu_to_le32(wdata->bytes); #endif if (wdata->credits.value > 0) { shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes, SMB2_MAX_BUFFER_SIZE)); shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1); rc = adjust_credits(server, &wdata->credits, wdata->bytes); if (rc) goto async_writev_out; flags |= CIFS_HAS_CREDITS; } kref_get(&wdata->refcount); rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL, wdata, flags, &wdata->credits); if (rc) { trace_smb3_write_err(0 /* no xid */, req->PersistentFileId, tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes, rc); kref_put(&wdata->refcount, release); cifs_stats_fail_inc(tcon, SMB2_WRITE_HE); } async_writev_out: cifs_small_buf_release(req); return rc; } /* * SMB2_write function gets iov pointer to kvec array with n_vec as a length. * The length field from io_parms must be at least 1 and indicates a number of * elements with data to write that begins with position 1 in iov array. All * data length is specified by count. */ int SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } cifs_small_buf_release(req); free_rsp_buf(resp_buftype, rsp); return rc; } static unsigned int num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size) { int len; unsigned int entrycount = 0; unsigned int next_offset = 0; char *entryptr; FILE_DIRECTORY_INFO *dir_info; if (bufstart == NULL) return 0; entryptr = bufstart; while (1) { if (entryptr + next_offset < entryptr || entryptr + next_offset > end_of_buf || entryptr + next_offset + size > end_of_buf) { cifs_dbg(VFS, "malformed search entry would overflow\n"); break; } entryptr = entryptr + next_offset; dir_info = (FILE_DIRECTORY_INFO *)entryptr; len = le32_to_cpu(dir_info->FileNameLength); if (entryptr + len < entryptr || entryptr + len > end_of_buf || entryptr + len + size > end_of_buf) { cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n", end_of_buf); break; } *lastentry = entryptr; entrycount++; next_offset = le32_to_cpu(dir_info->NextEntryOffset); if (!next_offset) break; } return entrycount; } /* * Readdir/FindFirst */ int SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int index, struct cifs_search_info *srch_inf) { struct smb_rqst rqst; struct smb2_query_directory_req *req; struct smb2_query_directory_rsp *rsp = NULL; struct kvec iov[2]; struct kvec rsp_iov; int rc = 0; int len; int resp_buftype = CIFS_NO_BUFFER; unsigned char *bufptr; struct TCP_Server_Info *server; struct cifs_ses *ses = tcon->ses; __le16 asteriks = cpu_to_le16('*'); char *end_of_smb; unsigned int output_size = CIFSMaxBufSize; size_t info_buf_size; int flags = 0; unsigned int total_len; if (ses && (ses->server)) server = ses->server; else return -EIO; rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; switch (srch_inf->info_level) { case SMB_FIND_FILE_DIRECTORY_INFO: req->FileInformationClass = FILE_DIRECTORY_INFORMATION; info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1; break; case SMB_FIND_FILE_ID_FULL_DIR_INFO: req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION; info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1; break; default: cifs_dbg(VFS, "info level %u isn't supported\n", srch_inf->info_level); rc = -EINVAL; goto qdir_exit; } req->FileIndex = cpu_to_le32(index); req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; len = 0x2; bufptr = req->Buffer; memcpy(bufptr, &asteriks, len); req->FileNameOffset = cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1); req->FileNameLength = cpu_to_le16(len); /* * BB could be 30 bytes or so longer if we used SMB2 specific * buffer lengths, but this is safe and close enough. */ output_size = min_t(unsigned int, output_size, server->maxBuf); output_size = min_t(unsigned int, output_size, 2 << 15); req->OutputBufferLength = cpu_to_le32(output_size); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; iov[1].iov_base = (char *)(req->Buffer); iov[1].iov_len = len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 2; trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid, tcon->ses->Suid, index, output_size); rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base; if (rc) { if (rc == -ENODATA && rsp->sync_hdr.Status == STATUS_NO_MORE_FILES) { trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid, tcon->ses->Suid, index, 0); srch_inf->endOfSearch = true; rc = 0; } else { trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid, tcon->ses->Suid, index, 0, rc); cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE); } goto qdir_exit; } rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, info_buf_size); if (rc) { trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid, tcon->ses->Suid, index, 0, rc); goto qdir_exit; } srch_inf->unicode = true; if (srch_inf->ntwrk_buf_start) { if (srch_inf->smallBuf) cifs_small_buf_release(srch_inf->ntwrk_buf_start); else cifs_buf_release(srch_inf->ntwrk_buf_start); } srch_inf->ntwrk_buf_start = (char *)rsp; srch_inf->srch_entries_start = srch_inf->last_entry = (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset); end_of_smb = rsp_iov.iov_len + (char *)rsp; srch_inf->entries_in_buffer = num_entries(srch_inf->srch_entries_start, end_of_smb, &srch_inf->last_entry, info_buf_size); srch_inf->index_of_last_entry += srch_inf->entries_in_buffer; cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n", srch_inf->entries_in_buffer, srch_inf->index_of_last_entry, srch_inf->srch_entries_start, srch_inf->last_entry); if (resp_buftype == CIFS_LARGE_BUFFER) srch_inf->smallBuf = false; else if (resp_buftype == CIFS_SMALL_BUFFER) srch_inf->smallBuf = true; else cifs_dbg(VFS, "illegal search buffer type\n"); trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid, tcon->ses->Suid, index, srch_inf->entries_in_buffer); return rc; qdir_exit: free_rsp_buf(resp_buftype, rsp); return rc; } int SMB2_set_info_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class, u8 info_type, u32 additional_info, void **data, unsigned int *size) { struct smb2_set_info_req *req; struct kvec *iov = rqst->rq_iov; unsigned int i, total_len; int rc; rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, (void **) &req, &total_len); if (rc) return rc; req->sync_hdr.ProcessId = cpu_to_le32(pid); req->InfoType = info_type; req->FileInfoClass = info_class; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; req->AdditionalInformation = cpu_to_le32(additional_info); req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req) - 1); req->BufferLength = cpu_to_le32(*size); memcpy(req->Buffer, *data, *size); total_len += *size; iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; for (i = 1; i < rqst->rq_nvec; i++) { le32_add_cpu(&req->BufferLength, size[i]); iov[i].iov_base = (char *)data[i]; iov[i].iov_len = size[i]; } return 0; } void SMB2_set_info_free(struct smb_rqst *rqst) { if (rqst && rqst->rq_iov) cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */ } static int send_set_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class, u8 info_type, u32 additional_info, unsigned int num, void **data, unsigned int *size) { struct smb_rqst rqst; struct smb2_set_info_rsp *rsp = NULL; struct kvec *iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; int flags = 0; if (!ses || !(ses->server)) return -EIO; if (!num) return -EINVAL; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL); if (!iov) return -ENOMEM; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = num; rc = SMB2_set_info_init(tcon, &rqst, persistent_fid, volatile_fid, pid, info_class, info_type, additional_info, data, size); if (rc) { kfree(iov); return rc; } rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); SMB2_set_info_free(&rqst); rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base; if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE); trace_smb3_set_info_err(xid, persistent_fid, tcon->tid, ses->Suid, info_class, (__u32)info_type, rc); } free_rsp_buf(resp_buftype, rsp); kfree(iov); return rc; } int SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, u32 pid, __le64 *eof) { struct smb2_file_eof_info info; void *data; unsigned int size; info.EndOfFile = *eof; data = &info; size = sizeof(struct smb2_file_eof_info); return send_set_info(xid, tcon, persistent_fid, volatile_fid, pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE, 0, 1, &data, &size); } int SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct cifs_ntsd *pnntsd, int pacllen, int aclflag) { return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag, 1, (void **)&pnntsd, &pacllen); } int SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_full_ea_info *buf, int len) { return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0, 1, (void **)&buf, &len); } int SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon, const u64 persistent_fid, const u64 volatile_fid, __u8 oplock_level) { struct smb_rqst rqst; int rc; struct smb2_oplock_break *req = NULL; struct cifs_ses *ses = tcon->ses; int flags = CIFS_OBREAK_OP; unsigned int total_len; struct kvec iov[1]; struct kvec rsp_iov; int resp_buf_type; cifs_dbg(FYI, "SMB2_oplock_break\n"); rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->VolatileFid = volatile_fid; req->PersistentFid = persistent_fid; req->OplockLevel = oplock_level; req->sync_hdr.CreditRequest = cpu_to_le16(1); flags |= CIFS_NO_RESP; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc); } return rc; } void smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf, struct kstatfs *kst) { kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) * le32_to_cpu(pfs_inf->SectorsPerAllocationUnit); kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits); kst->f_bfree = kst->f_bavail = le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits); return; } static void copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data, struct kstatfs *kst) { kst->f_bsize = le32_to_cpu(response_data->BlockSize); kst->f_blocks = le64_to_cpu(response_data->TotalBlocks); kst->f_bfree = le64_to_cpu(response_data->BlocksAvail); if (response_data->UserBlocksAvail == cpu_to_le64(-1)) kst->f_bavail = kst->f_bfree; else kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail); if (response_data->TotalFileNodes != cpu_to_le64(-1)) kst->f_files = le64_to_cpu(response_data->TotalFileNodes); if (response_data->FreeFileNodes != cpu_to_le64(-1)) kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes); return; } static int build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level, int outbuf_len, u64 persistent_fid, u64 volatile_fid) { int rc; struct smb2_query_info_req *req; unsigned int total_len; cifs_dbg(FYI, "Query FSInfo level %d\n", level); if ((tcon->ses == NULL) || (tcon->ses->server == NULL)) return -EIO; rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req, &total_len); if (rc) return rc; req->InfoType = SMB2_O_INFO_FILESYSTEM; req->FileInfoClass = level; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; /* 1 for pad */ req->InputBufferOffset = cpu_to_le16(sizeof(struct smb2_query_info_req) - 1); req->OutputBufferLength = cpu_to_le32( outbuf_len + sizeof(struct smb2_query_info_rsp) - 1); iov->iov_base = (char *)req; iov->iov_len = total_len; return 0; } int SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; FILE_SYSTEM_POSIX_INFO *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_POSIX_INFORMATION, sizeof(FILE_SYSTEM_POSIX_INFO), persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto posix_qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (FILE_SYSTEM_POSIX_INFO *)( le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp); rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, sizeof(FILE_SYSTEM_POSIX_INFO)); if (!rc) copy_posix_fs_info_to_kstatfs(info, fsdata); posix_qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; struct smb2_fs_full_size_info *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION, sizeof(struct smb2_fs_full_size_info), persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (struct smb2_fs_full_size_info *)( le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp); rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, sizeof(struct smb2_fs_full_size_info)); if (!rc) smb2_copy_fs_info_to_kstatfs(info, fsdata); qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int level) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype, max_len, min_len; struct cifs_ses *ses = tcon->ses; unsigned int rsp_len, offset; int flags = 0; if (level == FS_DEVICE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_DEVICE_INFO); min_len = sizeof(FILE_SYSTEM_DEVICE_INFO); } else if (level == FS_ATTRIBUTE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO); min_len = MIN_FS_ATTR_INFO_SIZE; } else if (level == FS_SECTOR_SIZE_INFORMATION) { max_len = sizeof(struct smb3_fs_ss_info); min_len = sizeof(struct smb3_fs_ss_info); } else if (level == FS_VOLUME_INFORMATION) { max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN; min_len = sizeof(struct smb3_fs_vol_info); } else { cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level); return -EINVAL; } rc = build_qfs_info_req(&iov, tcon, level, max_len, persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsattr_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; rsp_len = le32_to_cpu(rsp->OutputBufferLength); offset = le16_to_cpu(rsp->OutputBufferOffset); rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len); if (rc) goto qfsattr_exit; if (level == FS_ATTRIBUTE_INFORMATION) memcpy(&tcon->fsAttrInfo, offset + (char *)rsp, min_t(unsigned int, rsp_len, max_len)); else if (level == FS_DEVICE_INFORMATION) memcpy(&tcon->fsDevInfo, offset + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO)); else if (level == FS_SECTOR_SIZE_INFORMATION) { struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *) (offset + (char *)rsp); tcon->ss_flags = le32_to_cpu(ss_info->Flags); tcon->perf_sector_size = le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf); } else if (level == FS_VOLUME_INFORMATION) { struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *) (offset + (char *)rsp); tcon->vol_serial_number = vol_info->VolumeSerialNumber; tcon->vol_create_time = vol_info->VolumeCreationTime; } qfsattr_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } int smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u32 num_lock, struct smb2_lock_element *buf) { struct smb_rqst rqst; int rc = 0; struct smb2_lock_req *req = NULL; struct kvec iov[2]; struct kvec rsp_iov; int resp_buf_type; unsigned int count; int flags = CIFS_NO_RESP; unsigned int total_len; cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock); rc = smb2_plain_req_init(SMB2_LOCK, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(pid); req->LockCount = cpu_to_le16(num_lock); req->PersistentFileId = persist_fid; req->VolatileFileId = volatile_fid; count = num_lock * sizeof(struct smb2_lock_element); iov[0].iov_base = (char *)req; iov[0].iov_len = total_len - sizeof(struct smb2_lock_element); iov[1].iov_base = (char *)buf; iov[1].iov_len = count; cifs_stats_inc(&tcon->stats.cifs_stats.num_locks); memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 2; rc = cifs_send_recv(xid, tcon->ses, &rqst, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); if (rc) { cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc); cifs_stats_fail_inc(tcon, SMB2_LOCK_HE); trace_smb3_lock_err(xid, persist_fid, tcon->tid, tcon->ses->Suid, rc); } return rc; } int SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon, const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid, const __u64 length, const __u64 offset, const __u32 lock_flags, const bool wait) { struct smb2_lock_element lock; lock.Offset = cpu_to_le64(offset); lock.Length = cpu_to_le64(length); lock.Flags = cpu_to_le32(lock_flags); if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK) lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY); return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock); } int SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon, __u8 *lease_key, const __le32 lease_state) { struct smb_rqst rqst; int rc; struct smb2_lease_ack *req = NULL; struct cifs_ses *ses = tcon->ses; int flags = CIFS_OBREAK_OP; unsigned int total_len; struct kvec iov[1]; struct kvec rsp_iov; int resp_buf_type; __u64 *please_key_high; __u64 *please_key_low; cifs_dbg(FYI, "SMB2_lease_break\n"); rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.CreditRequest = cpu_to_le16(1); req->StructureSize = cpu_to_le16(36); total_len += 12; memcpy(req->LeaseKey, lease_key, 16); req->LeaseState = lease_state; flags |= CIFS_NO_RESP; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov); cifs_small_buf_release(req); please_key_low = (__u64 *)lease_key; please_key_high = (__u64 *)(lease_key+8); if (rc) { cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE); trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid, ses->Suid, *please_key_low, *please_key_high, rc); cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc); } else trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid, ses->Suid, *please_key_low, *please_key_high); return rc; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1056_0
crossvul-cpp_data_bad_2660_0
/* * Copyright (c) 2001 * Fortress Technologies, Inc. All rights reserved. * Charlie Lenahan (clenahan@fortresstech.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IEEE 802.11 printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "cpack.h" /* Lengths of 802.11 header components. */ #define IEEE802_11_FC_LEN 2 #define IEEE802_11_DUR_LEN 2 #define IEEE802_11_DA_LEN 6 #define IEEE802_11_SA_LEN 6 #define IEEE802_11_BSSID_LEN 6 #define IEEE802_11_RA_LEN 6 #define IEEE802_11_TA_LEN 6 #define IEEE802_11_ADDR1_LEN 6 #define IEEE802_11_SEQ_LEN 2 #define IEEE802_11_CTL_LEN 2 #define IEEE802_11_CARRIED_FC_LEN 2 #define IEEE802_11_HT_CONTROL_LEN 4 #define IEEE802_11_IV_LEN 3 #define IEEE802_11_KID_LEN 1 /* Frame check sequence length. */ #define IEEE802_11_FCS_LEN 4 /* Lengths of beacon components. */ #define IEEE802_11_TSTAMP_LEN 8 #define IEEE802_11_BCNINT_LEN 2 #define IEEE802_11_CAPINFO_LEN 2 #define IEEE802_11_LISTENINT_LEN 2 #define IEEE802_11_AID_LEN 2 #define IEEE802_11_STATUS_LEN 2 #define IEEE802_11_REASON_LEN 2 /* Length of previous AP in reassocation frame */ #define IEEE802_11_AP_LEN 6 #define T_MGMT 0x0 /* management */ #define T_CTRL 0x1 /* control */ #define T_DATA 0x2 /* data */ #define T_RESV 0x3 /* reserved */ #define ST_ASSOC_REQUEST 0x0 #define ST_ASSOC_RESPONSE 0x1 #define ST_REASSOC_REQUEST 0x2 #define ST_REASSOC_RESPONSE 0x3 #define ST_PROBE_REQUEST 0x4 #define ST_PROBE_RESPONSE 0x5 /* RESERVED 0x6 */ /* RESERVED 0x7 */ #define ST_BEACON 0x8 #define ST_ATIM 0x9 #define ST_DISASSOC 0xA #define ST_AUTH 0xB #define ST_DEAUTH 0xC #define ST_ACTION 0xD /* RESERVED 0xE */ /* RESERVED 0xF */ static const struct tok st_str[] = { { ST_ASSOC_REQUEST, "Assoc Request" }, { ST_ASSOC_RESPONSE, "Assoc Response" }, { ST_REASSOC_REQUEST, "ReAssoc Request" }, { ST_REASSOC_RESPONSE, "ReAssoc Response" }, { ST_PROBE_REQUEST, "Probe Request" }, { ST_PROBE_RESPONSE, "Probe Response" }, { ST_BEACON, "Beacon" }, { ST_ATIM, "ATIM" }, { ST_DISASSOC, "Disassociation" }, { ST_AUTH, "Authentication" }, { ST_DEAUTH, "DeAuthentication" }, { ST_ACTION, "Action" }, { 0, NULL } }; #define CTRL_CONTROL_WRAPPER 0x7 #define CTRL_BAR 0x8 #define CTRL_BA 0x9 #define CTRL_PS_POLL 0xA #define CTRL_RTS 0xB #define CTRL_CTS 0xC #define CTRL_ACK 0xD #define CTRL_CF_END 0xE #define CTRL_END_ACK 0xF static const struct tok ctrl_str[] = { { CTRL_CONTROL_WRAPPER, "Control Wrapper" }, { CTRL_BAR, "BAR" }, { CTRL_BA, "BA" }, { CTRL_PS_POLL, "Power Save-Poll" }, { CTRL_RTS, "Request-To-Send" }, { CTRL_CTS, "Clear-To-Send" }, { CTRL_ACK, "Acknowledgment" }, { CTRL_CF_END, "CF-End" }, { CTRL_END_ACK, "CF-End+CF-Ack" }, { 0, NULL } }; #define DATA_DATA 0x0 #define DATA_DATA_CF_ACK 0x1 #define DATA_DATA_CF_POLL 0x2 #define DATA_DATA_CF_ACK_POLL 0x3 #define DATA_NODATA 0x4 #define DATA_NODATA_CF_ACK 0x5 #define DATA_NODATA_CF_POLL 0x6 #define DATA_NODATA_CF_ACK_POLL 0x7 #define DATA_QOS_DATA 0x8 #define DATA_QOS_DATA_CF_ACK 0x9 #define DATA_QOS_DATA_CF_POLL 0xA #define DATA_QOS_DATA_CF_ACK_POLL 0xB #define DATA_QOS_NODATA 0xC #define DATA_QOS_CF_POLL_NODATA 0xE #define DATA_QOS_CF_ACK_POLL_NODATA 0xF /* * The subtype field of a data frame is, in effect, composed of 4 flag * bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have * any data), and QoS. */ #define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01) #define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02) #define DATA_FRAME_IS_NULL(x) ((x) & 0x04) #define DATA_FRAME_IS_QOS(x) ((x) & 0x08) /* * Bits in the frame control field. */ #define FC_VERSION(fc) ((fc) & 0x3) #define FC_TYPE(fc) (((fc) >> 2) & 0x3) #define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF) #define FC_TO_DS(fc) ((fc) & 0x0100) #define FC_FROM_DS(fc) ((fc) & 0x0200) #define FC_MORE_FLAG(fc) ((fc) & 0x0400) #define FC_RETRY(fc) ((fc) & 0x0800) #define FC_POWER_MGMT(fc) ((fc) & 0x1000) #define FC_MORE_DATA(fc) ((fc) & 0x2000) #define FC_PROTECTED(fc) ((fc) & 0x4000) #define FC_ORDER(fc) ((fc) & 0x8000) struct mgmt_header_t { uint16_t fc; uint16_t duration; uint8_t da[IEEE802_11_DA_LEN]; uint8_t sa[IEEE802_11_SA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint16_t seq_ctrl; }; #define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN) #define CAPABILITY_ESS(cap) ((cap) & 0x0001) #define CAPABILITY_IBSS(cap) ((cap) & 0x0002) #define CAPABILITY_CFP(cap) ((cap) & 0x0004) #define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008) #define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010) struct ssid_t { uint8_t element_id; uint8_t length; u_char ssid[33]; /* 32 + 1 for null */ }; struct rates_t { uint8_t element_id; uint8_t length; uint8_t rate[16]; }; struct challenge_t { uint8_t element_id; uint8_t length; uint8_t text[254]; /* 1-253 + 1 for null */ }; struct fh_t { uint8_t element_id; uint8_t length; uint16_t dwell_time; uint8_t hop_set; uint8_t hop_pattern; uint8_t hop_index; }; struct ds_t { uint8_t element_id; uint8_t length; uint8_t channel; }; struct cf_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint16_t max_duration; uint16_t dur_remaing; }; struct tim_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint8_t bitmap_control; uint8_t bitmap[251]; }; #define E_SSID 0 #define E_RATES 1 #define E_FH 2 #define E_DS 3 #define E_CF 4 #define E_TIM 5 #define E_IBSS 6 /* reserved 7 */ /* reserved 8 */ /* reserved 9 */ /* reserved 10 */ /* reserved 11 */ /* reserved 12 */ /* reserved 13 */ /* reserved 14 */ /* reserved 15 */ /* reserved 16 */ #define E_CHALLENGE 16 /* reserved 17 */ /* reserved 18 */ /* reserved 19 */ /* reserved 16 */ /* reserved 16 */ struct mgmt_body_t { uint8_t timestamp[IEEE802_11_TSTAMP_LEN]; uint16_t beacon_interval; uint16_t listen_interval; uint16_t status_code; uint16_t aid; u_char ap[IEEE802_11_AP_LEN]; uint16_t reason_code; uint16_t auth_alg; uint16_t auth_trans_seq_num; int challenge_present; struct challenge_t challenge; uint16_t capability_info; int ssid_present; struct ssid_t ssid; int rates_present; struct rates_t rates; int ds_present; struct ds_t ds; int cf_present; struct cf_t cf; int fh_present; struct fh_t fh; int tim_present; struct tim_t tim; }; struct ctrl_control_wrapper_hdr_t { uint16_t fc; uint16_t duration; uint8_t addr1[IEEE802_11_ADDR1_LEN]; uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN]; uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN]; }; #define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_ADDR1_LEN+\ IEEE802_11_CARRIED_FC_LEN+\ IEEE802_11_HT_CONTROL_LEN) struct ctrl_rts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN) struct ctrl_cts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ps_poll_hdr_t { uint16_t fc; uint16_t aid; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN) struct ctrl_end_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_end_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_ba_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_bar_hdr_t { uint16_t fc; uint16_t dur; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; uint16_t ctl; uint16_t seq; }; #define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\ IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN) struct meshcntl_t { uint8_t flags; uint8_t ttl; uint8_t seq[4]; uint8_t addr4[6]; uint8_t addr5[6]; uint8_t addr6[6]; }; #define IV_IV(iv) ((iv) & 0xFFFFFF) #define IV_PAD(iv) (((iv) >> 24) & 0x3F) #define IV_KEYID(iv) (((iv) >> 30) & 0x03) #define PRINT_SSID(p) \ if (p.ssid_present) { \ ND_PRINT((ndo, " (")); \ fn_print(ndo, p.ssid.ssid, NULL); \ ND_PRINT((ndo, ")")); \ } #define PRINT_RATE(_sep, _r, _suf) \ ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf)) #define PRINT_RATES(p) \ if (p.rates_present) { \ int z; \ const char *sep = " ["; \ for (z = 0; z < p.rates.length ; z++) { \ PRINT_RATE(sep, p.rates.rate[z], \ (p.rates.rate[z] & 0x80 ? "*" : "")); \ sep = " "; \ } \ if (p.rates.length != 0) \ ND_PRINT((ndo, " Mbit]")); \ } #define PRINT_DS_CHANNEL(p) \ if (p.ds_present) \ ND_PRINT((ndo, " CH: %u", p.ds.channel)); \ ND_PRINT((ndo, "%s", \ CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : "")); #define MAX_MCS_INDEX 76 /* * Indices are: * * the MCS index (0-76); * * 0 for 20 MHz, 1 for 40 MHz; * * 0 for a long guard interval, 1 for a short guard interval. */ static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = { /* MCS 0 */ { /* 20 Mhz */ { 6.5, /* SGI */ 7.2, }, /* 40 Mhz */ { 13.5, /* SGI */ 15.0, }, }, /* MCS 1 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 2 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 3 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 4 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 5 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 6 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 7 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 8 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 9 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 10 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 11 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 12 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 13 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 14 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 15 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 16 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 17 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 18 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 19 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 20 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 21 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 22 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 23 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 24 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 25 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 26 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 27 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 28 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 29 */ { /* 20 Mhz */ { 208.0, /* SGI */ 231.1, }, /* 40 Mhz */ { 432.0, /* SGI */ 480.0, }, }, /* MCS 30 */ { /* 20 Mhz */ { 234.0, /* SGI */ 260.0, }, /* 40 Mhz */ { 486.0, /* SGI */ 540.0, }, }, /* MCS 31 */ { /* 20 Mhz */ { 260.0, /* SGI */ 288.9, }, /* 40 Mhz */ { 540.0, /* SGI */ 600.0, }, }, /* MCS 32 */ { /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */ /* 40 Mhz */ { 6.0, /* SGI */ 6.7, }, }, /* MCS 33 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 34 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 35 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 36 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 37 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 38 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 39 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 40 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 41 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 42 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 43 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 44 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 45 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 46 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 47 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 48 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 49 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 50 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 51 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 52 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 53 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 54 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 55 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 56 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 57 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 58 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 59 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 60 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 61 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 62 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 63 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 64 */ { /* 20 Mhz */ { 143.0, /* SGI */ 158.9, }, /* 40 Mhz */ { 297.0, /* SGI */ 330.0, }, }, /* MCS 65 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 66 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 67 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 68 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 69 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 70 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 71 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 72 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 73 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 74 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 75 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 76 */ { /* 20 Mhz */ { 214.5, /* SGI */ 238.3, }, /* 40 Mhz */ { 445.5, /* SGI */ 495.0, }, }, }; static const char *auth_alg_text[]={"Open System","Shared Key","EAP"}; #define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0]) static const char *status_text[] = { "Successful", /* 0 */ "Unspecified failure", /* 1 */ "Reserved", /* 2 */ "Reserved", /* 3 */ "Reserved", /* 4 */ "Reserved", /* 5 */ "Reserved", /* 6 */ "Reserved", /* 7 */ "Reserved", /* 8 */ "Reserved", /* 9 */ "Cannot Support all requested capabilities in the Capability " "Information field", /* 10 */ "Reassociation denied due to inability to confirm that association " "exists", /* 11 */ "Association denied due to reason outside the scope of the " "standard", /* 12 */ "Responding station does not support the specified authentication " "algorithm ", /* 13 */ "Received an Authentication frame with authentication transaction " "sequence number out of expected sequence", /* 14 */ "Authentication rejected because of challenge failure", /* 15 */ "Authentication rejected due to timeout waiting for next frame in " "sequence", /* 16 */ "Association denied because AP is unable to handle additional" "associated stations", /* 17 */ "Association denied due to requesting station not supporting all of " "the data rates in BSSBasicRateSet parameter", /* 18 */ "Association denied due to requesting station not supporting " "short preamble operation", /* 19 */ "Association denied due to requesting station not supporting " "PBCC encoding", /* 20 */ "Association denied due to requesting station not supporting " "channel agility", /* 21 */ "Association request rejected because Spectrum Management " "capability is required", /* 22 */ "Association request rejected because the information in the " "Power Capability element is unacceptable", /* 23 */ "Association request rejected because the information in the " "Supported Channels element is unacceptable", /* 24 */ "Association denied due to requesting station not supporting " "short slot operation", /* 25 */ "Association denied due to requesting station not supporting " "DSSS-OFDM operation", /* 26 */ "Association denied because the requested STA does not support HT " "features", /* 27 */ "Reserved", /* 28 */ "Association denied because the requested STA does not support " "the PCO transition time required by the AP", /* 29 */ "Reserved", /* 30 */ "Reserved", /* 31 */ "Unspecified, QoS-related failure", /* 32 */ "Association denied due to QAP having insufficient bandwidth " "to handle another QSTA", /* 33 */ "Association denied due to excessive frame loss rates and/or " "poor conditions on current operating channel", /* 34 */ "Association (with QBSS) denied due to requesting station not " "supporting the QoS facility", /* 35 */ "Association denied due to requesting station not supporting " "Block Ack", /* 36 */ "The request has been declined", /* 37 */ "The request has not been successful as one or more parameters " "have invalid values", /* 38 */ "The TS has not been created because the request cannot be honored. " "Try again with the suggested changes to the TSPEC", /* 39 */ "Invalid Information Element", /* 40 */ "Group Cipher is not valid", /* 41 */ "Pairwise Cipher is not valid", /* 42 */ "AKMP is not valid", /* 43 */ "Unsupported RSN IE version", /* 44 */ "Invalid RSN IE Capabilities", /* 45 */ "Cipher suite is rejected per security policy", /* 46 */ "The TS has not been created. However, the HC may be capable of " "creating a TS, in response to a request, after the time indicated " "in the TS Delay element", /* 47 */ "Direct Link is not allowed in the BSS by policy", /* 48 */ "Destination STA is not present within this QBSS.", /* 49 */ "The Destination STA is not a QSTA.", /* 50 */ }; #define NUM_STATUSES (sizeof status_text / sizeof status_text[0]) static const char *reason_text[] = { "Reserved", /* 0 */ "Unspecified reason", /* 1 */ "Previous authentication no longer valid", /* 2 */ "Deauthenticated because sending station is leaving (or has left) " "IBSS or ESS", /* 3 */ "Disassociated due to inactivity", /* 4 */ "Disassociated because AP is unable to handle all currently " " associated stations", /* 5 */ "Class 2 frame received from nonauthenticated station", /* 6 */ "Class 3 frame received from nonassociated station", /* 7 */ "Disassociated because sending station is leaving " "(or has left) BSS", /* 8 */ "Station requesting (re)association is not authenticated with " "responding station", /* 9 */ "Disassociated because the information in the Power Capability " "element is unacceptable", /* 10 */ "Disassociated because the information in the SupportedChannels " "element is unacceptable", /* 11 */ "Invalid Information Element", /* 12 */ "Reserved", /* 13 */ "Michael MIC failure", /* 14 */ "4-Way Handshake timeout", /* 15 */ "Group key update timeout", /* 16 */ "Information element in 4-Way Handshake different from (Re)Association" "Request/Probe Response/Beacon", /* 17 */ "Group Cipher is not valid", /* 18 */ "AKMP is not valid", /* 20 */ "Unsupported RSN IE version", /* 21 */ "Invalid RSN IE Capabilities", /* 22 */ "IEEE 802.1X Authentication failed", /* 23 */ "Cipher suite is rejected per security policy", /* 24 */ "Reserved", /* 25 */ "Reserved", /* 26 */ "Reserved", /* 27 */ "Reserved", /* 28 */ "Reserved", /* 29 */ "Reserved", /* 30 */ "TS deleted because QoS AP lacks sufficient bandwidth for this " "QoS STA due to a change in BSS service characteristics or " "operational mode (e.g. an HT BSS change from 40 MHz channel " "to 20 MHz channel)", /* 31 */ "Disassociated for unspecified, QoS-related reason", /* 32 */ "Disassociated because QoS AP lacks sufficient bandwidth for this " "QoS STA", /* 33 */ "Disassociated because of excessive number of frames that need to be " "acknowledged, but are not acknowledged for AP transmissions " "and/or poor channel conditions", /* 34 */ "Disassociated because STA is transmitting outside the limits " "of its TXOPs", /* 35 */ "Requested from peer STA as the STA is leaving the BSS " "(or resetting)", /* 36 */ "Requested from peer STA as it does not want to use the " "mechanism", /* 37 */ "Requested from peer STA as the STA received frames using the " "mechanism for which a set up is required", /* 38 */ "Requested from peer STA due to time out", /* 39 */ "Reserved", /* 40 */ "Reserved", /* 41 */ "Reserved", /* 42 */ "Reserved", /* 43 */ "Reserved", /* 44 */ "Peer STA does not support the requested cipher suite", /* 45 */ "Association denied due to requesting STA not supporting HT " "features", /* 46 */ }; #define NUM_REASONS (sizeof reason_text / sizeof reason_text[0]) static int wep_print(netdissect_options *ndo, const u_char *p) { uint32_t iv; if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN)) return 0; iv = EXTRACT_LE_32BITS(p); ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv), IV_KEYID(iv))); return 1; } static int parse_elements(netdissect_options *ndo, struct mgmt_body_t *pbody, const u_char *p, int offset, u_int length) { u_int elementlen; struct ssid_t ssid; struct challenge_t challenge; struct rates_t rates; struct ds_t ds; struct cf_t cf; struct tim_t tim; /* * We haven't seen any elements yet. */ pbody->challenge_present = 0; pbody->ssid_present = 0; pbody->rates_present = 0; pbody->ds_present = 0; pbody->cf_present = 0; pbody->tim_present = 0; while (length != 0) { /* Make sure we at least have the element ID and length. */ if (!ND_TTEST2(*(p + offset), 2)) return 0; if (length < 2) return 0; elementlen = *(p + offset + 1); /* Make sure we have the entire element. */ if (!ND_TTEST2(*(p + offset + 2), elementlen)) return 0; if (length < elementlen + 2) return 0; switch (*(p + offset)) { case E_SSID: memcpy(&ssid, p + offset, 2); offset += 2; length -= 2; if (ssid.length != 0) { if (ssid.length > sizeof(ssid.ssid) - 1) return 0; if (!ND_TTEST2(*(p + offset), ssid.length)) return 0; if (length < ssid.length) return 0; memcpy(&ssid.ssid, p + offset, ssid.length); offset += ssid.length; length -= ssid.length; } ssid.ssid[ssid.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen an SSID IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ssid_present) { pbody->ssid = ssid; pbody->ssid_present = 1; } break; case E_CHALLENGE: memcpy(&challenge, p + offset, 2); offset += 2; length -= 2; if (challenge.length != 0) { if (challenge.length > sizeof(challenge.text) - 1) return 0; if (!ND_TTEST2(*(p + offset), challenge.length)) return 0; if (length < challenge.length) return 0; memcpy(&challenge.text, p + offset, challenge.length); offset += challenge.length; length -= challenge.length; } challenge.text[challenge.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen a challenge IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->challenge_present) { pbody->challenge = challenge; pbody->challenge_present = 1; } break; case E_RATES: memcpy(&rates, p + offset, 2); offset += 2; length -= 2; if (rates.length != 0) { if (rates.length > sizeof rates.rate) return 0; if (!ND_TTEST2(*(p + offset), rates.length)) return 0; if (length < rates.length) return 0; memcpy(&rates.rate, p + offset, rates.length); offset += rates.length; length -= rates.length; } /* * Present and not truncated. * * If we haven't already seen a rates IE, * copy this one if it's not zero-length, * otherwise ignore this one, so we later * report the first one we saw. * * We ignore zero-length rates IEs as some * devices seem to put a zero-length rates * IE, followed by an SSID IE, followed by * a non-zero-length rates IE into frames, * even though IEEE Std 802.11-2007 doesn't * seem to indicate that a zero-length rates * IE is valid. */ if (!pbody->rates_present && rates.length != 0) { pbody->rates = rates; pbody->rates_present = 1; } break; case E_DS: memcpy(&ds, p + offset, 2); offset += 2; length -= 2; if (ds.length != 1) { offset += ds.length; length -= ds.length; break; } ds.channel = *(p + offset); offset += 1; length -= 1; /* * Present and not truncated. * * If we haven't already seen a DS IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ds_present) { pbody->ds = ds; pbody->ds_present = 1; } break; case E_CF: memcpy(&cf, p + offset, 2); offset += 2; length -= 2; if (cf.length != 6) { offset += cf.length; length -= cf.length; break; } memcpy(&cf.count, p + offset, 6); offset += 6; length -= 6; /* * Present and not truncated. * * If we haven't already seen a CF IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->cf_present) { pbody->cf = cf; pbody->cf_present = 1; } break; case E_TIM: memcpy(&tim, p + offset, 2); offset += 2; length -= 2; if (tim.length <= 3) { offset += tim.length; length -= tim.length; break; } if (tim.length - 3 > (int)sizeof tim.bitmap) return 0; memcpy(&tim.count, p + offset, 3); offset += 3; length -= 3; memcpy(tim.bitmap, p + (tim.length - 3), (tim.length - 3)); offset += tim.length - 3; length -= tim.length - 3; /* * Present and not truncated. * * If we haven't already seen a TIM IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->tim_present) { pbody->tim = tim; pbody->tim_present = 1; } break; default: #if 0 ND_PRINT((ndo, "(1) unhandled element_id (%d) ", *(p + offset))); #endif offset += 2 + elementlen; length -= 2 + elementlen; break; } } /* No problems found. */ return 1; } /********************************************************************************* * Print Handle functions for the management frame types *********************************************************************************/ static int handle_beacon(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); ND_PRINT((ndo, " %s", CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS")); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_assoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_assoc_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.status_code = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_STATUS_LEN; length -= IEEE802_11_STATUS_LEN; pbody.aid = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_AID_LEN; length -= IEEE802_11_AID_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 , CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "", (pbody.status_code < NUM_STATUSES ? status_text[pbody.status_code] : "n/a"))); return ret; } static int handle_reassoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN); offset += IEEE802_11_AP_LEN; length -= IEEE802_11_AP_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap ))); return ret; } static int handle_reassoc_response(netdissect_options *ndo, const u_char *p, u_int length) { /* Same as a Association Reponse */ return handle_assoc_response(ndo, p, length); } static int handle_probe_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_probe_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_atim(void) { /* the frame body for ATIM is null. */ return 1; } static int handle_disassoc(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); ND_PRINT((ndo, ": %s", (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved")); return 1; } static int handle_auth(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, 6)) return 0; if (length < 6) return 0; pbody.auth_alg = EXTRACT_LE_16BITS(p); offset += 2; length -= 2; pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; pbody.status_code = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; ret = parse_elements(ndo, &pbody, p, offset, length); if ((pbody.auth_alg == 1) && ((pbody.auth_trans_seq_num == 2) || (pbody.auth_trans_seq_num == 3))) { ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, ((pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : ""))); return ret; } ND_PRINT((ndo, " (%s)-%x: %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, (pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : "")); return ret; } static int handle_deauth(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { struct mgmt_body_t pbody; const char *reason = NULL; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); reason = (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved"; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": %s", reason)); } else { ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason)); } return 1; } #define PRINT_HT_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \ (v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_BA_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \ (v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \ (v) == 2 ? ND_PRINT((ndo, "DELBA")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHLINK_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPEERING_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Open")) : \ (v) == 1 ? ND_PRINT((ndo, "Confirm")) : \ (v) == 2 ? ND_PRINT((ndo, "Close")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPATH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ (v) == 2 ? ND_PRINT((ndo, "Error")) : \ (v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \ (v) == 1 ? ND_PRINT((ndo, "HWMP")) : \ (v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \ (v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \ (v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \ (v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \ (v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \ (v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \ (v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \ (v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \ (v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MULTIHOP_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \ (v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_SELFPROT_ACTION(v) (\ (v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \ (v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \ (v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \ (v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \ (v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) static int handle_action(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { if (!ND_TTEST2(*p, 2)) return 0; if (length < 2) return 0; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": ")); } else { ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src))); } switch (p[0]) { case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break; case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break; case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break; case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break; case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break; case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break; case 14: ND_PRINT((ndo, "MultiohopAction ")); PRINT_MULTIHOP_ACTION(p[1]); break; case 15: ND_PRINT((ndo, "SelfprotectAction ")); PRINT_SELFPROT_ACTION(p[1]); break; case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break; default: ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1])); break; } return 1; } /********************************************************************************* * Print Body funcs *********************************************************************************/ static int mgmt_body_print(netdissect_options *ndo, uint16_t fc, const uint8_t *src, const u_char *p, u_int length) { ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc)))); /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) return wep_print(ndo, p); switch (FC_SUBTYPE(fc)) { case ST_ASSOC_REQUEST: return handle_assoc_request(ndo, p, length); case ST_ASSOC_RESPONSE: return handle_assoc_response(ndo, p, length); case ST_REASSOC_REQUEST: return handle_reassoc_request(ndo, p, length); case ST_REASSOC_RESPONSE: return handle_reassoc_response(ndo, p, length); case ST_PROBE_REQUEST: return handle_probe_request(ndo, p, length); case ST_PROBE_RESPONSE: return handle_probe_response(ndo, p, length); case ST_BEACON: return handle_beacon(ndo, p, length); case ST_ATIM: return handle_atim(); case ST_DISASSOC: return handle_disassoc(ndo, p, length); case ST_AUTH: return handle_auth(ndo, p, length); case ST_DEAUTH: return handle_deauth(ndo, src, p, length); case ST_ACTION: return handle_action(ndo, src, p, length); default: return 1; } } /********************************************************************************* * Handles printing all the control frame types *********************************************************************************/ static int ctrl_body_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc)))); switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: /* XXX - requires special handling */ break; case CTRL_BAR: if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: if (!ND_TTEST2(*p, CTRL_BA_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN)) return 0; ND_PRINT((ndo, " AID(%x)", EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid)))); break; case CTRL_RTS: if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: if (!ND_TTEST2(*p, CTRL_END_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra))); break; case CTRL_END_ACK: if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra))); break; } return 1; } /* * Data Frame - Address field contents * * To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4 * 0 | 0 | DA | SA | BSSID | n/a * 0 | 1 | DA | BSSID | SA | n/a * 1 | 0 | BSSID | SA | DA | n/a * 1 | 1 | RA | TA | DA | SA */ /* * Function to get source and destination MAC addresses for a data frame. */ static void get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc)) { if (!FC_FROM_DS(fc)) { /* not To DS and not From DS */ *srcp = ADDR2; *dstp = ADDR1; } else { /* not To DS and From DS */ *srcp = ADDR3; *dstp = ADDR1; } } else { if (!FC_FROM_DS(fc)) { /* From DS and not To DS */ *srcp = ADDR2; *dstp = ADDR3; } else { /* To DS and From DS */ *srcp = ADDR4; *dstp = ADDR3; } } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; if (srcp != NULL) *srcp = hp->sa; if (dstp != NULL) *dstp = hp->da; } /* * Print Header funcs */ static void data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { u_int subtype = FC_SUBTYPE(fc); if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) || DATA_FRAME_IS_QOS(subtype)) { ND_PRINT((ndo, "CF ")); if (DATA_FRAME_IS_CF_ACK(subtype)) { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Ack/Poll")); else ND_PRINT((ndo, "Ack")); } else { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Poll")); } if (DATA_FRAME_IS_QOS(subtype)) ND_PRINT((ndo, "+QoS")); ND_PRINT((ndo, " ")); } #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4))); } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void mgmt_header_print(netdissect_options *ndo, const u_char *p) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ", etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da), etheraddr_string(ndo, (hp)->sa))); } static void ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { switch (FC_SUBTYPE(fc)) { case CTRL_BAR: ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: ND_PRINT((ndo, "BSSID:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid), etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta))); break; case CTRL_RTS: ND_PRINT((ndo, "RA:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid))); break; case CTRL_END_ACK: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid))); break; default: /* We shouldn't get here - we should already have quit */ break; } } static int extract_header_length(netdissect_options *ndo, uint16_t fc) { int len; switch (FC_TYPE(fc)) { case T_MGMT: return MGMT_HDRLEN; case T_CTRL: switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: return CTRL_CONTROL_WRAPPER_HDRLEN; case CTRL_BAR: return CTRL_BAR_HDRLEN; case CTRL_BA: return CTRL_BA_HDRLEN; case CTRL_PS_POLL: return CTRL_PS_POLL_HDRLEN; case CTRL_RTS: return CTRL_RTS_HDRLEN; case CTRL_CTS: return CTRL_CTS_HDRLEN; case CTRL_ACK: return CTRL_ACK_HDRLEN; case CTRL_CF_END: return CTRL_END_HDRLEN; case CTRL_END_ACK: return CTRL_END_ACK_HDRLEN; default: ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc))); return 0; } case T_DATA: len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24; if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) len += 2; return len; default: ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc))); return 0; } } static int extract_mesh_header_length(const u_char *p) { return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3)); } /* * Print the 802.11 MAC header. */ static void ieee_802_11_hdr_print(netdissect_options *ndo, uint16_t fc, const u_char *p, u_int hdrlen, u_int meshdrlen) { if (ndo->ndo_vflag) { if (FC_MORE_DATA(fc)) ND_PRINT((ndo, "More Data ")); if (FC_MORE_FLAG(fc)) ND_PRINT((ndo, "More Fragments ")); if (FC_POWER_MGMT(fc)) ND_PRINT((ndo, "Pwr Mgmt ")); if (FC_RETRY(fc)) ND_PRINT((ndo, "Retry ")); if (FC_ORDER(fc)) ND_PRINT((ndo, "Strictly Ordered ")); if (FC_PROTECTED(fc)) ND_PRINT((ndo, "Protected ")); if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL) ND_PRINT((ndo, "%dus ", EXTRACT_LE_16BITS( &((const struct mgmt_header_t *)p)->duration))); } if (meshdrlen != 0) { const struct meshcntl_t *mc = (const struct meshcntl_t *)&p[hdrlen - meshdrlen]; int ae = mc->flags & 3; ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl, EXTRACT_LE_32BITS(mc->seq))); if (ae > 0) ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4))); if (ae > 1) ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5))); if (ae > 2) ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6))); ND_PRINT((ndo, ") ")); } switch (FC_TYPE(fc)) { case T_MGMT: mgmt_header_print(ndo, p); break; case T_CTRL: ctrl_header_print(ndo, fc, p); break; case T_DATA: data_header_print(ndo, fc, p); break; default: break; } } #ifndef roundup2 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #endif static const char tstr[] = "[|802.11]"; static u_int ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; } /* * This is the top level routine of the printer. 'p' points * to the 802.11 header of the packet, 'h->ts' is the timestamp, * 'h->len' is the length of the packet off the wire, and 'h->caplen' * is the number of bytes actually captured. */ u_int ieee802_11_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0); } /* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */ /* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */ /*- * Copyright (c) 2003, 2004 David Young. 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. * 3. The name of David Young may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``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 DAVID * YOUNG 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. */ /* A generic radio capture format is desirable. It must be * rigidly defined (e.g., units for fields should be given), * and easily extensible. * * The following is an extensible radio capture format. It is * based on a bitmap indicating which fields are present. * * I am trying to describe precisely what the application programmer * should expect in the following, and for that reason I tell the * units and origin of each measurement (where it applies), or else I * use sufficiently weaselly language ("is a monotonically nondecreasing * function of...") that I cannot set false expectations for lawyerly * readers. */ /* * The radio capture header precedes the 802.11 header. * * Note well: all radiotap fields are little-endian. */ struct ieee80211_radiotap_header { uint8_t it_version; /* Version 0. Only increases * for drastic changes, * introduction of compatible * new fields does not count. */ uint8_t it_pad; uint16_t it_len; /* length of the whole * header in bytes, including * it_version, it_pad, * it_len, and data fields. */ uint32_t it_present; /* A bitmap telling which * fields are present. Set bit 31 * (0x80000000) to extend the * bitmap by another 32 bits. * Additional extensions are made * by setting bit 31. */ }; /* Name Data type Units * ---- --------- ----- * * IEEE80211_RADIOTAP_TSFT uint64_t microseconds * * Value in microseconds of the MAC's 64-bit 802.11 Time * Synchronization Function timer when the first bit of the * MPDU arrived at the MAC. For received frames, only. * * IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap * * Tx/Rx frequency in MHz, followed by flags (see below). * Note that IEEE80211_RADIOTAP_XCHANNEL must be used to * represent an HT channel as there is not enough room in * the flags word. * * IEEE80211_RADIOTAP_FHSS uint16_t see below * * For frequency-hopping radios, the hop set (first byte) * and pattern (second byte). * * IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index * * Tx/Rx data rate. If bit 0x80 is set then it represents an * an MCS index and not an IEEE rate. * * IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from * one milliwatt (dBm) * * RF signal power at the antenna, decibel difference from * one milliwatt. * * IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from * one milliwatt (dBm) * * RF noise power at the antenna, decibel difference from one * milliwatt. * * IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB) * * RF signal power at the antenna, decibel difference from an * arbitrary, fixed reference. * * IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB) * * RF noise power at the antenna, decibel difference from an * arbitrary, fixed reference point. * * IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless * * Quality of Barker code lock. Unitless. Monotonically * nondecreasing with "better" lock strength. Called "Signal * Quality" in datasheets. (Is there a standard way to measure * this?) * * IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless * * Transmit power expressed as unitless distance from max * power set at factory calibration. 0 is max power. * Monotonically nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB) * * Transmit power expressed as decibel distance from max power * set at factory calibration. 0 is max power. Monotonically * nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from * one milliwatt (dBm) * * Transmit power expressed as dBm (decibels from a 1 milliwatt * reference). This is the absolute power level measured at * the antenna port. * * IEEE80211_RADIOTAP_FLAGS uint8_t bitmap * * Properties of transmitted and received frames. See flags * defined below. * * IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index * * Unitless indication of the Rx/Tx antenna for this packet. * The first antenna is antenna 0. * * IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap * * Properties of received frames. See flags defined below. * * IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap * uint16_t MHz * uint8_t channel number * uint8_t .5 dBm * * Extended channel specification: flags (see below) followed by * frequency in MHz, the corresponding IEEE channel number, and * finally the maximum regulatory transmit power cap in .5 dBm * units. This property supersedes IEEE80211_RADIOTAP_CHANNEL * and only one of the two should be present. * * IEEE80211_RADIOTAP_MCS uint8_t known * uint8_t flags * uint8_t mcs * * Bitset indicating which fields have known values, followed * by bitset of flag values, followed by the MCS rate index as * in IEEE 802.11n. * * * IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless * * Contains the AMPDU information for the subframe. * * IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16 * * Contains VHT information about this frame. * * IEEE80211_RADIOTAP_VENDOR_NAMESPACE * uint8_t OUI[3] * uint8_t subspace * uint16_t length * * The Vendor Namespace Field contains three sub-fields. The first * sub-field is 3 bytes long. It contains the vendor's IEEE 802 * Organizationally Unique Identifier (OUI). The fourth byte is a * vendor-specific "namespace selector." * */ enum ieee80211_radiotap_type { IEEE80211_RADIOTAP_TSFT = 0, IEEE80211_RADIOTAP_FLAGS = 1, IEEE80211_RADIOTAP_RATE = 2, IEEE80211_RADIOTAP_CHANNEL = 3, IEEE80211_RADIOTAP_FHSS = 4, IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5, IEEE80211_RADIOTAP_DBM_ANTNOISE = 6, IEEE80211_RADIOTAP_LOCK_QUALITY = 7, IEEE80211_RADIOTAP_TX_ATTENUATION = 8, IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9, IEEE80211_RADIOTAP_DBM_TX_POWER = 10, IEEE80211_RADIOTAP_ANTENNA = 11, IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12, IEEE80211_RADIOTAP_DB_ANTNOISE = 13, IEEE80211_RADIOTAP_RX_FLAGS = 14, /* NB: gap for netbsd definitions */ IEEE80211_RADIOTAP_XCHANNEL = 18, IEEE80211_RADIOTAP_MCS = 19, IEEE80211_RADIOTAP_AMPDU_STATUS = 20, IEEE80211_RADIOTAP_VHT = 21, IEEE80211_RADIOTAP_NAMESPACE = 29, IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30, IEEE80211_RADIOTAP_EXT = 31 }; /* channel attributes */ #define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */ #define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */ #define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */ #define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */ #define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */ #define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */ #define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */ #define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */ #define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */ #define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */ #define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */ #define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */ #define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */ #define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */ #define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */ /* Useful combinations of channel characteristics, borrowed from Ethereal */ #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IEEE80211_CHAN_TA \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO) #define IEEE80211_CHAN_TG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO) /* For IEEE80211_RADIOTAP_FLAGS */ #define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received * during CFP */ #define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received * with short * preamble */ #define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received * with WEP encryption */ #define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received * with fragmentation */ #define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */ #define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between * 802.11 header and payload * (to 32-bit boundary) */ #define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */ /* For IEEE80211_RADIOTAP_RX_FLAGS */ #define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */ #define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */ /* For IEEE80211_RADIOTAP_MCS known */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01 #define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */ #define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04 #define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20 #define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80 /* For IEEE80211_RADIOTAP_MCS flags */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3 #define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */ #define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60 #define IEEE80211_RADIOTAP_MCS_STBC_1 1 #define IEEE80211_RADIOTAP_MCS_STBC_2 2 #define IEEE80211_RADIOTAP_MCS_STBC_3 3 #define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80 /* For IEEE80211_RADIOTAP_AMPDU_STATUS */ #define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001 #define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002 #define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004 #define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020 /* For IEEE80211_RADIOTAP_VHT known */ #define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002 #define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040 #define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080 #define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100 /* For IEEE80211_RADIOTAP_VHT flags */ #define IEEE80211_RADIOTAP_VHT_STBC 0x01 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02 #define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f #define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f #define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0 #define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4 #define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01 #define IEEE80211_CHAN_FHSS \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK) #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_PUREG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IS_CHAN_FHSS(flags) \ ((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS) #define IS_CHAN_A(flags) \ ((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A) #define IS_CHAN_B(flags) \ ((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B) #define IS_CHAN_PUREG(flags) \ ((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG) #define IS_CHAN_G(flags) \ ((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G) #define IS_CHAN_ANYG(flags) \ (IS_CHAN_PUREG(flags) || IS_CHAN_G(flags)) static void print_chaninfo(netdissect_options *ndo, uint16_t freq, int flags, int presentflags) { ND_PRINT((ndo, "%u MHz", freq)); if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) { /* * We have the MCS field, so this is 11n, regardless * of what the channel flags say. */ ND_PRINT((ndo, " 11n")); } else { if (IS_CHAN_FHSS(flags)) ND_PRINT((ndo, " FHSS")); if (IS_CHAN_A(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11a/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11a/5Mhz")); else ND_PRINT((ndo, " 11a")); } if (IS_CHAN_ANYG(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11g/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11g/5Mhz")); else ND_PRINT((ndo, " 11g")); } else if (IS_CHAN_B(flags)) ND_PRINT((ndo, " 11b")); if (flags & IEEE80211_CHAN_TURBO) ND_PRINT((ndo, " Turbo")); } /* * These apply to 11n. */ if (flags & IEEE80211_CHAN_HT20) ND_PRINT((ndo, " ht/20")); else if (flags & IEEE80211_CHAN_HT40D) ND_PRINT((ndo, " ht/40-")); else if (flags & IEEE80211_CHAN_HT40U) ND_PRINT((ndo, " ht/40+")); ND_PRINT((ndo, " ")); } static int print_radiotap_field(netdissect_options *ndo, struct cpack_state *s, uint32_t bit, uint8_t *flagsp, uint32_t presentflags) { u_int i; int rc; switch (bit) { case IEEE80211_RADIOTAP_TSFT: { uint64_t tsft; rc = cpack_uint64(s, &tsft); if (rc != 0) goto trunc; ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft)); break; } case IEEE80211_RADIOTAP_FLAGS: { uint8_t flagsval; rc = cpack_uint8(s, &flagsval); if (rc != 0) goto trunc; *flagsp = flagsval; if (flagsval & IEEE80211_RADIOTAP_F_CFP) ND_PRINT((ndo, "cfp ")); if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE) ND_PRINT((ndo, "short preamble ")); if (flagsval & IEEE80211_RADIOTAP_F_WEP) ND_PRINT((ndo, "wep ")); if (flagsval & IEEE80211_RADIOTAP_F_FRAG) ND_PRINT((ndo, "fragmented ")); if (flagsval & IEEE80211_RADIOTAP_F_BADFCS) ND_PRINT((ndo, "bad-fcs ")); break; } case IEEE80211_RADIOTAP_RATE: { uint8_t rate; rc = cpack_uint8(s, &rate); if (rc != 0) goto trunc; /* * XXX On FreeBSD rate & 0x80 means we have an MCS. On * Linux and AirPcap it does not. (What about * Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?) * * This is an issue either for proprietary extensions * to 11a or 11g, which do exist, or for 11n * implementations that stuff a rate value into * this field, which also appear to exist. * * We currently handle that by assuming that * if the 0x80 bit is set *and* the remaining * bits have a value between 0 and 15 it's * an MCS value, otherwise it's a rate. If * there are cases where systems that use * "0x80 + MCS index" for MCS indices > 15, * or stuff a rate value here between 64 and * 71.5 Mb/s in here, we'll need a preference * setting. Such rates do exist, e.g. 11n * MCS 7 at 20 MHz with a long guard interval. */ if (rate >= 0x80 && rate <= 0x8f) { /* * XXX - we don't know the channel width * or guard interval length, so we can't * convert this to a data rate. * * If you want us to show a data rate, * use the MCS field, not the Rate field; * the MCS field includes not only the * MCS index, it also includes bandwidth * and guard interval information. * * XXX - can we get the channel width * from XChannel and the guard interval * information from Flags, at least on * FreeBSD? */ ND_PRINT((ndo, "MCS %u ", rate & 0x7f)); } else ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate)); break; } case IEEE80211_RADIOTAP_CHANNEL: { uint16_t frequency; uint16_t flags; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; /* * If CHANNEL and XCHANNEL are both present, skip * CHANNEL. */ if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL)) break; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_FHSS: { uint8_t hopset; uint8_t hoppat; rc = cpack_uint8(s, &hopset); if (rc != 0) goto trunc; rc = cpack_uint8(s, &hoppat); if (rc != 0) goto trunc; ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat)); break; } case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: { int8_t dbm_antsignal; rc = cpack_int8(s, &dbm_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal)); break; } case IEEE80211_RADIOTAP_DBM_ANTNOISE: { int8_t dbm_antnoise; rc = cpack_int8(s, &dbm_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise)); break; } case IEEE80211_RADIOTAP_LOCK_QUALITY: { uint16_t lock_quality; rc = cpack_uint16(s, &lock_quality); if (rc != 0) goto trunc; ND_PRINT((ndo, "%u sq ", lock_quality)); break; } case IEEE80211_RADIOTAP_TX_ATTENUATION: { uint16_t tx_attenuation; rc = cpack_uint16(s, &tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation)); break; } case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: { uint8_t db_tx_attenuation; rc = cpack_uint8(s, &db_tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation)); break; } case IEEE80211_RADIOTAP_DBM_TX_POWER: { int8_t dbm_tx_power; rc = cpack_int8(s, &dbm_tx_power); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power)); break; } case IEEE80211_RADIOTAP_ANTENNA: { uint8_t antenna; rc = cpack_uint8(s, &antenna); if (rc != 0) goto trunc; ND_PRINT((ndo, "antenna %u ", antenna)); break; } case IEEE80211_RADIOTAP_DB_ANTSIGNAL: { uint8_t db_antsignal; rc = cpack_uint8(s, &db_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB signal ", db_antsignal)); break; } case IEEE80211_RADIOTAP_DB_ANTNOISE: { uint8_t db_antnoise; rc = cpack_uint8(s, &db_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB noise ", db_antnoise)); break; } case IEEE80211_RADIOTAP_RX_FLAGS: { uint16_t rx_flags; rc = cpack_uint16(s, &rx_flags); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_XCHANNEL: { uint32_t flags; uint16_t frequency; uint8_t channel; uint8_t maxpower; rc = cpack_uint32(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint8(s, &channel); if (rc != 0) goto trunc; rc = cpack_uint8(s, &maxpower); if (rc != 0) goto trunc; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_MCS: { uint8_t known; uint8_t flags; uint8_t mcs_index; static const char *ht_bandwidth[4] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)" }; float htrate; rc = cpack_uint8(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &mcs_index); if (rc != 0) goto trunc; if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) { /* * We know the MCS index. */ if (mcs_index <= MAX_MCS_INDEX) { /* * And it's in-range. */ if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) { /* * And we know both the bandwidth and * the guard interval, so we can look * up the rate. */ htrate = ieee80211_float_htrates \ [mcs_index] \ [((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \ [((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)]; } else { /* * We don't know both the bandwidth * and the guard interval, so we can * only report the MCS index. */ htrate = 0.0; } } else { /* * The MCS value is out of range. */ htrate = 0.0; } if (htrate != 0.0) { /* * We have the rate. * Print it. */ ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index)); } else { /* * We at least have the MCS index. * Print it. */ ND_PRINT((ndo, "MCS %u ", mcs_index)); } } if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? "short" : "long")); } if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) { ND_PRINT((ndo, "%s ", (flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ? "greenfield" : "mixed")); } if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) { ND_PRINT((ndo, "%s FEC ", (flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) { ND_PRINT((ndo, "RX-STBC%u ", (flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT)); } break; } case IEEE80211_RADIOTAP_AMPDU_STATUS: { uint32_t reference_num; uint16_t flags; uint8_t delim_crc; uint8_t reserved; rc = cpack_uint32(s, &reference_num); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &delim_crc); if (rc != 0) goto trunc; rc = cpack_uint8(s, &reserved); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_VHT: { uint16_t known; uint8_t flags; uint8_t bandwidth; uint8_t mcs_nss[4]; uint8_t coding; uint8_t group_id; uint16_t partial_aid; static const char *vht_bandwidth[32] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)", "80 MHz", "80 MHz (L)", "80 MHz (U)", "80 MHz (LL)", "80 MHz (LU)", "80 MHz (UL)", "80 MHz (UU)", "160 MHz", "160 MHz (L)", "160 MHz (U)", "160 MHz (LL)", "160 MHz (LU)", "160 MHz (UL)", "160 MHz (UU)", "160 MHz (LLL)", "160 MHz (LLU)", "160 MHz (LUL)", "160 MHz (UUU)", "160 MHz (ULL)", "160 MHz (ULU)", "160 MHz (UUL)", "160 MHz (UUU)", "unknown (26)", "unknown (27)", "unknown (28)", "unknown (29)", "unknown (30)", "unknown (31)" }; rc = cpack_uint16(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &bandwidth); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { rc = cpack_uint8(s, &mcs_nss[i]); if (rc != 0) goto trunc; } rc = cpack_uint8(s, &coding); if (rc != 0) goto trunc; rc = cpack_uint8(s, &group_id); if (rc != 0) goto trunc; rc = cpack_uint16(s, &partial_aid); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { u_int nss, mcs; nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK; mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT; if (nss == 0) continue; ND_PRINT((ndo, "User %u MCS %u ", i, mcs)); ND_PRINT((ndo, "%s FEC ", (coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ? "short" : "long")); } break; } default: /* this bit indicates a field whose * size we do not know, so we cannot * proceed. Just print the bit number. */ ND_PRINT((ndo, "[bit %u] ", bit)); return -1; } return 0; trunc: ND_PRINT((ndo, "%s", tstr)); return rc; } static int print_in_radiotap_namespace(netdissect_options *ndo, struct cpack_state *s, uint8_t *flags, uint32_t presentflags, int bit0) { #define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x))) #define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x))) #define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x))) #define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x))) #define BITNO_2(x) (((x) & 2) ? 1 : 0) uint32_t present, next_present; int bitno; enum ieee80211_radiotap_type bit; int rc; for (present = presentflags; present; present = next_present) { /* * Clear the least significant bit that is set. */ next_present = present & (present - 1); /* * Get the bit number, within this presence word, * of the remaining least significant bit that * is set. */ bitno = BITNO_32(present ^ next_present); /* * Stop if this is one of the "same meaning * in all presence flags" bits. */ if (bitno >= IEEE80211_RADIOTAP_NAMESPACE) break; /* * Get the radiotap bit number of that bit. */ bit = (enum ieee80211_radiotap_type)(bit0 + bitno); rc = print_radiotap_field(ndo, s, bit, flags, presentflags); if (rc != 0) return rc; } return 0; } static u_int ieee802_11_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { #define BIT(n) (1U << n) #define IS_EXTENDED(__p) \ (EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0 struct cpack_state cpacker; const struct ieee80211_radiotap_header *hdr; uint32_t presentflags; const uint32_t *presentp, *last_presentp; int vendor_namespace; uint8_t vendor_oui[3]; uint8_t vendor_subnamespace; uint16_t skip_length; int bit0; u_int len; uint8_t flags; int pad; u_int fcslen; if (caplen < sizeof(*hdr)) { ND_PRINT((ndo, "%s", tstr)); return caplen; } hdr = (const struct ieee80211_radiotap_header *)p; len = EXTRACT_LE_16BITS(&hdr->it_len); /* * If we don't have the entire radiotap header, just give up. */ if (caplen < len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */ cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */ for (last_presentp = &hdr->it_present; (const u_char*)(last_presentp + 1) <= p + len && IS_EXTENDED(last_presentp); last_presentp++) cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */ /* are there more bitmap extensions than bytes in header? */ if ((const u_char*)(last_presentp + 1) > p + len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } /* * Start out at the beginning of the default radiotap namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; /* Assume no flags */ flags = 0; /* Assume no Atheros padding between 802.11 header and body */ pad = 0; /* Assume no FCS at end of frame */ fcslen = 0; for (presentp = &hdr->it_present; presentp <= last_presentp; presentp++) { presentflags = EXTRACT_LE_32BITS(presentp); /* * If this is a vendor namespace, we don't handle it. */ if (vendor_namespace) { /* * Skip past the stuff we don't understand. * If we add support for any vendor namespaces, * it'd be added here; use vendor_oui and * vendor_subnamespace to interpret the fields. */ if (cpack_advance(&cpacker, skip_length) != 0) { /* * Ran out of space in the packet. */ break; } /* * We've skipped it all; nothing more to * skip. */ skip_length = 0; } else { if (print_in_radiotap_namespace(ndo, &cpacker, &flags, presentflags, bit0) != 0) { /* * Fatal error - can't process anything * more in the radiotap header. */ break; } } /* * Handle the namespace switch bits; we've already handled * the extension bit in all but the last word above. */ switch (presentflags & (BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) { case 0: /* * We're not changing namespaces. * advance to the next 32 bits in the current * namespace. */ bit0 += 32; break; case BIT(IEEE80211_RADIOTAP_NAMESPACE): /* * We're switching to the radiotap namespace. * Reset the presence-bitmap index to 0, and * reset the namespace to the default radiotap * namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; break; case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE): /* * We're switching to a vendor namespace. * Reset the presence-bitmap index to 0, * note that we're in a vendor namespace, * and fetch the fields of the Vendor Namespace * item. */ bit0 = 0; vendor_namespace = 1; if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint16(&cpacker, &skip_length) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } break; default: /* * Illegal combination. The behavior in this * case is undefined by the radiotap spec; we * just ignore both bits. */ break; } } if (flags & IEEE80211_RADIOTAP_F_DATAPAD) pad = 1; /* Atheros padding */ if (flags & IEEE80211_RADIOTAP_F_FCS) fcslen = 4; /* FCS at end of packet */ return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad, fcslen); #undef BITNO_32 #undef BITNO_16 #undef BITNO_8 #undef BITNO_4 #undef BITNO_2 #undef BIT } static u_int ieee802_11_avs_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { uint32_t caphdr_len; if (caplen < 8) { ND_PRINT((ndo, "%s", tstr)); return caplen; } caphdr_len = EXTRACT_32BITS(p + 4); if (caphdr_len < 8) { /* * Yow! The capture header length is claimed not * to be large enough to include even the version * cookie or capture header length! */ ND_PRINT((ndo, "%s", tstr)); return caplen; } if (caplen < caphdr_len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return caphdr_len + ieee802_11_print(ndo, p + caphdr_len, length - caphdr_len, caplen - caphdr_len, 0, 0); } #define PRISM_HDR_LEN 144 #define WLANCAP_MAGIC_COOKIE_BASE 0x80211000 #define WLANCAP_MAGIC_COOKIE_V1 0x80211001 #define WLANCAP_MAGIC_COOKIE_V2 0x80211002 /* * For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header, * containing information such as radio information, which we * currently ignore. * * If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or * WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS * (currently, on Linux, there's no ARPHRD_ type for * DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM * for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for * the AVS header, and the first 4 bytes of the header are used to * indicate whether it's a Prism header or an AVS header). */ u_int prism_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t msgcode; if (caplen < 4) { ND_PRINT((ndo, "%s", tstr)); return caplen; } msgcode = EXTRACT_32BITS(p); if (msgcode == WLANCAP_MAGIC_COOKIE_V1 || msgcode == WLANCAP_MAGIC_COOKIE_V2) return ieee802_11_avs_radio_print(ndo, p, length, caplen); if (caplen < PRISM_HDR_LEN) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN, length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0); } /* * For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra * header, containing information such as radio information. */ u_int ieee802_11_radio_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_radio_print(ndo, p, h->len, h->caplen); } /* * For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an * extra header, containing information such as radio information, * which we currently ignore. */ u_int ieee802_11_radio_avs_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2660_0
crossvul-cpp_data_bad_142_0
/* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */ #if 0 http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set #endif #include <string.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> static RDESContext desctx; typedef struct _cpu_const_tag { const char *const key; ut8 type; ut32 value; ut8 size; } CPU_CONST; #define CPU_CONST_NONE 0 #define CPU_CONST_PARAM 1 #define CPU_CONST_REG 2 typedef struct _cpu_model_tag { const char *const model; int pc; char *inherit; struct _cpu_model_tag *inherit_cpu_p; CPU_CONST *consts[10]; } CPU_MODEL; typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu); typedef struct _opcodes_tag_ { const char *const name; int mask; int selector; inst_handler_t handler; int cycles; int size; ut64 type; } OPCODE_DESC; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu); #define CPU_MODEL_DECL(model, pc, consts) \ { \ model, \ pc, \ consts \ } #define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits)))) #define CPU_PC_MASK(cpu) MASK((cpu)->pc) #define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0)) #define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu) #define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T } #define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK } #define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu) #define INST_INVALID { *fail = 1; return; } #define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } } #define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__) #define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s)) // Following IO definitions are valid for: // ATmega8 // ATmega88 CPU_CONST cpu_reg_common[] = { { "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) }, { "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) }, { "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) }, { "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_common[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_xmega128a4u[] = { { "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_5_bits[] = { { "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_7_bits[] = { { "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_MODEL cpu_models[] = { { .model = "ATmega640", .pc = 15, .consts = { cpu_reg_common, cpu_memsize_m640_m1280m_m1281_m2560_m2561, cpu_pagesize_7_bits, NULL }, }, { .model = "ATxmega128a4u", .pc = 17, .consts = { cpu_reg_common, cpu_memsize_xmega128a4u, cpu_pagesize_7_bits, NULL } }, { .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega88", .pc = 8, .inherit = "ATmega8" }, // CPU_MODEL_DECL ("ATmega168", 13, 512, 512), // last model is the default AVR - ATmega8 forever! { .model = "ATmega8", .pc = 13, .consts = { cpu_reg_common, cpu_memsize_common, cpu_pagesize_5_bits, NULL } }, }; static CPU_MODEL *get_cpu_model(char *model); static CPU_MODEL *__get_cpu_model_recursive(char *model) { CPU_MODEL *cpu = NULL; for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) { if (!strcasecmp (model, cpu->model)) { break; } } // fix inheritance tree if (cpu->inherit && !cpu->inherit_cpu_p) { cpu->inherit_cpu_p = get_cpu_model (cpu->inherit); if (!cpu->inherit_cpu_p) { eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit); } } return cpu; } static CPU_MODEL *get_cpu_model(char *model) { static CPU_MODEL *cpu = NULL; // cached value? if (cpu && !strcasecmp (model, cpu->model)) return cpu; // do the real search cpu = __get_cpu_model_recursive (model); return cpu; } static ut32 const_get_value(CPU_CONST *c) { return c ? MASK (c->size * 8) & c->value : 0; } static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem->key; citem++) { if (!strcmp (c, citem->key) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_name (cpu->inherit_cpu_p, type, c); eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c); return NULL; } static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) { char *t = r_anal_esil_pop (esil); if (!t || !r_anal_esil_get_parm (esil, t, v)) { free (t); return false; } free (t); return true; } static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem && citem->key; citem++) { if (citem->value == (MASK (citem->size * 8) & v) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_value (cpu->inherit_cpu_p, type, v); return NULL; } static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) { RStrBuf *r = r_strbuf_new (""); CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port); if (c != NULL) { r_strbuf_set (r, c->key); if (write) { r_strbuf_append (r, ",="); } } else { r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : ""); } return r; } static void __generic_bitop_flags(RAnalOp *op) { ESIL_A ("0,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S } static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) { if (ireg) { // preincrement index register if (prepostdec < 0) { ESIL_A ("1,%c,-,%c,=,", ireg, ireg); } // set register index address ESIL_A ("%c,", ireg); // add offset if (offset != 0) { ESIL_A ("%d,+,", offset); } } else { ESIL_A ("%d,", offset); } if (use_ramp) { ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd'); } // set SRAM base address ESIL_A ("_%s,+,", mem); // read/write from SRAM ESIL_A ("%s[1],", st ? "=" : ""); // postincrement index register if (ireg && prepostdec > 0) { ESIL_A ("1,%c,+,%c,=,", ireg, ireg); } } static void __generic_pop(RAnalOp *op, int sz) { if (sz > 1) { ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1) ESIL_A ("[%d],", sz); // read value ESIL_A ("%d,sp,+=,", sz); // sp += item_size } else { ESIL_A ("1,sp,+=," // increment stack pointer "sp,_ram,+,[1],"); // load SRAM[sp] } } static void __generic_push(RAnalOp *op, int sz) { ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp) if (sz > 1) { ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz' } ESIL_A ("=[%d],", sz); // store value in stack ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer } static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) { __generic_add_update_flags(op, 'r', d, 'r', r); } static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&," "%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N if (carry) ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z else ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&," "%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) { __generic_sub_update_flags(op, 'r', d, 'r', r, carry); } static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) { __generic_sub_update_flags(op, 'r', d, 'k', k, carry); } INST_HANDLER (adc) { // ADC Rd, Rr // ROL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (add) { // ADD Rd, Rr // LSL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr // FLAGS: ESIL_A ("r%d,0x80,&,!," // V "0,RPICK,0x8000,&,!,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!,!," // C "0,RPICK,0x8000,&,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (and) { // AND Rd, Rr // TST Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (andi) { // ANDI Rd, K // CBR Rd, K (= ANDI Rd, 1-K) if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f); op->val = k; ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (asr) { // ASR Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7 ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (bclr) { // BCLR s // CLC // CLH // CLI // CLN // CLR // CLS // CLT // CLV // CLZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s); } INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } INST_HANDLER (brbx) { // BRBC s, k // BRBS s, k // BRBC/S 0: BRCC BRCS // BRSH BRLO // BRBC/S 1: BREQ BRNE // BRBC/S 2: BRPL BRMI // BRBC/S 3: BRVC BRVS // BRBC/S 4: BRGE BRLT // BRBC/S 5: BRHC BRHS // BRBC/S 6: BRTC BRTS // BRBC/S 7: BRID BRIE int s = buf[0] & 0x7; op->jump = op->addr + ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2)) | (buf[1] & 0x2 ? ~((int) 0x7f) : 0)) + 2; op->fail = op->addr + op->size; op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s) ESIL_A (buf[1] & 0x4 ? "!," // BRBC => branch if cleared : "!,!,"); // BRBS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (break) { // BREAK ESIL_A ("BREAK"); } INST_HANDLER (bset) { // BSET s // SEC // SEH // SEI // SEN // SER // SES // SET // SEV // SEZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("%d,1,<<,sreg,|=,", s); } INST_HANDLER (bst) { // BST Rd, b if (len < 2) { return; } ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r buf[0] & 0x7); // b } INST_HANDLER (call) { // CALL k if (len < 4) { return; } op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->fail = op->addr + op->size; op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // AT*mega optimizes one cycle } ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (cbi) { // CBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->family = R_ANAL_OP_FAMILY_IO; op->type2 = 1; op->val = a; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (com) { // COM Rd int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd // FLAGS: ESIL_A ("0,cf,=,"); // C __generic_bitop_flags (op); // ...rest... } INST_HANDLER (cp) { // CP Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) } INST_HANDLER (cpc) { // CPC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) } INST_HANDLER (cpi) { // CPI Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); ESIL_A ("%d,r%d,-,", k, d); // Rd - k __generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry) } INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (dec) { // DEC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("-1,r%d,+,", d); // --Rd // FLAGS: ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (des) { // DES k if (desctx.round < 16) { //DES op->type = R_ANAL_OP_TYPE_CRYPTO; op->cycles = 1; //redo this r_strbuf_setf (&op->esil, "%d,des", desctx.round); } } INST_HANDLER (eijmp) { // EIJMP ut64 z, eind; // read z and eind for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = ((eind << 16) + z) << 1; // jump ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,"); // cycles op->cycles = 2; } INST_HANDLER (eicall) { // EICALL // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard EIJMP INST_CALL (eijmp); // fix cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4; } INST_HANDLER (elpm) { // ELPM // ELPM Rd // ELPM Rd, Z+ int d = ((buf[1] & 0xfe) == 0x90) ? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd : 0; // R0 ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z ESIL_A ("r%d,=,", d); // Rd = [1] if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) { ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z) } } INST_HANDLER (eor) { // EOR Rd, Rr // CLR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (fmul) { // FMUL Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmuls) { // FMULS Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmulsu) { // FMULSU Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d", r); // unsigned Rr ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (ijmp) { // IJMP k ut64 z; // read z for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = z << 1; op->cycles = 2; ESIL_A ("1,z,<<,pc,=,"); // jump! } INST_HANDLER (icall) { // ICALL k // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard IJMP INST_CALL (ijmp); // fix cycles if (!STR_BEGINS (cpu->model, "ATxmega")) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } INST_HANDLER (inc) { // INC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("1,r%d,+,", d); // ++Rd // FLAGS: ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (jmp) { // JMP k op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->cycles = 3; ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (lac) { // LAC Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (las) { // LAS Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,|,", d); // 0: (Z) | Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (lat) { // LAT Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (ld) { // LD Rd, X // LD Rd, X+ // LD Rd, -X // read memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post incremented : 0, // no increment 0, // offset always 0 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[0] & 0x3) == 0 ? 2 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z // LD Rd, Y+ LD Rd, Z+ // LD Rd, -Y LD Rd, -Z // LD Rd, Y+q LD Rd, Z+q // calculate offset (this value only has sense in some opcodes, // but we are optimistic and we calculate it always) int offset = (buf[1] & 0x20) | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7); // read memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? offset : 0, // offset or not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[1] & 0x10) == 0 ? (!offset ? 1 : 3) // LDD : (buf[0] & 0x3) == 0 ? 1 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldi) { // LDI Rd, K int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4); int d = ((buf[0] >> 4) & 0xf) + 16; op->val = k; ESIL_A ("0x%x,r%d,=,", k, d); } INST_HANDLER (lds) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; // load value from RAMPD:k __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } #if 0 INST_HANDLER (lds16) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x30) | ((buf[1] << 4) & 0x40) | (~(buf[1] << 4) & 0x80); op->ptr = k; // load value from @k __generic_ld_st (op, "ram", 0, 0, 0, k, 0); ESIL_A ("r%d,=,", d); } #endif INST_HANDLER (lpm) { // LPM // LPM Rd, Z // LPM Rd, Z+ ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]); // read program memory __generic_ld_st ( op, "prog", 'z', // index register Y/Z 1, // use RAMP* registers (ins & 0xfe0f) == 0x9005 ? 1 // post incremented : 0, // no increment 0, // not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", (ins == 0x95c8) ? 0 // LPM (r0) : ((buf[0] >> 4) & 0xf) // LPM Rd | ((buf[1] & 0x1) << 4)); } INST_HANDLER (lsr) { // LSR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1) ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (mov) { // MOV Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,=,", r, d); } INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr int d = (buf[0] & 0xf0) >> 3; int r = (buf[0] & 0x0f) << 1; ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1); } INST_HANDLER (mul) { // MUL Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (muls) { // MULS Rd, Rr int d = (buf[0] >> 4 & 0x0f) + 16; int r = (buf[0] & 0x0f) + 16; ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (mulsu) { // MULSU Rd, Rr int d = (buf[0] >> 4 & 0x07) + 16; int r = (buf[0] & 0x07) + 16; ESIL_A ("r%d,", r); // unsigned Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (neg) { // NEG Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd) ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N ESIL_A ("DUP,!,zf,=,"); // Z ESIL_A ("DUP,!,!,cf,=,"); // C ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (nop) { // NOP ESIL_A (",,"); } INST_HANDLER (or) { // OR Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (ori) { // ORI Rd, K // SBR Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); op->val = k; ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (out) { // OUT A, Rr int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_dst = __generic_io_dest (a, 1, cpu); op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst)); r_strbuf_free (io_dst); } INST_HANDLER (pop) { // POP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); __generic_pop (op, 1); ESIL_A ("r%d,=,", d); // store in Rd } INST_HANDLER (push) { // PUSH Rr int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("r%d,", r); // load Rr __generic_push (op, 1); // push it into stack // cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 1 // AT*mega optimizes one cycle : 2; } INST_HANDLER (rcall) { // RCALL k // target address op->jump = (op->addr + (((((buf[1] & 0xf) << 8) | buf[0]) << 1) | (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0))) + 2) & CPU_PC_MASK (cpu); op->fail = op->addr + op->size; // esil ESIL_A ("pc,"); // esil already points to next // instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! // cycles if (!strncasecmp (cpu->model, "ATtiny", 6)) { op->cycles = 4; // ATtiny is always slow } else { // PC size decides required runtime! op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // ATxmega optimizes one cycle } } } INST_HANDLER (ret) { // RET op->eob = true; // esil __generic_pop (op, CPU_PC_SIZE (cpu)); ESIL_A ("pc,=,"); // jump! // cycles if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit op->cycles++; // (i.e. a 22-bit bus), add one extra cycle } } INST_HANDLER (reti) { // RETI //XXX: There are not privileged instructions in ATMEL/AVR op->family = R_ANAL_OP_FAMILY_PRIV; // first perform a standard 'ret' INST_CALL (ret); // RETI: The I-bit is cleared by hardware after an interrupt // has occurred, and is set by the RETI instruction to enable // subsequent interrupts ESIL_A ("1,if,=,"); } INST_HANDLER (rjmp) { // RJMP k op->jump = (op->addr #ifdef _MSC_VER #pragma message ("anal_avr.c: WARNING: Probably broken on windows") + ((((( buf[1] & 0xf) << 9) | (buf[0] << 1))) | (buf[1] & 0x8 ? ~(0x1fff) : 0)) #else + ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1))) | (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0)) #endif + 2) & CPU_PC_MASK (cpu); ESIL_A ("%"PFMT64d",pc,=,", op->jump); } INST_HANDLER (ror) { // ROR Rd int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7) ESIL_A ("r%d,1,&,cf,=,", d); // C ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (sbc) { // SBC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C) __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbci) { // SBCI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sub) { // SUB Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k) __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (subi) { // SUBI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbi) { // SBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (sbix) { // SBIC A, b // SBIS A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RAnalOp next_op; RStrBuf *io_port; op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBIC => branch if 0 : "!,!,"); // SBIS => branch if 1 ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp r_strbuf_free (io_port); } INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr) ESIL_A ("r%d,0x80,&,!,!," // V "0,RPICK,0x8000,&,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!," // C "0,RPICK,0x8000,&,!,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (sbrx) { // SBRC Rr, b // SBRS Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (sleep) { // SLEEP ESIL_A ("BREAK"); } INST_HANDLER (spm) { // SPM Z+ ut64 spmcsr; // read SPM Control Register (SPMCR) r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL); // clear SPMCSR ESIL_A ("0x7c,spmcsr,&=,"); // decide action depending on the old value of SPMCSR switch (spmcsr & 0x7f) { case 0x03: // PAGE ERASE // invoke SPM_CLEAR_PAGE (erases target page writing // the 0xff value ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_ERASE,"); // do magic break; case 0x01: // FILL TEMPORARY BUFFER ESIL_A ("r1,r0,"); // push data ESIL_A ("z,"); // push target address ESIL_A ("SPM_PAGE_FILL,"); // do magic break; case 0x05: // WRITE PAGE ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_WRITE,"); // do magic break; default: eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n", (unsigned int) spmcsr); } op->cycles = 1; // This is truly false. Datasheets do not publish how // many cycles this instruction uses in all its // operation modes and I am pretty sure that this value // can vary substantially from one MCU type to another. // So... one cycle is fine. } INST_HANDLER (st) { // ST X, Rr // ST X+, Rr // ST -X, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post increment : 0, // no increment 0, // offset always 0 1); // store operation (st) // // cycles // op->cycles = buf[0] & 0x3 == 0 // ? 2 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (std) { // ST Y, Rr ST Z, Rr // ST Y+, Rr ST Z+, Rr // ST -Y, Rr ST -Z, Rr // ST Y+q, Rr ST Z+q, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? (buf[1] & 0x20) // offset | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7) : 0, // no offset 1); // load operation (!st) // // cycles // op->cycles = // buf[1] & 0x1 == 0 // ? !(offset ? 1 : 3) // LDD // : buf[0] & 0x3 == 0 // ? 1 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (swap) { // SWAP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf ESIL_A ("|,", d); // S[0] | S[1] ESIL_A ("r%d,=,", d); // Rd = result } OPCODE_DESC opcodes[] = { // op mask select cycles size type INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ... INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+ INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+ INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+ INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+ INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A //INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr INST_LAST }; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) { CPU_MODEL *cpu; ut64 offset; // init op if (!op) { return 2; } // select cpu info cpu = get_cpu_model (anal->cpu); // set memory layout registers if (anal->esil) { offset = 0; r_anal_esil_reg_write (anal->esil, "_prog", offset); offset += (1 << cpu->pc); r_anal_esil_reg_write (anal->esil, "_io", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start")); r_anal_esil_reg_write (anal->esil, "_sram", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size")); r_anal_esil_reg_write (anal->esil, "_eeprom", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size")); r_anal_esil_reg_write (anal->esil, "_page", offset); } // process opcode avr_op_analyze (anal, op, addr, buf, len, cpu); return op->size; } static int avr_custom_des (RAnalEsil *esil) { ut64 key, encrypt, text,des_round; ut32 key_lo, key_hi, buf_lo, buf_hi; if (!esil || !esil->anal || !esil->anal->reg) { return false; } if (!__esil_pop_argument (esil, &des_round)) { return false; } r_anal_esil_reg_read (esil, "hf", &encrypt, NULL); r_anal_esil_reg_read (esil, "deskey", &key, NULL); r_anal_esil_reg_read (esil, "text", &text, NULL); key_lo = key & UT32_MAX; key_hi = key >> 32; buf_lo = text & UT32_MAX; buf_hi = text >> 32; if (des_round != desctx.round) { desctx.round = des_round; } if (!desctx.round) { int i; //generating all round keys r_des_permute_key (&key_lo, &key_hi); for (i = 0; i < 16; i++) { r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi); } r_des_permute_block0 (&buf_lo, &buf_hi); } if (encrypt) { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]); } else { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]); } if (desctx.round == 15) { r_des_permute_block1 (&buf_hi, &buf_lo); desctx.round = 0; } else { desctx.round++; } r_anal_esil_reg_write (esil, "text", text); return true; } // ESIL operation SPM_PAGE_ERASE static int avr_custom_spm_page_erase(RAnalEsil *esil) { CPU_MODEL *cpu; ut8 c; ut64 addr, page_size_bits, i; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument(esil, &addr)) { return false; } // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align base address to page_size_bits addr &= ~(MASK (page_size_bits)); // perform erase //eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); c = 0xff; for (i = 0; i < (1ULL << page_size_bits); i++) { r_anal_esil_mem_write ( esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1); } return true; } // ESIL operation SPM_PAGE_FILL static int avr_custom_spm_page_fill(RAnalEsil *esil) { CPU_MODEL *cpu; ut64 addr, page_size_bits, i; ut8 r0, r1; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address, r0, r1 if (!__esil_pop_argument(esil, &addr)) { return false; } if (!__esil_pop_argument (esil, &i)) { return false; } r0 = i; if (!__esil_pop_argument (esil, &i)) { return false; } r1 = i; // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align and crop base address addr &= (MASK (page_size_bits) ^ 1); // perform write to temporary page //eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr); r_anal_esil_mem_write (esil, addr++, &r0, 1); r_anal_esil_mem_write (esil, addr++, &r1, 1); return true; } // ESIL operation SPM_PAGE_WRITE static int avr_custom_spm_page_write(RAnalEsil *esil) { CPU_MODEL *cpu; char *t = NULL; ut64 addr, page_size_bits, tmp_page; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument (esil, &addr)) { return false; } // get details about current MCU and fix input address and base address // of the internal temporary page cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL); // align base address to page_size_bits addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu)); // perform writing //eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); if (!(t = malloc (1 << page_size_bits))) { eprintf ("Cannot alloc a buffer for copying the temporary page.\n"); return false; } r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits); r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits); return true; } static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) { CPU_MODEL *cpu; if (!esil || !esil->anal) { return 0; } // select cpu info cpu = get_cpu_model (esil->anal->cpu); // crop registers and force certain values if (!strcmp (name, "pc")) { *val &= CPU_PC_MASK (cpu); } else if (!strcmp (name, "pcl")) { if (cpu->pc < 8) { *val &= MASK (8); } } else if (!strcmp (name, "pch")) { *val = cpu->pc > 8 ? *val & MASK (cpu->pc - 8) : 0; } return 0; } static int esil_avr_init(RAnalEsil *esil) { if (!esil) { return false; } desctx.round = 0; r_anal_esil_set_op (esil, "des", avr_custom_des); r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase); r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill); r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write); esil->cb.hook_reg_write = esil_avr_hook_reg_write; return true; } static int esil_avr_fini(RAnalEsil *esil) { return true; } static int set_reg_profile(RAnal *anal) { const char *p = "=PC pcl\n" "=SP sp\n" // explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html // and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file "=A0 r25\n" "=A1 r24\n" "=A2 r23\n" "=A3 r22\n" "=R0 r24\n" #if 0 PC: 16- or 22-bit program counter SP: 8- or 16-bit stack pointer SREG: 8-bit status register RAMPX, RAMPY, RAMPZ, RAMPD and EIND: #endif // 8bit registers x 32 "gpr r0 .8 0 0\n" "gpr r1 .8 1 0\n" "gpr r2 .8 2 0\n" "gpr r3 .8 3 0\n" "gpr r4 .8 4 0\n" "gpr r5 .8 5 0\n" "gpr r6 .8 6 0\n" "gpr r7 .8 7 0\n" "gpr text .64 0 0\n" "gpr r8 .8 8 0\n" "gpr r9 .8 9 0\n" "gpr r10 .8 10 0\n" "gpr r11 .8 11 0\n" "gpr r12 .8 12 0\n" "gpr r13 .8 13 0\n" "gpr r14 .8 14 0\n" "gpr r15 .8 15 0\n" "gpr deskey .64 8 0\n" "gpr r16 .8 16 0\n" "gpr r17 .8 17 0\n" "gpr r18 .8 18 0\n" "gpr r19 .8 19 0\n" "gpr r20 .8 20 0\n" "gpr r21 .8 21 0\n" "gpr r22 .8 22 0\n" "gpr r23 .8 23 0\n" "gpr r24 .8 24 0\n" "gpr r25 .8 25 0\n" "gpr r26 .8 26 0\n" "gpr r27 .8 27 0\n" "gpr r28 .8 28 0\n" "gpr r29 .8 29 0\n" "gpr r30 .8 30 0\n" "gpr r31 .8 31 0\n" // 16 bit overlapped registers for 16 bit math "gpr r17:r16 .16 16 0\n" "gpr r19:r18 .16 18 0\n" "gpr r21:r20 .16 20 0\n" "gpr r23:r22 .16 22 0\n" "gpr r25:r24 .16 24 0\n" "gpr r27:r26 .16 26 0\n" "gpr r29:r28 .16 28 0\n" "gpr r31:r30 .16 30 0\n" // 16 bit overlapped registers for memory addressing "gpr x .16 26 0\n" "gpr y .16 28 0\n" "gpr z .16 30 0\n" // program counter // NOTE: program counter size in AVR depends on the CPU model. It seems that // the PC may range from 16 bits to 22 bits. "gpr pc .32 32 0\n" "gpr pcl .16 32 0\n" "gpr pch .16 34 0\n" // special purpose registers "gpr sp .16 36 0\n" "gpr spl .8 36 0\n" "gpr sph .8 37 0\n" // status bit register (SREG) "gpr sreg .8 38 0\n" "gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts. "gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero. "gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result. "gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow. "gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison. "gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic. "gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit. "gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled. // 8bit segment registers to be added to X, Y, Z to get 24bit offsets "gpr rampx .8 39 0\n" "gpr rampy .8 40 0\n" "gpr rampz .8 41 0\n" "gpr rampd .8 42 0\n" "gpr eind .8 43 0\n" // memory mapping emulator registers // _prog // the program flash. It has its own address space. // _ram // _io // start of the data addres space. It is the same address of IO, // because IO is the first memory space addressable in the AVR. // _sram // start of the SRAM (this offset depends on IO size, and it is // inside the _ram address space) // _eeprom // this is another address space, outside ram and flash // _page // this is the temporary page used by the SPM instruction. This // memory is not directly addressable and it is used internally by // the CPU when autoflashing. "gpr _prog .32 44 0\n" "gpr _page .32 48 0\n" "gpr _eeprom .32 52 0\n" "gpr _ram .32 56 0\n" "gpr _io .32 56 0\n" "gpr _sram .32 60 0\n" // other important MCU registers // spmcsr/spmcr // Store Program Memory Control and Status Register (SPMCSR) "gpr spmcsr .8 64 0\n" ; return r_reg_set_profile_string (anal->reg, p); } static int archinfo(RAnal *anal, int q) { if (q == R_ANAL_ARCHINFO_ALIGN) return 2; if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE) return 4; if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE) return 2; return 2; // XXX } static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) { RAnalOp *op = NULL; ut8 *ret = NULL; int idx; if (!(op = r_anal_op_new ())) { return NULL; } if (!(ret = malloc (size))) { r_anal_op_free (op); return NULL; } memset (ret, 0xff, size); CPU_MODEL *cpu = get_cpu_model (anal->cpu); for (idx = 0; idx + 1 < size; idx += op->size) { OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu); if (op->size < 1) { break; } if (!opcode_desc) { // invalid instruction continue; } // the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching // (things like memory offsets or jump addresses) if (op->size == 4) { ret[idx + 2] = 0; ret[idx + 3] = 0; } if (op->ptr != UT64_MAX || op->jump != UT64_MAX) { ret[idx] = opcode_desc->mask; ret[idx + 1] = opcode_desc->mask >> 8; } } r_anal_op_free (op); return ret; } RAnalPlugin r_anal_plugin_avr = { .name = "avr", .desc = "AVR code analysis plugin", .license = "LGPL3", .arch = "avr", .esil = true, .archinfo = archinfo, .bits = 8 | 16, // 24 big regs conflicts .op = &avr_op, .set_reg_profile = &set_reg_profile, .esil_init = esil_avr_init, .esil_fini = esil_avr_fini, .anal_mask = anal_mask_avr, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_avr, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_142_0
crossvul-cpp_data_good_145_0
/* radare - LGPL - Copyright 2010-2018 - nibble, pancake */ #include <stdio.h> #include <r_types.h> #include <r_util.h> #include "mach0.h" #define bprintf if (bin->verbose) eprintf typedef struct _ulebr { ut8 *p; } ulebr; // OMG; THIS SHOULD BE KILLED; this var exposes the local native endian, which is completely unnecessary static bool little_; static ut64 read_uleb128(ulebr *r, ut8 *end) { ut64 result = 0; int bit = 0; ut64 slice = 0; ut8 *p = r->p; do { if (p == end) { eprintf ("malformed uleb128"); break; } slice = *p & 0x7f; if (bit > 63) { eprintf ("uleb128 too big for uint64, bit=%d, result=0x%"PFMT64x, bit, result); } else { result |= (slice << bit); bit += 7; } } while (*p++ & 0x80); r->p = p; return result; } static st64 read_sleb128(ulebr *r, ut8 *end) { st64 result = 0; int bit = 0; ut8 byte = 0; ut8 *p = r->p; do { if (p == end) { eprintf ("malformed sleb128"); break; } byte = *p++; result |= (((st64)(byte & 0x7f)) << bit); bit += 7; } while (byte & 0x80); // sign extend negative numbers if ((byte & 0x40)) { result |= (-1LL) << bit; } r->p = p; return result; } static ut64 entry_to_vaddr(struct MACH0_(obj_t)* bin) { switch (bin->main_cmd.cmd) { case LC_MAIN: return bin->entry + bin->baddr; case LC_UNIXTHREAD: case LC_THREAD: return bin->entry; default: return 0; } } static ut64 addr_to_offset(struct MACH0_(obj_t)* bin, ut64 addr) { ut64 segment_base, segment_size; int i; if (!bin->segs) { return 0; } for (i = 0; i < bin->nsegs; i++) { segment_base = (ut64)bin->segs[i].vmaddr; segment_size = (ut64)bin->segs[i].vmsize; if (addr >= segment_base && addr < segment_base + segment_size) { return bin->segs[i].fileoff + (addr - segment_base); } } return 0; } static int init_hdr(struct MACH0_(obj_t)* bin) { ut8 magicbytes[4] = {0}; ut8 machohdrbytes[sizeof (struct MACH0_(mach_header))] = {0}; int len; if (r_buf_read_at (bin->b, 0, magicbytes, 4) < 1) { return false; } if (r_read_le32 (magicbytes) == 0xfeedface) { bin->big_endian = false; } else if (r_read_be32 (magicbytes) == 0xfeedface) { bin->big_endian = true; } else if (r_read_le32(magicbytes) == FAT_MAGIC) { bin->big_endian = false; } else if (r_read_be32(magicbytes) == FAT_MAGIC) { bin->big_endian = true; } else if (r_read_le32(magicbytes) == 0xfeedfacf) { bin->big_endian = false; } else if (r_read_be32(magicbytes) == 0xfeedfacf) { bin->big_endian = true; } else { return false; // object files are magic == 0, but body is different :? } len = r_buf_read_at (bin->b, 0, machohdrbytes, sizeof (machohdrbytes)); if (len != sizeof (machohdrbytes)) { bprintf ("Error: read (hdr)\n"); return false; } bin->hdr.magic = r_read_ble (&machohdrbytes[0], bin->big_endian, 32); bin->hdr.cputype = r_read_ble (&machohdrbytes[4], bin->big_endian, 32); bin->hdr.cpusubtype = r_read_ble (&machohdrbytes[8], bin->big_endian, 32); bin->hdr.filetype = r_read_ble (&machohdrbytes[12], bin->big_endian, 32); bin->hdr.ncmds = r_read_ble (&machohdrbytes[16], bin->big_endian, 32); bin->hdr.sizeofcmds = r_read_ble (&machohdrbytes[20], bin->big_endian, 32); bin->hdr.flags = r_read_ble (&machohdrbytes[24], bin->big_endian, 32); #if R_BIN_MACH064 bin->hdr.reserved = r_read_ble (&machohdrbytes[28], bin->big_endian, 32); #endif sdb_set (bin->kv, "mach0_header.format", "xxxxddx " "magic cputype cpusubtype filetype ncmds sizeofcmds flags", 0); sdb_num_set (bin->kv, "mach0_header.offset", 0, 0); // wat about fatmach0? sdb_set (bin->kv, "mach_filetype.cparse", "enum mach_filetype{MH_OBJECT=1," "MH_EXECUTE=2, MH_FVMLIB=3, MH_CORE=4, MH_PRELOAD=5, MH_DYLIB=6," "MH_DYLINKER=7, MH_BUNDLE=8, MH_DYLIB_STUB=9, MH_DSYM=10," "MH_KEXT_BUNDLE=11}" ,0); sdb_set (bin->kv, "mach_flags.cparse", "enum mach_flags{MH_NOUNDEFS=1," "MH_INCRLINK=2,MH_DYLDLINK=4,MH_BINDATLOAD=8,MH_PREBOUND=0x10," "MH_SPLIT_SEGS=0x20,MH_LAZY_INIT=0x40,MH_TWOLEVEL=0x80," "MH_FORCE_FLAT=0x100,MH_NOMULTIDEFS=0x200,MH_NOFIXPREBINDING=0x400," "MH_PREBINDABLE=0x800, MH_ALLMODSBOUND=0x1000," "MH_SUBSECTIONS_VIA_SYMBOLS=0x2000," "MH_CANONICAL=0x4000,MH_WEAK_DEFINES=0x8000," "MH_BINDS_TO_WEAK=0x10000,MH_ALLOW_STACK_EXECUTION=0x20000," "MH_ROOT_SAFE=0x40000,MH_SETUID_SAFE=0x80000," "MH_NO_REEXPORTED_DYLIBS=0x100000,MH_PIE=0x200000," "MH_DEAD_STRIPPABLE_DYLIB=0x400000," "MH_HAS_TLV_DESCRIPTORS=0x800000," "MH_NO_HEAP_EXECUTION=0x1000000 }",0); return true; } static int parse_segments(struct MACH0_(obj_t)* bin, ut64 off) { int i, j, k, sect, len; ut32 size_sects; ut8 segcom[sizeof (struct MACH0_(segment_command))] = {0}; ut8 sec[sizeof (struct MACH0_(section))] = {0}; if (!UT32_MUL (&size_sects, bin->nsegs, sizeof (struct MACH0_(segment_command)))) { return false; } if (!size_sects || size_sects > bin->size) { return false; } if (off > bin->size || off + sizeof (struct MACH0_(segment_command)) > bin->size) { return false; } if (!(bin->segs = realloc (bin->segs, bin->nsegs * sizeof(struct MACH0_(segment_command))))) { perror ("realloc (seg)"); return false; } j = bin->nsegs - 1; len = r_buf_read_at (bin->b, off, segcom, sizeof (struct MACH0_(segment_command))); if (len != sizeof (struct MACH0_(segment_command))) { bprintf ("Error: read (seg)\n"); return false; } i = 0; bin->segs[j].cmd = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].cmdsize = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); memcpy (&bin->segs[j].segname, &segcom[i], 16); i += 16; #if R_BIN_MACH064 bin->segs[j].vmaddr = r_read_ble64 (&segcom[i], bin->big_endian); i += sizeof (ut64); bin->segs[j].vmsize = r_read_ble64 (&segcom[i], bin->big_endian); i += sizeof (ut64); bin->segs[j].fileoff = r_read_ble64 (&segcom[i], bin->big_endian); i += sizeof (ut64); bin->segs[j].filesize = r_read_ble64 (&segcom[i], bin->big_endian); i += sizeof (ut64); #else bin->segs[j].vmaddr = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].vmsize = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].fileoff = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].filesize = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); #endif bin->segs[j].maxprot = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].initprot = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].nsects = r_read_ble32 (&segcom[i], bin->big_endian); i += sizeof (ut32); bin->segs[j].flags = r_read_ble32 (&segcom[i], bin->big_endian); sdb_num_set (bin->kv, sdb_fmt ("mach0_segment_%d.offset", j), off, 0); sdb_num_set (bin->kv, "mach0_segments.count", 0, 0); sdb_set (bin->kv, "mach0_segment.format", "xd[16]zxxxxoodx " "cmd cmdsize segname vmaddr vmsize " "fileoff filesize maxprot initprot nsects flags", 0); if (bin->segs[j].nsects > 0) { sect = bin->nsects; bin->nsects += bin->segs[j].nsects; if (bin->nsects > 128) { int new_nsects = bin->nsects & 0xf; bprintf ("WARNING: mach0 header contains too many sections (%d). Wrapping to %d\n", bin->nsects, new_nsects); bin->nsects = new_nsects; } if ((int)bin->nsects < 1) { bprintf ("Warning: Invalid number of sections\n"); bin->nsects = sect; return false; } if (!UT32_MUL (&size_sects, bin->nsects-sect, sizeof (struct MACH0_(section)))){ bin->nsects = sect; return false; } if (!size_sects || size_sects > bin->size){ bin->nsects = sect; return false; } if (bin->segs[j].cmdsize != sizeof (struct MACH0_(segment_command)) \ + (sizeof (struct MACH0_(section))*bin->segs[j].nsects)){ bin->nsects = sect; return false; } if (off + sizeof (struct MACH0_(segment_command)) > bin->size ||\ off + sizeof (struct MACH0_(segment_command)) + size_sects > bin->size){ bin->nsects = sect; return false; } if (!(bin->sects = realloc (bin->sects, bin->nsects * sizeof (struct MACH0_(section))))) { perror ("realloc (sects)"); bin->nsects = sect; return false; } for (k = sect, j = 0; k < bin->nsects; k++, j++) { ut64 offset = off + sizeof (struct MACH0_(segment_command)) + j * sizeof (struct MACH0_(section)); len = r_buf_read_at (bin->b, offset, sec, sizeof (struct MACH0_(section))); if (len != sizeof (struct MACH0_(section))) { bprintf ("Error: read (sects)\n"); bin->nsects = sect; return false; } i = 0; memcpy (&bin->sects[k].sectname, &sec[i], 16); i += 16; memcpy (&bin->sects[k].segname, &sec[i], 16); bin->sects[k].segname[15] = 0; i += 16; #if R_BIN_MACH064 bin->sects[k].addr = r_read_ble64 (&sec[i], bin->big_endian); i += sizeof (ut64); bin->sects[k].size = r_read_ble64 (&sec[i], bin->big_endian); i += sizeof (ut64); #else bin->sects[k].addr = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].size = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); #endif bin->sects[k].offset = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].align = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].reloff = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].nreloc = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].flags = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].reserved1 = r_read_ble32 (&sec[i], bin->big_endian); i += sizeof (ut32); bin->sects[k].reserved2 = r_read_ble32 (&sec[i], bin->big_endian); #if R_BIN_MACH064 i += sizeof (ut32); bin->sects[k].reserved3 = r_read_ble32 (&sec[i], bin->big_endian); #endif } } return true; } static int parse_symtab(struct MACH0_(obj_t)* bin, ut64 off) { struct symtab_command st; ut32 size_sym; int i; ut8 symt[sizeof (struct symtab_command)] = {0}; ut8 nlst[sizeof (struct MACH0_(nlist))] = {0}; if (off > (ut64)bin->size || off + sizeof (struct symtab_command) > (ut64)bin->size) { return false; } int len = r_buf_read_at (bin->b, off, symt, sizeof (struct symtab_command)); if (len != sizeof (struct symtab_command)) { bprintf ("Error: read (symtab)\n"); return false; } st.cmd = r_read_ble32 (&symt[0], bin->big_endian); st.cmdsize = r_read_ble32 (&symt[4], bin->big_endian); st.symoff = r_read_ble32 (&symt[8], bin->big_endian); st.nsyms = r_read_ble32 (&symt[12], bin->big_endian); st.stroff = r_read_ble32 (&symt[16], bin->big_endian); st.strsize = r_read_ble32 (&symt[20], bin->big_endian); bin->symtab = NULL; bin->nsymtab = 0; if (st.strsize > 0 && st.strsize < bin->size && st.nsyms > 0) { bin->nsymtab = st.nsyms; if (st.stroff > bin->size || st.stroff + st.strsize > bin->size) { return false; } if (!UT32_MUL (&size_sym, bin->nsymtab, sizeof (struct MACH0_(nlist)))) { bprintf("fail2\n"); return false; } if (!size_sym) { bprintf("fail3\n"); return false; } if (st.symoff > bin->size || st.symoff + size_sym > bin->size) { bprintf("fail4\n"); return false; } if (!(bin->symstr = calloc (1, st.strsize + 2))) { perror ("calloc (symstr)"); return false; } bin->symstrlen = st.strsize; len = r_buf_read_at (bin->b, st.stroff, (ut8*)bin->symstr, st.strsize); if (len != st.strsize) { bprintf ("Error: read (symstr)\n"); R_FREE (bin->symstr); return false; } if (!(bin->symtab = calloc (bin->nsymtab, sizeof (struct MACH0_(nlist))))) { perror ("calloc (symtab)"); return false; } for (i = 0; i < bin->nsymtab; i++) { len = r_buf_read_at (bin->b, st.symoff + (i * sizeof (struct MACH0_(nlist))), nlst, sizeof (struct MACH0_(nlist))); if (len != sizeof (struct MACH0_(nlist))) { bprintf ("Error: read (nlist)\n"); R_FREE (bin->symtab); return false; } //XXX not very safe what if is n_un.n_name instead? bin->symtab[i].n_strx = r_read_ble32 (&nlst[0], bin->big_endian); bin->symtab[i].n_type = r_read_ble8 (&nlst[4]); bin->symtab[i].n_sect = r_read_ble8 (&nlst[5]); bin->symtab[i].n_desc = r_read_ble16 (&nlst[6], bin->big_endian); #if R_BIN_MACH064 bin->symtab[i].n_value = r_read_ble64 (&nlst[8], bin->big_endian); #else bin->symtab[i].n_value = r_read_ble32 (&nlst[8], bin->big_endian); #endif } } return true; } static int parse_dysymtab(struct MACH0_(obj_t)* bin, ut64 off) { int len, i; ut32 size_tab; ut8 dysym[sizeof (struct dysymtab_command)] = {0}; ut8 dytoc[sizeof (struct dylib_table_of_contents)] = {0}; ut8 dymod[sizeof (struct MACH0_(dylib_module))] = {0}; ut8 idsyms[sizeof (ut32)] = {0}; if (off > bin->size || off + sizeof (struct dysymtab_command) > bin->size) { return false; } len = r_buf_read_at (bin->b, off, dysym, sizeof (struct dysymtab_command)); if (len != sizeof (struct dysymtab_command)) { bprintf ("Error: read (dysymtab)\n"); return false; } bin->dysymtab.cmd = r_read_ble32 (&dysym[0], bin->big_endian); bin->dysymtab.cmdsize = r_read_ble32 (&dysym[4], bin->big_endian); bin->dysymtab.ilocalsym = r_read_ble32 (&dysym[8], bin->big_endian); bin->dysymtab.nlocalsym = r_read_ble32 (&dysym[12], bin->big_endian); bin->dysymtab.iextdefsym = r_read_ble32 (&dysym[16], bin->big_endian); bin->dysymtab.nextdefsym = r_read_ble32 (&dysym[20], bin->big_endian); bin->dysymtab.iundefsym = r_read_ble32 (&dysym[24], bin->big_endian); bin->dysymtab.nundefsym = r_read_ble32 (&dysym[28], bin->big_endian); bin->dysymtab.tocoff = r_read_ble32 (&dysym[32], bin->big_endian); bin->dysymtab.ntoc = r_read_ble32 (&dysym[36], bin->big_endian); bin->dysymtab.modtaboff = r_read_ble32 (&dysym[40], bin->big_endian); bin->dysymtab.nmodtab = r_read_ble32 (&dysym[44], bin->big_endian); bin->dysymtab.extrefsymoff = r_read_ble32 (&dysym[48], bin->big_endian); bin->dysymtab.nextrefsyms = r_read_ble32 (&dysym[52], bin->big_endian); bin->dysymtab.indirectsymoff = r_read_ble32 (&dysym[56], bin->big_endian); bin->dysymtab.nindirectsyms = r_read_ble32 (&dysym[60], bin->big_endian); bin->dysymtab.extreloff = r_read_ble32 (&dysym[64], bin->big_endian); bin->dysymtab.nextrel = r_read_ble32 (&dysym[68], bin->big_endian); bin->dysymtab.locreloff = r_read_ble32 (&dysym[72], bin->big_endian); bin->dysymtab.nlocrel = r_read_ble32 (&dysym[76], bin->big_endian); bin->ntoc = bin->dysymtab.ntoc; if (bin->ntoc > 0) { if (!(bin->toc = calloc (bin->ntoc, sizeof (struct dylib_table_of_contents)))) { perror ("calloc (toc)"); return false; } if (!UT32_MUL (&size_tab, bin->ntoc, sizeof (struct dylib_table_of_contents))){ R_FREE (bin->toc); return false; } if (!size_tab){ R_FREE (bin->toc); return false; } if (bin->dysymtab.tocoff > bin->size || bin->dysymtab.tocoff + size_tab > bin->size){ R_FREE (bin->toc); return false; } for (i = 0; i < bin->ntoc; i++) { len = r_buf_read_at (bin->b, bin->dysymtab.tocoff + i * sizeof (struct dylib_table_of_contents), dytoc, sizeof (struct dylib_table_of_contents)); if (len != sizeof (struct dylib_table_of_contents)) { bprintf ("Error: read (toc)\n"); R_FREE (bin->toc); return false; } bin->toc[i].symbol_index = r_read_ble32 (&dytoc[0], bin->big_endian); bin->toc[i].module_index = r_read_ble32 (&dytoc[4], bin->big_endian); } } bin->nmodtab = bin->dysymtab.nmodtab; if (bin->nmodtab > 0) { if (!(bin->modtab = calloc (bin->nmodtab, sizeof (struct MACH0_(dylib_module))))) { perror ("calloc (modtab)"); return false; } if (!UT32_MUL (&size_tab, bin->nmodtab, sizeof (struct MACH0_(dylib_module)))){ R_FREE (bin->modtab); return false; } if (!size_tab){ R_FREE (bin->modtab); return false; } if (bin->dysymtab.modtaboff > bin->size || \ bin->dysymtab.modtaboff + size_tab > bin->size){ R_FREE (bin->modtab); return false; } for (i = 0; i < bin->nmodtab; i++) { len = r_buf_read_at (bin->b, bin->dysymtab.modtaboff + i * sizeof (struct MACH0_(dylib_module)), dymod, sizeof (struct MACH0_(dylib_module))); if (len == -1) { bprintf ("Error: read (modtab)\n"); R_FREE (bin->modtab); return false; } bin->modtab[i].module_name = r_read_ble32 (&dymod[0], bin->big_endian); bin->modtab[i].iextdefsym = r_read_ble32 (&dymod[4], bin->big_endian); bin->modtab[i].nextdefsym = r_read_ble32 (&dymod[8], bin->big_endian); bin->modtab[i].irefsym = r_read_ble32 (&dymod[12], bin->big_endian); bin->modtab[i].nrefsym = r_read_ble32 (&dymod[16], bin->big_endian); bin->modtab[i].ilocalsym = r_read_ble32 (&dymod[20], bin->big_endian); bin->modtab[i].nlocalsym = r_read_ble32 (&dymod[24], bin->big_endian); bin->modtab[i].iextrel = r_read_ble32 (&dymod[28], bin->big_endian); bin->modtab[i].nextrel = r_read_ble32 (&dymod[32], bin->big_endian); bin->modtab[i].iinit_iterm = r_read_ble32 (&dymod[36], bin->big_endian); bin->modtab[i].ninit_nterm = r_read_ble32 (&dymod[40], bin->big_endian); #if R_BIN_MACH064 bin->modtab[i].objc_module_info_size = r_read_ble32 (&dymod[44], bin->big_endian); bin->modtab[i].objc_module_info_addr = r_read_ble64 (&dymod[48], bin->big_endian); #else bin->modtab[i].objc_module_info_addr = r_read_ble32 (&dymod[44], bin->big_endian); bin->modtab[i].objc_module_info_size = r_read_ble32 (&dymod[48], bin->big_endian); #endif } } bin->nindirectsyms = bin->dysymtab.nindirectsyms; if (bin->nindirectsyms > 0) { if (!(bin->indirectsyms = calloc (bin->nindirectsyms, sizeof (ut32)))) { perror ("calloc (indirectsyms)"); return false; } if (!UT32_MUL (&size_tab, bin->nindirectsyms, sizeof (ut32))){ R_FREE (bin->indirectsyms); return false; } if (!size_tab){ R_FREE (bin->indirectsyms); return false; } if (bin->dysymtab.indirectsymoff > bin->size || \ bin->dysymtab.indirectsymoff + size_tab > bin->size){ R_FREE (bin->indirectsyms); return false; } for (i = 0; i < bin->nindirectsyms; i++) { len = r_buf_read_at (bin->b, bin->dysymtab.indirectsymoff + i * sizeof (ut32), idsyms, 4); if (len == -1) { bprintf ("Error: read (indirect syms)\n"); R_FREE (bin->indirectsyms); return false; } bin->indirectsyms[i] = r_read_ble32 (&idsyms[0], bin->big_endian); } } /* TODO extrefsyms, extrel, locrel */ return true; } static bool parse_signature(struct MACH0_(obj_t) *bin, ut64 off) { int i,len; ut32 data; bin->signature = NULL; struct linkedit_data_command link = {0}; ut8 lit[sizeof (struct linkedit_data_command)] = {0}; struct blob_index_t idx = {0}; struct super_blob_t super = {{0}}; if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) { return false; } len = r_buf_read_at (bin->b, off, lit, sizeof (struct linkedit_data_command)); if (len != sizeof (struct linkedit_data_command)) { bprintf ("Failed to get data while parsing LC_CODE_SIGNATURE command\n"); return false; } link.cmd = r_read_ble32 (&lit[0], bin->big_endian); link.cmdsize = r_read_ble32 (&lit[4], bin->big_endian); link.dataoff = r_read_ble32 (&lit[8], bin->big_endian); link.datasize = r_read_ble32 (&lit[12], bin->big_endian); data = link.dataoff; if (data > bin->size || data + sizeof (struct super_blob_t) > bin->size) { bin->signature = (ut8 *)strdup ("Malformed entitlement"); return true; } super.blob.magic = r_read_ble32 (bin->b->buf + data, little_); super.blob.length = r_read_ble32 (bin->b->buf + data + 4, little_); super.count = r_read_ble32 (bin->b->buf + data + 8, little_); for (i = 0; i < super.count; ++i) { if ((ut8 *)(bin->b->buf + data + i) > (ut8 *)(bin->b->buf + bin->size)) { bin->signature = (ut8 *)strdup ("Malformed entitlement"); break; } struct blob_index_t bi; if (r_buf_read_at (bin->b, data + 12 + (i * sizeof (struct blob_index_t)), (ut8*)&bi, sizeof (struct blob_index_t)) < sizeof (struct blob_index_t)) { break; } idx.type = r_read_ble32 (&bi.type, little_); idx.offset = r_read_ble32 (&bi.offset, little_); if (idx.type == CSSLOT_ENTITLEMENTS) { ut64 off = data + idx.offset; if (off > bin->size || off + sizeof (struct blob_t) > bin->size) { bin->signature = (ut8 *)strdup ("Malformed entitlement"); break; } struct blob_t entitlements = {0}; entitlements.magic = r_read_ble32 (bin->b->buf + off, little_); entitlements.length = r_read_ble32 (bin->b->buf + off + 4, little_); len = entitlements.length - sizeof (struct blob_t); if (len <= bin->size && len > 1) { bin->signature = calloc (1, len + 1); if (bin->signature) { ut8 *src = bin->b->buf + off + sizeof (struct blob_t); if (off + sizeof (struct blob_t) + len < bin->b->length) { memcpy (bin->signature, src, len); bin->signature[len] = '\0'; return true; } bin->signature = (ut8 *)strdup ("Malformed entitlement"); return true; } } else { bin->signature = (ut8 *)strdup ("Malformed entitlement"); } } } if (!bin->signature) { bin->signature = (ut8 *)strdup ("No entitlement found"); } return true; } static int parse_thread(struct MACH0_(obj_t)* bin, struct load_command *lc, ut64 off, bool is_first_thread) { ut64 ptr_thread, pc = UT64_MAX, pc_offset = UT64_MAX; ut32 flavor, count; ut8 *arw_ptr = NULL; int arw_sz, len = 0; ut8 thc[sizeof (struct thread_command)] = {0}; ut8 tmp[4]; if (off > bin->size || off + sizeof (struct thread_command) > bin->size) return false; len = r_buf_read_at (bin->b, off, thc, 8); if (len < 1) { goto wrong_read; } bin->thread.cmd = r_read_ble32 (&thc[0], bin->big_endian); bin->thread.cmdsize = r_read_ble32 (&thc[4], bin->big_endian); if (r_buf_read_at (bin->b, off + sizeof (struct thread_command), tmp, 4) < 4) { goto wrong_read; } flavor = r_read_ble32 (tmp, bin->big_endian); if (len == -1) goto wrong_read; if (off + sizeof (struct thread_command) + sizeof (flavor) > bin->size || \ off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (ut32) > bin->size) return false; // TODO: use count for checks if (r_buf_read_at (bin->b, off + sizeof (struct thread_command) + sizeof (flavor), tmp, 4) < 4) { goto wrong_read; } count = r_read_ble32 (tmp, bin->big_endian); ptr_thread = off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (count); if (ptr_thread > bin->size) return false; switch (bin->hdr.cputype) { case CPU_TYPE_I386: case CPU_TYPE_X86_64: switch (flavor) { case X86_THREAD_STATE32: if (ptr_thread + sizeof (struct x86_thread_state32) > bin->size) return false; if ((len = r_buf_fread_at (bin->b, ptr_thread, (ut8*)&bin->thread_state.x86_32, "16i", 1)) == -1) { bprintf ("Error: read (thread state x86_32)\n"); return false; } pc = bin->thread_state.x86_32.eip; pc_offset = ptr_thread + r_offsetof(struct x86_thread_state32, eip); arw_ptr = (ut8 *)&bin->thread_state.x86_32; arw_sz = sizeof (struct x86_thread_state32); break; case X86_THREAD_STATE64: if (ptr_thread + sizeof (struct x86_thread_state64) > bin->size) return false; if ((len = r_buf_fread_at (bin->b, ptr_thread, (ut8*)&bin->thread_state.x86_64, "32l", 1)) == -1) { bprintf ("Error: read (thread state x86_64)\n"); return false; } pc = bin->thread_state.x86_64.rip; pc_offset = ptr_thread + r_offsetof(struct x86_thread_state64, rip); arw_ptr = (ut8 *)&bin->thread_state.x86_64; arw_sz = sizeof (struct x86_thread_state64); break; //default: bprintf ("Unknown type\n"); } break; case CPU_TYPE_POWERPC: case CPU_TYPE_POWERPC64: if (flavor == X86_THREAD_STATE32) { if (ptr_thread + sizeof (struct ppc_thread_state32) > bin->size) return false; if ((len = r_buf_fread_at (bin->b, ptr_thread, (ut8*)&bin->thread_state.ppc_32, bin->big_endian?"40I":"40i", 1)) == -1) { bprintf ("Error: read (thread state ppc_32)\n"); return false; } pc = bin->thread_state.ppc_32.srr0; pc_offset = ptr_thread + r_offsetof(struct ppc_thread_state32, srr0); arw_ptr = (ut8 *)&bin->thread_state.ppc_32; arw_sz = sizeof (struct ppc_thread_state32); } else if (flavor == X86_THREAD_STATE64) { if (ptr_thread + sizeof (struct ppc_thread_state64) > bin->size) return false; if ((len = r_buf_fread_at (bin->b, ptr_thread, (ut8*)&bin->thread_state.ppc_64, bin->big_endian?"34LI3LI":"34li3li", 1)) == -1) { bprintf ("Error: read (thread state ppc_64)\n"); return false; } pc = bin->thread_state.ppc_64.srr0; pc_offset = ptr_thread + r_offsetof(struct ppc_thread_state64, srr0); arw_ptr = (ut8 *)&bin->thread_state.ppc_64; arw_sz = sizeof (struct ppc_thread_state64); } break; case CPU_TYPE_ARM: if (ptr_thread + sizeof (struct arm_thread_state32) > bin->size) return false; if ((len = r_buf_fread_at (bin->b, ptr_thread, (ut8*)&bin->thread_state.arm_32, bin->big_endian?"17I":"17i", 1)) == -1) { bprintf ("Error: read (thread state arm)\n"); return false; } pc = bin->thread_state.arm_32.r15; pc_offset = ptr_thread + r_offsetof (struct arm_thread_state32, r15); arw_ptr = (ut8 *)&bin->thread_state.arm_32; arw_sz = sizeof (struct arm_thread_state32); break; case CPU_TYPE_ARM64: if (ptr_thread + sizeof (struct arm_thread_state64) > bin->size) { return false; } if ((len = r_buf_fread_at(bin->b, ptr_thread, (ut8*)&bin->thread_state.arm_64, bin->big_endian?"34LI1I":"34Li1i", 1)) == -1) { bprintf ("Error: read (thread state arm)\n"); return false; } pc = r_read_be64 (&bin->thread_state.arm_64.pc); pc_offset = ptr_thread + r_offsetof (struct arm_thread_state64, pc); arw_ptr = (ut8*)&bin->thread_state.arm_64; arw_sz = sizeof (struct arm_thread_state64); break; default: bprintf ("Error: read (unknown thread state structure)\n"); return false; } // TODO: this shouldnt be an bprintf... if (arw_ptr && arw_sz > 0) { int i; ut8 *p = arw_ptr; bprintf ("arw "); for (i = 0; i < arw_sz; i++) { bprintf ("%02x", 0xff & p[i]); } bprintf ("\n"); } if (is_first_thread) { bin->main_cmd = *lc; if (pc != UT64_MAX) { bin->entry = pc; } if (pc_offset != UT64_MAX) { sdb_num_set (bin->kv, "mach0.entry.offset", pc_offset, 0); } } return true; wrong_read: bprintf ("Error: read (thread)\n"); return false; } static int parse_function_starts (struct MACH0_(obj_t)* bin, ut64 off) { struct linkedit_data_command fc; ut8 sfc[sizeof (struct linkedit_data_command)] = {0}; ut8 *buf; int len; if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) { bprintf ("Likely overflow while parsing" " LC_FUNCTION_STARTS command\n"); } bin->func_start = NULL; len = r_buf_read_at (bin->b, off, sfc, sizeof (struct linkedit_data_command)); if (len < 1) { bprintf ("Failed to get data while parsing" " LC_FUNCTION_STARTS command\n"); } fc.cmd = r_read_ble32 (&sfc[0], bin->big_endian); fc.cmdsize = r_read_ble32 (&sfc[4], bin->big_endian); fc.dataoff = r_read_ble32 (&sfc[8], bin->big_endian); fc.datasize = r_read_ble32 (&sfc[12], bin->big_endian); buf = calloc (1, fc.datasize + 1); if (!buf) { bprintf ("Failed to allocate buffer\n"); return false; } bin->func_size = fc.datasize; if (fc.dataoff > bin->size || fc.dataoff + fc.datasize > bin->size) { free (buf); bprintf ("Likely overflow while parsing " "LC_FUNCTION_STARTS command\n"); return false; } len = r_buf_read_at (bin->b, fc.dataoff, buf, fc.datasize); if (len != fc.datasize) { free (buf); bprintf ("Failed to get data while parsing" " LC_FUNCTION_STARTS\n"); return false; } buf[fc.datasize] = 0; // null-terminated buffer bin->func_start = buf; return true; } static int parse_dylib(struct MACH0_(obj_t)* bin, ut64 off) { struct dylib_command dl; int lib, len; ut8 sdl[sizeof (struct dylib_command)] = {0}; if (off > bin->size || off + sizeof (struct dylib_command) > bin->size) return false; lib = bin->nlibs - 1; if (!(bin->libs = realloc (bin->libs, bin->nlibs * R_BIN_MACH0_STRING_LENGTH))) { perror ("realloc (libs)"); return false; } len = r_buf_read_at (bin->b, off, sdl, sizeof (struct dylib_command)); if (len < 1) { bprintf ("Error: read (dylib)\n"); return false; } dl.cmd = r_read_ble32 (&sdl[0], bin->big_endian); dl.cmdsize = r_read_ble32 (&sdl[4], bin->big_endian); dl.dylib.name = r_read_ble32 (&sdl[8], bin->big_endian); dl.dylib.timestamp = r_read_ble32 (&sdl[12], bin->big_endian); dl.dylib.current_version = r_read_ble32 (&sdl[16], bin->big_endian); dl.dylib.compatibility_version = r_read_ble32 (&sdl[20], bin->big_endian); if (off + dl.dylib.name > bin->size ||\ off + dl.dylib.name + R_BIN_MACH0_STRING_LENGTH > bin->size) return false; len = r_buf_read_at (bin->b, off+dl.dylib.name, (ut8*)bin->libs[lib], R_BIN_MACH0_STRING_LENGTH); if (len < 1) { bprintf ("Error: read (dylib str)"); return false; } return true; } static const char *cmd_to_string(ut32 cmd) { switch (cmd) { case LC_DATA_IN_CODE: return "LC_DATA_IN_CODE"; case LC_CODE_SIGNATURE: return "LC_CODE_SIGNATURE"; case LC_RPATH: return "LC_RPATH"; case LC_SEGMENT: return "LC_SEGMENT"; case LC_SEGMENT_64: return "LC_SEGMENT_64"; case LC_SYMTAB: return "LC_SYMTAB"; case LC_SYMSEG: return "LC_SYMSEG"; case LC_ID_DYLIB: return "LC_ID_DYLIB"; case LC_DYSYMTAB: return "LC_DYSYMTAB"; case LC_FUNCTION_STARTS: return "LC_FUNCTION_STARTS"; case LC_DYLIB_CODE_SIGN_DRS: return "LC_DYLIB_CODE_SIGN_DRS"; case LC_VERSION_MIN_MACOSX: return "LC_VERSION_MIN_MACOSX"; case LC_VERSION_MIN_IPHONEOS: return "LC_VERSION_MIN_IPHONEOS"; case LC_VERSION_MIN_TVOS: return "LC_VERSION_MIN_TVOS"; case LC_VERSION_MIN_WATCHOS: return "LC_VERSION_MIN_WATCHOS"; case LC_DYLD_INFO: return "LC_DYLD_INFO"; case LC_SOURCE_VERSION: return "LC_SOURCE_VERSION"; case LC_MAIN: return "LC_MAIN"; case LC_UUID: return "LC_UUID"; case LC_ENCRYPTION_INFO_64: return "LC_ENCRYPTION_INFO_64"; case LC_ENCRYPTION_INFO: return "LC_ENCRYPTION_INFO"; case LC_LOAD_DYLINKER: return "LC_LOAD_DYLINKER"; case LC_LOAD_DYLIB: return "LC_LOAD_DYLIB"; case LC_THREAD: return "LC_THREAD"; case LC_UNIXTHREAD: return "LC_UNIXTHREAD"; case LC_IDENT: return "LC_IDENT"; case LC_DYLD_INFO_ONLY: return "LC_DYLD_INFO_ONLY"; } return ""; } static int init_items(struct MACH0_(obj_t)* bin) { struct load_command lc = {0, 0}; ut8 loadc[sizeof (struct load_command)] = {0}; bool is_first_thread = true; ut64 off = 0LL; int i, len; bin->uuidn = 0; bin->os = 0; bin->has_crypto = 0; if (bin->hdr.sizeofcmds > bin->size) { bprintf ("Warning: chopping hdr.sizeofcmds\n"); bin->hdr.sizeofcmds = bin->size - 128; //return false; } //bprintf ("Commands: %d\n", bin->hdr.ncmds); for (i = 0, off = sizeof (struct MACH0_(mach_header)); \ i < bin->hdr.ncmds; i++, off += lc.cmdsize) { if (off > bin->size || off + sizeof (struct load_command) > bin->size){ bprintf ("mach0: out of bounds command\n"); return false; } len = r_buf_read_at (bin->b, off, loadc, sizeof (struct load_command)); if (len < 1) { bprintf ("Error: read (lc) at 0x%08"PFMT64x"\n", off); return false; } lc.cmd = r_read_ble32 (&loadc[0], bin->big_endian); lc.cmdsize = r_read_ble32 (&loadc[4], bin->big_endian); if (lc.cmdsize < 1 || off + lc.cmdsize > bin->size) { bprintf ("Warning: mach0_header %d = cmdsize<1. (0x%llx vs 0x%llx)\n", i, (ut64)(off + lc.cmdsize), (ut64)(bin->size)); break; } // TODO: a different format for each cmd sdb_num_set (bin->kv, sdb_fmt ("mach0_cmd_%d.offset", i), off, 0); sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.format", i), "xd cmd size", 0); //bprintf ("%d\n", lc.cmd); switch (lc.cmd) { case LC_DATA_IN_CODE: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "data_in_code", 0); // TODO table of non-instructions in __text break; case LC_RPATH: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "rpath", 0); //bprintf ("--->\n"); break; case LC_SEGMENT_64: case LC_SEGMENT: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "segment", 0); bin->nsegs++; if (!parse_segments (bin, off)) { bprintf ("error parsing segment\n"); bin->nsegs--; return false; } break; case LC_SYMTAB: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "symtab", 0); if (!parse_symtab (bin, off)) { bprintf ("error parsing symtab\n"); return false; } break; case LC_DYSYMTAB: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dysymtab", 0); if (!parse_dysymtab(bin, off)) { bprintf ("error parsing dysymtab\n"); return false; } break; case LC_DYLIB_CODE_SIGN_DRS: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylib_code_sign_drs", 0); //bprintf ("[mach0] code is signed\n"); break; case LC_VERSION_MIN_MACOSX: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_macosx", 0); bin->os = 1; // set OS = osx //bprintf ("[mach0] Requires OSX >= x\n"); break; case LC_VERSION_MIN_IPHONEOS: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_iphoneos", 0); bin->os = 2; // set OS = ios //bprintf ("[mach0] Requires iOS >= x\n"); break; case LC_VERSION_MIN_TVOS: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_tvos", 0); bin->os = 4; break; case LC_VERSION_MIN_WATCHOS: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version_min_watchos", 0); bin->os = 3; break; case LC_UUID: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "uuid", 0); { struct uuid_command uc = {0}; if (off + sizeof (struct uuid_command) > bin->size) { bprintf ("UUID out of obunds\n"); return false; } if (r_buf_fread_at (bin->b, off, (ut8*)&uc, "24c", 1) != -1) { char key[128]; char val[128]; snprintf (key, sizeof (key)-1, "uuid.%d", bin->uuidn++); r_hex_bin2str ((ut8*)&uc.uuid, 16, val); sdb_set (bin->kv, key, val, 0); //for (i=0;i<16; i++) bprintf ("%02x%c", uc.uuid[i], (i==15)?'\n':'-'); } } break; case LC_ENCRYPTION_INFO_64: /* TODO: the struct is probably different here */ case LC_ENCRYPTION_INFO: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "encryption_info", 0); { struct MACH0_(encryption_info_command) eic = {0}; ut8 seic[sizeof (struct MACH0_(encryption_info_command))] = {0}; if (off + sizeof (struct MACH0_(encryption_info_command)) > bin->size) { bprintf ("encryption info out of bounds\n"); return false; } if (r_buf_read_at (bin->b, off, seic, sizeof (struct MACH0_(encryption_info_command))) != -1) { eic.cmd = r_read_ble32 (&seic[0], bin->big_endian); eic.cmdsize = r_read_ble32 (&seic[4], bin->big_endian); eic.cryptoff = r_read_ble32 (&seic[8], bin->big_endian); eic.cryptsize = r_read_ble32 (&seic[12], bin->big_endian); eic.cryptid = r_read_ble32 (&seic[16], bin->big_endian); bin->has_crypto = eic.cryptid; sdb_set (bin->kv, "crypto", "true", 0); sdb_num_set (bin->kv, "cryptid", eic.cryptid, 0); sdb_num_set (bin->kv, "cryptoff", eic.cryptoff, 0); sdb_num_set (bin->kv, "cryptsize", eic.cryptsize, 0); sdb_num_set (bin->kv, "cryptheader", off, 0); } } break; case LC_LOAD_DYLINKER: { sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylinker", 0); free (bin->intrp); bin->intrp = NULL; //bprintf ("[mach0] load dynamic linker\n"); struct dylinker_command dy = {0}; ut8 sdy[sizeof (struct dylinker_command)] = {0}; if (off + sizeof (struct dylinker_command) > bin->size){ bprintf ("Warning: Cannot parse dylinker command\n"); return false; } if (r_buf_read_at (bin->b, off, sdy, sizeof (struct dylinker_command)) == -1) { bprintf ("Warning: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off); } else { dy.cmd = r_read_ble32 (&sdy[0], bin->big_endian); dy.cmdsize = r_read_ble32 (&sdy[4], bin->big_endian); dy.name = r_read_ble32 (&sdy[8], bin->big_endian); int len = dy.cmdsize; char *buf = malloc (len+1); if (buf) { // wtf @ off + 0xc ? r_buf_read_at (bin->b, off + 0xc, (ut8*)buf, len); buf[len] = 0; free (bin->intrp); bin->intrp = buf; } } } break; case LC_MAIN: { struct { ut64 eo; ut64 ss; } ep = {0}; ut8 sep[2 * sizeof (ut64)] = {0}; sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "main", 0); if (!is_first_thread) { bprintf("Error: LC_MAIN with other threads\n"); return false; } if (off + 8 > bin->size || off + sizeof (ep) > bin->size) { bprintf ("invalid command size for main\n"); return false; } r_buf_read_at (bin->b, off + 8, sep, 2 * sizeof (ut64)); ep.eo = r_read_ble64 (&sep[0], bin->big_endian); ep.ss = r_read_ble64 (&sep[8], bin->big_endian); bin->entry = ep.eo; bin->main_cmd = lc; sdb_num_set (bin->kv, "mach0.entry.offset", off + 8, 0); sdb_num_set (bin->kv, "stacksize", ep.ss, 0); is_first_thread = false; } break; case LC_UNIXTHREAD: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "unixthread", 0); if (!is_first_thread) { bprintf("Error: LC_UNIXTHREAD with other threads\n"); return false; } case LC_THREAD: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "thread", 0); if (!parse_thread (bin, &lc, off, is_first_thread)) { bprintf ("Cannot parse thread\n"); return false; } is_first_thread = false; break; case LC_LOAD_DYLIB: case LC_LOAD_WEAK_DYLIB: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "load_dylib", 0); bin->nlibs++; if (!parse_dylib (bin, off)){ bprintf ("Cannot parse dylib\n"); bin->nlibs--; return false; } break; case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: { ut8 dyldi[sizeof (struct dyld_info_command)] = {0}; sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dyld_info", 0); bin->dyld_info = calloc (1, sizeof (struct dyld_info_command)); if (bin->dyld_info) { if (off + sizeof (struct dyld_info_command) > bin->size){ bprintf ("Cannot parse dyldinfo\n"); R_FREE (bin->dyld_info); return false; } if (r_buf_read_at (bin->b, off, dyldi, sizeof (struct dyld_info_command)) == -1) { free (bin->dyld_info); bin->dyld_info = NULL; bprintf ("Error: read (LC_DYLD_INFO) at 0x%08"PFMT64x"\n", off); } else { bin->dyld_info->cmd = r_read_ble32 (&dyldi[0], bin->big_endian); bin->dyld_info->cmdsize = r_read_ble32 (&dyldi[4], bin->big_endian); bin->dyld_info->rebase_off = r_read_ble32 (&dyldi[8], bin->big_endian); bin->dyld_info->rebase_size = r_read_ble32 (&dyldi[12], bin->big_endian); bin->dyld_info->bind_off = r_read_ble32 (&dyldi[16], bin->big_endian); bin->dyld_info->bind_size = r_read_ble32 (&dyldi[20], bin->big_endian); bin->dyld_info->weak_bind_off = r_read_ble32 (&dyldi[24], bin->big_endian); bin->dyld_info->weak_bind_size = r_read_ble32 (&dyldi[28], bin->big_endian); bin->dyld_info->lazy_bind_off = r_read_ble32 (&dyldi[32], bin->big_endian); bin->dyld_info->lazy_bind_size = r_read_ble32 (&dyldi[36], bin->big_endian); bin->dyld_info->export_off = r_read_ble32 (&dyldi[40], bin->big_endian); bin->dyld_info->export_size = r_read_ble32 (&dyldi[44], bin->big_endian); } } } break; case LC_CODE_SIGNATURE: parse_signature (bin, off); sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "signature", 0); /* ut32 dataoff // ut32 datasize */ break; case LC_SOURCE_VERSION: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "version", 0); /* uint64_t version; */ /* A.B.C.D.E packed as a24.b10.c10.d10.e10 */ //bprintf ("mach0: TODO: Show source version\n"); break; case LC_SEGMENT_SPLIT_INFO: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "split_info", 0); /* TODO */ break; case LC_FUNCTION_STARTS: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "function_starts", 0); if (!parse_function_starts (bin, off)) { bprintf ("Cannot parse LC_FUNCTION_STARTS\n"); } break; case LC_REEXPORT_DYLIB: sdb_set (bin->kv, sdb_fmt ("mach0_cmd_%d.cmd", i), "dylib", 0); /* TODO */ break; default: //bprintf ("mach0: Unknown header command %x\n", lc.cmd); break; } } return true; } static int init(struct MACH0_(obj_t)* bin) { union { ut16 word; ut8 byte[2]; } endian = { 1 }; little_ = endian.byte[0]; if (!init_hdr (bin)) { bprintf ("Warning: File is not MACH0\n"); return false; } if (!init_items (bin)) { bprintf ("Warning: Cannot initialize items\n"); } bin->baddr = MACH0_(get_baddr)(bin); return true; } void* MACH0_(mach0_free)(struct MACH0_(obj_t)* bin) { if (!bin) { return NULL; } free (bin->segs); free (bin->sects); free (bin->symtab); free (bin->symstr); free (bin->indirectsyms); free (bin->imports_by_ord); free (bin->dyld_info); free (bin->toc); free (bin->modtab); free (bin->libs); free (bin->func_start); free (bin->signature); r_buf_free (bin->b); free (bin); return NULL; } struct MACH0_(obj_t)* MACH0_(mach0_new)(const char* file, bool verbose) { ut8 *buf; struct MACH0_(obj_t) *bin; if (!(bin = malloc (sizeof (struct MACH0_(obj_t))))) { return NULL; } memset (bin, 0, sizeof (struct MACH0_(obj_t))); bin->verbose = verbose; bin->file = file; if (!(buf = (ut8*)r_file_slurp (file, &bin->size))) { return MACH0_(mach0_free)(bin); } bin->b = r_buf_new (); if (!r_buf_set_bytes (bin->b, buf, bin->size)) { free (buf); return MACH0_(mach0_free)(bin); } free (buf); bin->dyld_info = NULL; if (!init (bin)) { return MACH0_(mach0_free)(bin); } bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; return bin; } struct MACH0_(obj_t)* MACH0_(new_buf)(RBuffer *buf, bool verbose) { if (!buf) { return NULL; } RBuffer * buf_copy = r_buf_new_with_buf (buf); if (!buf_copy) { return NULL; } return MACH0_(new_buf_steal) (buf_copy, verbose); } struct MACH0_(obj_t)* MACH0_(new_buf_steal)(RBuffer *buf, bool verbose) { struct MACH0_(obj_t) *bin = R_NEW0 (struct MACH0_(obj_t)); if (!bin) { return NULL; } bin->kv = sdb_new (NULL, "bin.mach0", 0); bin->size = r_buf_size (buf); bin->verbose = verbose; bin->b = buf; if (!init (bin)) { return MACH0_(mach0_free)(bin); } return bin; } // prot: r = 1, w = 2, x = 4 // perm: r = 4, w = 2, x = 1 static int prot2perm (int x) { int r = 0; if (x&1) r |= 4; if (x&2) r |= 2; if (x&4) r |= 1; return r; } struct section_t* MACH0_(get_sections)(struct MACH0_(obj_t)* bin) { struct section_t *sections; char segname[32], sectname[32]; int i, j, to; if (!bin) { return NULL; } /* for core files */ if (bin->nsects < 1 && bin->nsegs > 0) { struct MACH0_(segment_command) *seg; if (!(sections = calloc ((bin->nsegs + 1), sizeof (struct section_t)))) { return NULL; } for (i = 0; i < bin->nsegs; i++) { seg = &bin->segs[i]; sections[i].addr = seg->vmaddr; sections[i].offset = seg->fileoff; sections[i].size = seg->vmsize; sections[i].vsize = seg->vmsize; sections[i].align = 4096; sections[i].flags = seg->flags; r_str_ncpy (sectname, seg->segname, sizeof (sectname)); r_str_filter (sectname, -1); // hack to support multiple sections with same name sections[i].srwx = prot2perm (seg->initprot); sections[i].last = 0; } sections[i].last = 1; return sections; } if (!bin->sects) { return NULL; } to = R_MIN (bin->nsects, 128); // limit number of sections here to avoid fuzzed bins if (to < 1) { return NULL; } if (!(sections = calloc (bin->nsects + 1, sizeof (struct section_t)))) { return NULL; } for (i = 0; i < to; i++) { sections[i].offset = (ut64)bin->sects[i].offset; sections[i].addr = (ut64)bin->sects[i].addr; sections[i].size = (bin->sects[i].flags == S_ZEROFILL) ? 0 : (ut64)bin->sects[i].size; sections[i].vsize = (ut64)bin->sects[i].size; sections[i].align = bin->sects[i].align; sections[i].flags = bin->sects[i].flags; r_str_ncpy (sectname, bin->sects[i].sectname, sizeof (sectname)); r_str_filter (sectname, -1); // hack to support multiple sections with same name // snprintf (segname, sizeof (segname), "%d", i); // wtf snprintf (segname, sizeof (segname), "%d.%s", i, bin->sects[i].segname); for (j = 0; j < bin->nsegs; j++) { if (sections[i].addr >= bin->segs[j].vmaddr && sections[i].addr < (bin->segs[j].vmaddr + bin->segs[j].vmsize)) { sections[i].srwx = prot2perm (bin->segs[j].initprot); break; } } // XXX: if two sections have the same name are merged :O // XXX: append section index in flag name maybe? // XXX: do not load out of bound sections? // XXX: load segments instead of sections? what about PAGEZERO and ... snprintf (sections[i].name, sizeof (sections[i].name), "%s.%s", segname, sectname); sections[i].last = 0; } sections[i].last = 1; return sections; } static int parse_import_stub(struct MACH0_(obj_t)* bin, struct symbol_t *symbol, int idx) { int i, j, nsyms, stridx; const char *symstr; if (idx < 0) { return 0; } symbol->offset = 0LL; symbol->addr = 0LL; symbol->name[0] = '\0'; if (!bin || !bin->sects) { return false; } for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == S_SYMBOL_STUBS && bin->sects[i].reserved2 > 0) { nsyms = (int)(bin->sects[i].size / bin->sects[i].reserved2); if (nsyms > bin->size) { bprintf ("mach0: Invalid symbol table size\n"); } for (j = 0; j < nsyms; j++) { if (bin->sects) { if (bin->sects[i].reserved1 + j >= bin->nindirectsyms) { continue; } } if (bin->indirectsyms) { if (idx != bin->indirectsyms[bin->sects[i].reserved1 + j]) { continue; } } if (idx > bin->nsymtab) { continue; } symbol->type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL; symbol->offset = bin->sects[i].offset + j * bin->sects[i].reserved2; symbol->addr = bin->sects[i].addr + j * bin->sects[i].reserved2; symbol->size = 0; stridx = bin->symtab[idx].n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char *)bin->symstr + stridx; } else { symstr = "???"; } // Remove the extra underscore that every import seems to have in Mach-O. if (*symstr == '_') { symstr++; } snprintf (symbol->name, R_BIN_MACH0_STRING_LENGTH, "imp.%s", symstr); return true; } } } return false; } #if 0 static ut64 get_text_base(struct MACH0_(obj_t)* bin) { ut64 ret = 0LL; struct section_t *sections; if ((sections = MACH0_(get_sections) (bin))) { int i; for (i = 0; !sections[i].last; i++) { if (strstr(sections[i].name, "text")) { ret = sections[i].offset; break; } } free (sections); } return ret; } #endif static int inSymtab(SdbHash *hash, struct symbol_t *symbols, const char *name, ut64 addr) { bool found; const char *key = sdb_fmt ("%s.%"PFMT64x, name, addr); (void)sdb_ht_find (hash, key, &found); if (found) { return true; } sdb_ht_insert (hash, key, "1"); return false; } struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) { const char *symstr; struct symbol_t *symbols; int from, to, i, j, s, stridx, symbols_size, symbols_count; SdbHash *hash; //ut64 text_base = get_text_base (bin); if (!bin || !bin->symtab || !bin->symstr) { return NULL; } /* parse symbol table */ /* parse dynamic symbol table */ symbols_count = (bin->dysymtab.nextdefsym + \ bin->dysymtab.nlocalsym + \ bin->dysymtab.nundefsym ); symbols_count += bin->nsymtab; //symbols_count = bin->nsymtab; symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t); if (symbols_size < 1) { return NULL; } if (!(symbols = calloc (1, symbols_size))) { return NULL; } hash = sdb_ht_new (); j = 0; // symbol_idx for (s = 0; s < 2; s++) { switch (s) { case 0: from = bin->dysymtab.iextdefsym; to = from + bin->dysymtab.nextdefsym; break; case 1: from = bin->dysymtab.ilocalsym; to = from + bin->dysymtab.nlocalsym; break; #if NOT_USED case 2: from = bin->dysymtab.iundefsym; to = from + bin->dysymtab.nundefsym; break; #endif } if (from == to) { continue; } #define OLD 1 #if OLD from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t)); to = R_MIN (to , symbols_size / sizeof (struct symbol_t)); to = R_MIN (to, bin->nsymtab); #else from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t)); to = symbols_count; //symbols_size/sizeof(struct symbol_t); #endif int maxsymbols = symbols_size / sizeof (struct symbol_t); if (to > 0x500000) { bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to); free (symbols); sdb_ht_free (hash); return NULL; } if (symbols_count >= maxsymbols) { symbols_count = maxsymbols - 1; } for (i = from; i < to && j < symbols_count; i++, j++) { symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value); symbols[j].addr = bin->symtab[i].n_value; symbols[j].size = 0; /* TODO: Is it anywhere? */ if (bin->symtab[i].n_type & N_EXT) { symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT; } else { symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL; } stridx = bin->symtab[i].n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char*)bin->symstr + stridx; } else { symstr = "???"; } { int i = 0; int len = 0; len = bin->symstrlen - stridx; if (len > 0) { for (i = 0; i < len; i++) { if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) { len = i; break; } } char *symstr_dup = NULL; if (len > 0) { symstr_dup = r_str_ndup (symstr, len); } if (!symstr_dup) { symbols[j].name[0] = 0; } else { r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH); r_str_filter (symbols[j].name, -1); symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0; } free (symstr_dup); } else { symbols[j].name[0] = 0; } symbols[j].last = 0; } if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) { symbols[j].name[0] = 0; j--; } } } to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym); for (i = bin->dysymtab.iundefsym; i < to; i++) { if (j > symbols_count) { bprintf ("mach0-get-symbols: error\n"); break; } if (parse_import_stub(bin, &symbols[j], i)) { symbols[j++].last = 0; } } #if 1 // symtab is wrongly parsed and produces dupped syms with incorrect vaddr */ for (i = 0; i < bin->nsymtab; i++) { struct MACH0_(nlist) *st = &bin->symtab[i]; #if 0 bprintf ("stridx %d -> section %d type %d value = %d\n", st->n_strx, st->n_sect, st->n_type, st->n_value); #endif stridx = st->n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char*)bin->symstr + stridx; } else { symstr = "???"; } // 0 is for imports // 1 is for symbols // 2 is for func.eh (exception handlers?) int section = st->n_sect; if (section == 1 && j < symbols_count) { // text ??st->n_type == 1) /* is symbol */ symbols[j].addr = st->n_value; // + text_base; symbols[j].offset = addr_to_offset (bin, symbols[j].addr); symbols[j].size = 0; /* find next symbol and crop */ if (st->n_type & N_EXT) { symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT; } else { symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL; } strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH); symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0; symbols[j].last = 0; if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) { symbols[j].name[0] = 0; } else { j++; } } } #endif sdb_ht_free (hash); symbols[j].last = 1; return symbols; } static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) { int i, j, sym, wordsize; ut32 stype; wordsize = MACH0_(get_bits)(bin) / 8; if (idx < 0 || idx >= bin->nsymtab) { return 0; } if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) { stype = S_LAZY_SYMBOL_POINTERS; } else { stype = S_NON_LAZY_SYMBOL_POINTERS; } reloc->offset = 0; reloc->addr = 0; reloc->addend = 0; #define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return false; } #undef CASE for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == stype) { for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) { int indidx = bin->sects[i].reserved1 + j; if (indidx < 0 || indidx >= bin->nindirectsyms) { break; } if (idx == bin->indirectsyms[indidx]) { sym = j; break; } } reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; return true; } } return false; } struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) { struct import_t *imports; int i, j, idx, stridx; const char *symstr; if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) { return NULL; } if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) { return NULL; } if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) { return NULL; } for (i = j = 0; i < bin->dysymtab.nundefsym; i++) { idx = bin->dysymtab.iundefsym + i; if (idx < 0 || idx >= bin->nsymtab) { bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n"); free (imports); return NULL; } stridx = bin->symtab[idx].n_strx; if (stridx >= 0 && stridx < bin->symstrlen) { symstr = (char *)bin->symstr + stridx; } else { symstr = ""; } if (!*symstr) { continue; } { int i = 0; int len = 0; char *symstr_dup = NULL; len = bin->symstrlen - stridx; imports[j].name[0] = 0; if (len > 0) { for (i = 0; i < len; i++) { if ((unsigned char)symstr[i] == 0xff || !symstr[i]) { len = i; break; } } symstr_dup = r_str_ndup (symstr, len); if (symstr_dup) { r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH); r_str_filter (imports[j].name, - 1); imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0; free (symstr_dup); } } } imports[j].ord = i; imports[j++].last = 0; } imports[j].last = 1; if (!bin->imports_by_ord_size) { if (j > 0) { bin->imports_by_ord_size = j; bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*)); } else { bin->imports_by_ord_size = 0; bin->imports_by_ord = NULL; } } return imports; } struct reloc_t* MACH0_(get_relocs)(struct MACH0_(obj_t)* bin) { struct reloc_t *relocs; int i = 0, len; ulebr ur = {NULL}; int wordsize = MACH0_(get_bits)(bin) / 8; if (bin->dyld_info) { ut8 *opcodes,*end, type = 0, rel_type = 0; int lib_ord, seg_idx = -1, sym_ord = -1; size_t j, count, skip, bind_size, lazy_size; st64 addend = 0; ut64 segmentAddress = 0LL; ut64 addr = 0LL; ut8 done = 0; #define CASE(T) case (T / 8): rel_type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return NULL; } #undef CASE bind_size = bin->dyld_info->bind_size; lazy_size = bin->dyld_info->lazy_bind_size; if (!bind_size || !lazy_size) { return NULL; } if ((bind_size + lazy_size)<1) { return NULL; } if (bin->dyld_info->bind_off > bin->size || bin->dyld_info->bind_off + bind_size > bin->size) { return NULL; } if (bin->dyld_info->lazy_bind_off > bin->size || \ bin->dyld_info->lazy_bind_off + lazy_size > bin->size) { return NULL; } if (bin->dyld_info->bind_off+bind_size+lazy_size > bin->size) { return NULL; } // NOTE(eddyb) it's a waste of memory, but we don't know the actual number of relocs. if (!(relocs = calloc (1, (1 + bind_size + lazy_size) * sizeof (struct reloc_t)))) { return NULL; } opcodes = calloc (1, bind_size + lazy_size + 1); if (!opcodes) { free (relocs); return NULL; } len = r_buf_read_at (bin->b, bin->dyld_info->bind_off, opcodes, bind_size); i = r_buf_read_at (bin->b, bin->dyld_info->lazy_bind_off, opcodes + bind_size, lazy_size); if (len < 1 || i < 1) { bprintf ("Error: read (dyld_info bind) at 0x%08"PFMT64x"\n", (ut64)(size_t)bin->dyld_info->bind_off); free (opcodes); relocs[i].last = 1; return relocs; } i = 0; // that +2 is a minimum required for uleb128, this may be wrong, // the correct fix would be to make ULEB() must use rutil's // implementation that already checks for buffer boundaries for (ur.p = opcodes, end = opcodes + bind_size + lazy_size ; (ur.p+2 < end) && !done; ) { ut8 imm = *ur.p & BIND_IMMEDIATE_MASK, op = *ur.p & BIND_OPCODE_MASK; ++ur.p; switch (op) { #define ULEB() read_uleb128 (&ur,end) #define SLEB() read_sleb128 (&ur,end) case BIND_OPCODE_DONE: done = 1; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: lib_ord = imm; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: lib_ord = ULEB(); break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: lib_ord = imm? (st8)(BIND_OPCODE_MASK | imm) : 0; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: { char *sym_name = (char*)ur.p; //ut8 sym_flags = imm; while (*ur.p++ && ur.p<end) { /* empty loop */ } sym_ord = -1; if (bin->symtab && bin->dysymtab.nundefsym < 0xffff) for (j = 0; j < bin->dysymtab.nundefsym; j++) { int stridx = 0; int iundefsym = bin->dysymtab.iundefsym; if (iundefsym>=0 && iundefsym < bin->nsymtab) { int sidx = iundefsym +j; if (sidx<0 || sidx>= bin->nsymtab) continue; stridx = bin->symtab[sidx].n_strx; if (stridx < 0 || stridx >= bin->symstrlen) continue; } if (!strcmp ((char *)bin->symstr + stridx, sym_name)) { sym_ord = j; break; } } break; } case BIND_OPCODE_SET_TYPE_IMM: type = imm; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = SLEB(); break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: seg_idx = imm; if (seg_idx < 0 || seg_idx >= bin->nsegs) { bprintf ("Error: BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB" " has unexistent segment %d\n", seg_idx); addr = 0LL; return 0; // early exit to avoid future mayhem } else { addr = bin->segs[seg_idx].vmaddr + ULEB(); segmentAddress = bin->segs[seg_idx].vmaddr \ + bin->segs[seg_idx].vmsize; } break; case BIND_OPCODE_ADD_ADDR_ULEB: addr += ULEB(); break; #define DO_BIND() do {\ if (sym_ord < 0 || seg_idx < 0 ) break;\ if (i >= (bind_size + lazy_size)) break;\ relocs[i].addr = addr;\ relocs[i].offset = addr - bin->segs[seg_idx].vmaddr + bin->segs[seg_idx].fileoff;\ if (type == BIND_TYPE_TEXT_PCREL32)\ relocs[i].addend = addend - (bin->baddr + addr);\ else relocs[i].addend = addend;\ /* library ordinal ??? */ \ relocs[i].ord = lib_ord;\ relocs[i].ord = sym_ord;\ relocs[i].type = rel_type;\ relocs[i++].last = 0;\ } while (0) case BIND_OPCODE_DO_BIND: if (addr >= segmentAddress) { bprintf ("Error: Malformed DO bind opcode\n"); goto beach; } DO_BIND(); addr += wordsize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: if (addr >= segmentAddress) { bprintf ("Error: Malformed ADDR ULEB bind opcode\n"); goto beach; } DO_BIND(); addr += ULEB() + wordsize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: if (addr >= segmentAddress) { bprintf ("Error: Malformed IMM SCALED bind opcode\n"); goto beach; } DO_BIND(); addr += (ut64)imm * (ut64)wordsize + wordsize; break; case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: count = ULEB(); skip = ULEB(); for (j = 0; j < count; j++) { if (addr >= segmentAddress) { bprintf ("Error: Malformed ULEB TIMES bind opcode\n"); goto beach; } DO_BIND(); addr += skip + wordsize; } break; #undef DO_BIND #undef ULEB #undef SLEB default: bprintf ("Error: unknown bind opcode 0x%02x in dyld_info\n", *ur.p); free (opcodes); relocs[i].last = 1; return relocs; } } free (opcodes); } else { int j; if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) { return NULL; } if (!(relocs = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct reloc_t)))) { return NULL; } for (j = 0; j < bin->dysymtab.nundefsym; j++) { if (parse_import_ptr (bin, &relocs[i], bin->dysymtab.iundefsym + j)) { relocs[i].ord = j; relocs[i++].last = 0; } } } beach: relocs[i].last = 1; return relocs; } struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) { struct addr_t *entry; int i; if (!bin->entry && !bin->sects) { return NULL; } if (!(entry = calloc (1, sizeof (struct addr_t)))) { return NULL; } if (bin->entry) { entry->addr = entry_to_vaddr (bin); entry->offset = addr_to_offset (bin, entry->addr); entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0); sdb_num_set (bin->kv, "mach0.entry.vaddr", entry->addr, 0); sdb_num_set (bin->kv, "mach0.entry.paddr", bin->entry, 0); } if (!bin->entry || entry->offset == 0) { // XXX: section name doesnt matters at all.. just check for exec flags for (i = 0; i < bin->nsects; i++) { if (!strncmp (bin->sects[i].sectname, "__text", 6)) { entry->offset = (ut64)bin->sects[i].offset; sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0); entry->addr = (ut64)bin->sects[i].addr; if (!entry->addr) { // workaround for object files entry->addr = entry->offset; } break; } } bin->entry = entry->addr; } return entry; } void MACH0_(kv_loadlibs)(struct MACH0_(obj_t)* bin) { int i; for (i = 0; i < bin->nlibs; i++) { sdb_set (bin->kv, sdb_fmt ("libs.%d.name", i), bin->libs[i], 0); } } struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) { return NULL; } if (!(libs = calloc ((bin->nlibs + 1), sizeof (struct lib_t)))) { return NULL; } for (i = 0; i < bin->nlibs; i++) { sdb_set (bin->kv, sdb_fmt ("libs.%d.name", i), bin->libs[i], 0); strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; } ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) { int i; if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER) { return 0; } for (i = 0; i < bin->nsegs; ++i) { if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0) { return bin->segs[i].vmaddr; } } return 0; } char* MACH0_(get_class)(struct MACH0_(obj_t)* bin) { #if R_BIN_MACH064 return r_str_new ("MACH064"); #else return r_str_new ("MACH0"); #endif } //XXX we are mixing up bits from cpu and opcodes //since thumb use 16 bits opcode but run in 32 bits //cpus so here we should only return 32 or 64 int MACH0_(get_bits)(struct MACH0_(obj_t)* bin) { if (bin) { int bits = MACH0_(get_bits_from_hdr) (&bin->hdr); if (bin->hdr.cputype == CPU_TYPE_ARM && bin->entry & 1) { return 16; } return bits; } return 32; } int MACH0_(get_bits_from_hdr)(struct MACH0_(mach_header)* hdr) { if (hdr->magic == MH_MAGIC_64 || hdr->magic == MH_CIGAM_64) { return 64; } if ((hdr->cpusubtype & CPU_SUBTYPE_MASK) == (CPU_SUBTYPE_ARM_V7K << 24)) { return 16; } return 32; } bool MACH0_(is_big_endian)(struct MACH0_(obj_t)* bin) { if (bin) { const int cpu = bin->hdr.cputype; return cpu == CPU_TYPE_POWERPC || cpu == CPU_TYPE_POWERPC64; } return false; } const char* MACH0_(get_intrp)(struct MACH0_(obj_t)* bin) { return bin? bin->intrp: NULL; } const char* MACH0_(get_os)(struct MACH0_(obj_t)* bin) { if (bin) switch (bin->os) { case 1: return "macos"; case 2: return "ios"; case 3: return "watchos"; case 4: return "tvos"; } return "darwin"; } const char* MACH0_(get_cputype_from_hdr)(struct MACH0_(mach_header) *hdr) { const char *archstr = "unknown"; switch (hdr->cputype) { case CPU_TYPE_VAX: archstr = "vax"; break; case CPU_TYPE_MC680x0: archstr = "mc680x0"; break; case CPU_TYPE_I386: case CPU_TYPE_X86_64: archstr = "x86"; break; case CPU_TYPE_MC88000: archstr = "mc88000"; break; case CPU_TYPE_MC98000: archstr = "mc98000"; break; case CPU_TYPE_HPPA: archstr = "hppa"; break; case CPU_TYPE_ARM: case CPU_TYPE_ARM64: archstr = "arm"; break; case CPU_TYPE_SPARC: archstr = "sparc"; break; case CPU_TYPE_MIPS: archstr = "mips"; break; case CPU_TYPE_I860: archstr = "i860"; break; case CPU_TYPE_POWERPC: case CPU_TYPE_POWERPC64: archstr = "ppc"; } return archstr; } const char* MACH0_(get_cputype)(struct MACH0_(obj_t)* bin) { return bin? MACH0_(get_cputype_from_hdr) (&bin->hdr): "unknown"; } // TODO: use const char* char* MACH0_(get_cpusubtype_from_hdr)(struct MACH0_(mach_header) *hdr) { if (hdr) { switch (hdr->cputype) { case CPU_TYPE_VAX: switch (hdr->cpusubtype) { case CPU_SUBTYPE_VAX_ALL: return strdup ("all"); case CPU_SUBTYPE_VAX780: return strdup ("vax780"); case CPU_SUBTYPE_VAX785: return strdup ("vax785"); case CPU_SUBTYPE_VAX750: return strdup ("vax750"); case CPU_SUBTYPE_VAX730: return strdup ("vax730"); case CPU_SUBTYPE_UVAXI: return strdup ("uvaxI"); case CPU_SUBTYPE_UVAXII: return strdup ("uvaxII"); case CPU_SUBTYPE_VAX8200: return strdup ("vax8200"); case CPU_SUBTYPE_VAX8500: return strdup ("vax8500"); case CPU_SUBTYPE_VAX8600: return strdup ("vax8600"); case CPU_SUBTYPE_VAX8650: return strdup ("vax8650"); case CPU_SUBTYPE_VAX8800: return strdup ("vax8800"); case CPU_SUBTYPE_UVAXIII: return strdup ("uvaxIII"); default: return strdup ("Unknown vax subtype"); } case CPU_TYPE_MC680x0: switch (hdr->cpusubtype) { case CPU_SUBTYPE_MC68030: return strdup ("mc68030"); case CPU_SUBTYPE_MC68040: return strdup ("mc68040"); case CPU_SUBTYPE_MC68030_ONLY: return strdup ("mc68030 only"); default: return strdup ("Unknown mc680x0 subtype"); } case CPU_TYPE_I386: switch (hdr->cpusubtype) { case CPU_SUBTYPE_386: return strdup ("386"); case CPU_SUBTYPE_486: return strdup ("486"); case CPU_SUBTYPE_486SX: return strdup ("486sx"); case CPU_SUBTYPE_PENT: return strdup ("Pentium"); case CPU_SUBTYPE_PENTPRO: return strdup ("Pentium Pro"); case CPU_SUBTYPE_PENTII_M3: return strdup ("Pentium 3 M3"); case CPU_SUBTYPE_PENTII_M5: return strdup ("Pentium 3 M5"); case CPU_SUBTYPE_CELERON: return strdup ("Celeron"); case CPU_SUBTYPE_CELERON_MOBILE: return strdup ("Celeron Mobile"); case CPU_SUBTYPE_PENTIUM_3: return strdup ("Pentium 3"); case CPU_SUBTYPE_PENTIUM_3_M: return strdup ("Pentium 3 M"); case CPU_SUBTYPE_PENTIUM_3_XEON: return strdup ("Pentium 3 Xeon"); case CPU_SUBTYPE_PENTIUM_M: return strdup ("Pentium Mobile"); case CPU_SUBTYPE_PENTIUM_4: return strdup ("Pentium 4"); case CPU_SUBTYPE_PENTIUM_4_M: return strdup ("Pentium 4 M"); case CPU_SUBTYPE_ITANIUM: return strdup ("Itanium"); case CPU_SUBTYPE_ITANIUM_2: return strdup ("Itanium 2"); case CPU_SUBTYPE_XEON: return strdup ("Xeon"); case CPU_SUBTYPE_XEON_MP: return strdup ("Xeon MP"); default: return strdup ("Unknown i386 subtype"); } case CPU_TYPE_X86_64: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_X86_64_ALL: return strdup ("x86 64 all"); case CPU_SUBTYPE_X86_ARCH1: return strdup ("x86 arch 1"); default: return strdup ("Unknown x86 subtype"); } case CPU_TYPE_MC88000: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_MC88000_ALL: return strdup ("all"); case CPU_SUBTYPE_MC88100: return strdup ("mc88100"); case CPU_SUBTYPE_MC88110: return strdup ("mc88110"); default: return strdup ("Unknown mc88000 subtype"); } case CPU_TYPE_MC98000: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_MC98000_ALL: return strdup ("all"); case CPU_SUBTYPE_MC98601: return strdup ("mc98601"); default: return strdup ("Unknown mc98000 subtype"); } case CPU_TYPE_HPPA: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_HPPA_7100: return strdup ("hppa7100"); case CPU_SUBTYPE_HPPA_7100LC: return strdup ("hppa7100LC"); default: return strdup ("Unknown hppa subtype"); } case CPU_TYPE_ARM64: return strdup ("v8"); case CPU_TYPE_ARM: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_ARM_ALL: return strdup ("all"); case CPU_SUBTYPE_ARM_V4T: return strdup ("v4t"); case CPU_SUBTYPE_ARM_V5: return strdup ("v5"); case CPU_SUBTYPE_ARM_V6: return strdup ("v6"); case CPU_SUBTYPE_ARM_XSCALE: return strdup ("xscale"); case CPU_SUBTYPE_ARM_V7: return strdup ("v7"); case CPU_SUBTYPE_ARM_V7F: return strdup ("v7f"); case CPU_SUBTYPE_ARM_V7S: return strdup ("v7s"); case CPU_SUBTYPE_ARM_V7K: return strdup ("v7k"); case CPU_SUBTYPE_ARM_V7M: return strdup ("v7m"); case CPU_SUBTYPE_ARM_V7EM: return strdup ("v7em"); default: return r_str_newf ("unknown ARM subtype %d", hdr->cpusubtype & 0xff); } case CPU_TYPE_SPARC: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_SPARC_ALL: return strdup ("all"); default: return strdup ("Unknown sparc subtype"); } case CPU_TYPE_MIPS: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_MIPS_ALL: return strdup ("all"); case CPU_SUBTYPE_MIPS_R2300: return strdup ("r2300"); case CPU_SUBTYPE_MIPS_R2600: return strdup ("r2600"); case CPU_SUBTYPE_MIPS_R2800: return strdup ("r2800"); case CPU_SUBTYPE_MIPS_R2000a: return strdup ("r2000a"); case CPU_SUBTYPE_MIPS_R2000: return strdup ("r2000"); case CPU_SUBTYPE_MIPS_R3000a: return strdup ("r3000a"); case CPU_SUBTYPE_MIPS_R3000: return strdup ("r3000"); default: return strdup ("Unknown mips subtype"); } case CPU_TYPE_I860: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_I860_ALL: return strdup ("all"); case CPU_SUBTYPE_I860_860: return strdup ("860"); default: return strdup ("Unknown i860 subtype"); } case CPU_TYPE_POWERPC: case CPU_TYPE_POWERPC64: switch (hdr->cpusubtype & 0xff) { case CPU_SUBTYPE_POWERPC_ALL: return strdup ("all"); case CPU_SUBTYPE_POWERPC_601: return strdup ("601"); case CPU_SUBTYPE_POWERPC_602: return strdup ("602"); case CPU_SUBTYPE_POWERPC_603: return strdup ("603"); case CPU_SUBTYPE_POWERPC_603e: return strdup ("603e"); case CPU_SUBTYPE_POWERPC_603ev: return strdup ("603ev"); case CPU_SUBTYPE_POWERPC_604: return strdup ("604"); case CPU_SUBTYPE_POWERPC_604e: return strdup ("604e"); case CPU_SUBTYPE_POWERPC_620: return strdup ("620"); case CPU_SUBTYPE_POWERPC_750: return strdup ("750"); case CPU_SUBTYPE_POWERPC_7400: return strdup ("7400"); case CPU_SUBTYPE_POWERPC_7450: return strdup ("7450"); case CPU_SUBTYPE_POWERPC_970: return strdup ("970"); default: return strdup ("Unknown ppc subtype"); } } } return strdup ("Unknown cputype"); } char* MACH0_(get_cpusubtype)(struct MACH0_(obj_t)* bin) { if (bin) { return MACH0_(get_cpusubtype_from_hdr) (&bin->hdr); } return strdup ("Unknown"); } int MACH0_(is_pie)(struct MACH0_(obj_t)* bin) { return (bin && bin->hdr.filetype == MH_EXECUTE && bin->hdr.flags & MH_PIE); } int MACH0_(has_nx)(struct MACH0_(obj_t)* bin) { return (bin && bin->hdr.filetype == MH_EXECUTE && bin->hdr.flags & MH_NO_HEAP_EXECUTION); } char* MACH0_(get_filetype_from_hdr)(struct MACH0_(mach_header) *hdr) { const char *mhtype = "Unknown"; switch (hdr->filetype) { case MH_OBJECT: mhtype = "Relocatable object"; break; case MH_EXECUTE: mhtype = "Executable file"; break; case MH_FVMLIB: mhtype = "Fixed VM shared library"; break; case MH_CORE: mhtype = "Core file"; break; case MH_PRELOAD: mhtype = "Preloaded executable file"; break; case MH_DYLIB: mhtype = "Dynamically bound shared library"; break; case MH_DYLINKER: mhtype = "Dynamic link editor"; break; case MH_BUNDLE: mhtype = "Dynamically bound bundle file"; break; case MH_DYLIB_STUB: mhtype = "Shared library stub for static linking (no sections)"; break; case MH_DSYM: mhtype = "Companion file with only debug sections"; break; } return strdup (mhtype); } char* MACH0_(get_filetype)(struct MACH0_(obj_t)* bin) { if (bin) { return MACH0_(get_filetype_from_hdr) (&bin->hdr); } return strdup ("Unknown"); } ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) { ut64 addr = 0LL; struct symbol_t *symbols; int i; if (!(symbols = MACH0_(get_symbols) (bin))) { return 0; } for (i = 0; !symbols[i].last; i++) { const char *name = symbols[i].name; if (!strcmp (name, "__Dmain")) { addr = symbols[i].addr; break; } if (strstr (name, "4main") && !strstr (name, "STATIC")) { addr = symbols[i].addr; break; } if (!strcmp (symbols[i].name, "_main")) { addr = symbols[i].addr; // break; } } free (symbols); if (!addr && bin->main_cmd.cmd == LC_MAIN) { addr = bin->entry + bin->baddr; } if (!addr) { ut8 b[128]; ut64 entry = addr_to_offset(bin, bin->entry); // XXX: X86 only and hacky! if (entry > bin->size || entry + sizeof (b) > bin->size) { return 0; } i = r_buf_read_at (bin->b, entry, b, sizeof (b)); if (i < 1) { return 0; } for (i = 0; i < 64; i++) { if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) { int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24); return bin->entry + i + 5 + delta; } } } return addr; } void MACH0_(mach_headerfields)(RBinFile *file) { RBuffer *buf = file->buf; int n = 0; struct MACH0_(mach_header) *mh = MACH0_(get_hdr_from_bytes)(buf); if (!mh) { return; } printf ("0x00000000 Magic 0x%x\n", mh->magic); printf ("0x00000004 CpuType 0x%x\n", mh->cputype); printf ("0x00000008 CpuSubType 0x%x\n", mh->cpusubtype); printf ("0x0000000c FileType 0x%x\n", mh->filetype); printf ("0x00000010 nCmds %d\n", mh->ncmds); printf ("0x00000014 sizeOfCmds %d\n", mh->sizeofcmds); printf ("0x00000018 Flags 0x%x\n", mh->flags); ut64 addr = 0x20 - 4; ut32 word = 0; ut8 wordbuf[sizeof (word)]; #define READWORD() \ addr += 4; \ if (!r_buf_read_at (buf, addr, (ut8*)wordbuf, 4)) { \ eprintf ("Invalid address in buffer."); \ break; \ } \ word = r_read_le32 (wordbuf); for (n = 0; n < mh->ncmds; n++) { printf ("\n# Load Command %d\n", n); READWORD(); int lcType = word; eprintf ("0x%08"PFMT64x" cmd 0x%x %s\n", addr, lcType, cmd_to_string (lcType)); READWORD(); int lcSize = word; word &= 0xFFFFFF; printf ("0x%08"PFMT64x" cmdsize %d\n", addr, word); if (lcSize < 1) { eprintf ("Invalid size for a load command\n"); break; } switch (lcType) { case LC_ID_DYLIB: // install_name_tool printf ("0x%08"PFMT64x" id %s\n", addr + 20, r_buf_get_at (buf, addr + 20, NULL)); break; case LC_UUID: printf ("0x%08"PFMT64x" uuid %s\n", addr + 20, r_buf_get_at (buf, addr + 32, NULL)); break; case LC_LOAD_DYLIB: printf ("0x%08"PFMT64x" uuid %s\n", addr + 20, r_buf_get_at (buf, addr + 20, NULL)); break; case LC_RPATH: printf ("0x%08"PFMT64x" uuid %s\n", addr + 8, r_buf_get_at (buf, addr + 8, NULL)); break; case LC_CODE_SIGNATURE: { ut32 *words = (ut32*)r_buf_get_at (buf, addr + 4, NULL); printf ("0x%08"PFMT64x" dataoff 0x%08x\n", addr + 4, words[0]); printf ("0x%08"PFMT64x" datasize %d\n", addr + 8, words[1]); printf ("# wtf mach0.sign %d @ 0x%x\n", words[1], words[0]); } break; } addr += word - 8; } free (mh); } RList* MACH0_(mach_fields)(RBinFile *bf) { struct MACH0_(mach_header) *mh = MACH0_(get_hdr_from_bytes)(bf->buf); if (!mh) { return NULL; } RList *ret = r_list_new (); if (!ret) { return NULL; } ret->free = free; ut64 addr = 0; #define ROW(nam,siz,val,fmt) \ r_list_append (ret, r_bin_field_new (addr, addr, siz, nam, sdb_fmt ("0x%08x", val), fmt)); \ addr += 4; ROW("hdr.magic", 4, mh->magic, "x"); ROW("hdr.cputype", 4, mh->cputype, NULL); ROW("hdr.cpusubtype", 4, mh->cpusubtype, NULL); ROW("hdr.filetype", 4, mh->filetype, NULL); ROW("hdr.ncmds", 4, mh->ncmds, NULL); ROW("hdr.sizeofcmds", 4, mh->sizeofcmds, NULL); free (mh); return ret; } struct MACH0_(mach_header) * MACH0_(get_hdr_from_bytes)(RBuffer *buf) { ut8 magicbytes[sizeof (ut32)] = {0}; ut8 machohdrbytes[sizeof (struct MACH0_(mach_header))] = {0}; int len; struct MACH0_(mach_header) *macho_hdr = R_NEW0 (struct MACH0_(mach_header)); bool big_endian = false; if (!macho_hdr) { return NULL; } if (r_buf_read_at (buf, 0, magicbytes, 4) < 1) { free (macho_hdr); return false; } if (r_read_le32 (magicbytes) == 0xfeedface) { big_endian = false; } else if (r_read_be32 (magicbytes) == 0xfeedface) { big_endian = true; } else if (r_read_le32 (magicbytes) == FAT_MAGIC) { big_endian = false; } else if (r_read_be32 (magicbytes) == FAT_MAGIC) { big_endian = true; } else if (r_read_le32 (magicbytes) == 0xfeedfacf) { big_endian = false; } else if (r_read_be32 (magicbytes) == 0xfeedfacf) { big_endian = true; } else { /* also extract non-mach0s */ #if 0 free (macho_hdr); return NULL; #endif } len = r_buf_read_at (buf, 0, machohdrbytes, sizeof (machohdrbytes)); if (len != sizeof (struct MACH0_(mach_header))) { free (macho_hdr); return NULL; } macho_hdr->magic = r_read_ble (&machohdrbytes[0], big_endian, 32); macho_hdr->cputype = r_read_ble (&machohdrbytes[4], big_endian, 32); macho_hdr->cpusubtype = r_read_ble (&machohdrbytes[8], big_endian, 32); macho_hdr->filetype = r_read_ble (&machohdrbytes[12], big_endian, 32); macho_hdr->ncmds = r_read_ble (&machohdrbytes[16], big_endian, 32); macho_hdr->sizeofcmds = r_read_ble (&machohdrbytes[20], big_endian, 32); macho_hdr->flags = r_read_ble (&machohdrbytes[24], big_endian, 32); #if R_BIN_MACH064 macho_hdr->reserved = r_read_ble (&machohdrbytes[28], big_endian, 32); #endif return macho_hdr; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_145_0
crossvul-cpp_data_good_2651_0
/* * Decode and print Zephyr packets. * * http://web.mit.edu/zephyr/doc/protocol * * Copyright (c) 2001 Nickolai Zeldovich <kolya@MIT.EDU> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * The name of the author(s) may not be used to endorse or promote * products derived from this software without specific prior written * permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. */ /* \summary: Zephyr printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "netdissect.h" struct z_packet { const char *version; int numfields; int kind; const char *uid; int port; int auth; int authlen; const char *authdata; const char *class; const char *inst; const char *opcode; const char *sender; const char *recipient; const char *format; int cksum; int multi; const char *multi_uid; /* Other fields follow here.. */ }; enum z_packet_type { Z_PACKET_UNSAFE = 0, Z_PACKET_UNACKED, Z_PACKET_ACKED, Z_PACKET_HMACK, Z_PACKET_HMCTL, Z_PACKET_SERVACK, Z_PACKET_SERVNAK, Z_PACKET_CLIENTACK, Z_PACKET_STAT }; static const struct tok z_types[] = { { Z_PACKET_UNSAFE, "unsafe" }, { Z_PACKET_UNACKED, "unacked" }, { Z_PACKET_ACKED, "acked" }, { Z_PACKET_HMACK, "hm-ack" }, { Z_PACKET_HMCTL, "hm-ctl" }, { Z_PACKET_SERVACK, "serv-ack" }, { Z_PACKET_SERVNAK, "serv-nak" }, { Z_PACKET_CLIENTACK, "client-ack" }, { Z_PACKET_STAT, "stat" }, { 0, NULL } }; static char z_buf[256]; static const char * parse_field(netdissect_options *ndo, const char **pptr, int *len, int *truncated) { const char *s; /* Start of string */ s = *pptr; /* Scan for the NUL terminator */ for (;;) { if (*len == 0) { /* Ran out of packet data without finding it */ return NULL; } if (!ND_TTEST(**pptr)) { /* Ran out of captured data without finding it */ *truncated = 1; return NULL; } if (**pptr == '\0') { /* Found it */ break; } /* Keep scanning */ (*pptr)++; (*len)--; } /* Skip the NUL terminator */ (*pptr)++; (*len)--; return s; } static const char * z_triple(const char *class, const char *inst, const char *recipient) { if (!*recipient) recipient = "*"; snprintf(z_buf, sizeof(z_buf), "<%s,%s,%s>", class, inst, recipient); z_buf[sizeof(z_buf)-1] = '\0'; return z_buf; } static const char * str_to_lower(const char *string) { char *zb_string; strncpy(z_buf, string, sizeof(z_buf)); z_buf[sizeof(z_buf)-1] = '\0'; zb_string = z_buf; while (*zb_string) { *zb_string = tolower((unsigned char)(*zb_string)); zb_string++; } return z_buf; } void zephyr_print(netdissect_options *ndo, const u_char *cp, int length) { struct z_packet z; const char *parse = (const char *) cp; int parselen = length; const char *s; int lose = 0; int truncated = 0; /* squelch compiler warnings */ z.kind = 0; z.class = 0; z.inst = 0; z.opcode = 0; z.sender = 0; z.recipient = 0; #define PARSE_STRING \ s = parse_field(ndo, &parse, &parselen, &truncated); \ if (truncated) goto trunc; \ if (!s) lose = 1; #define PARSE_FIELD_INT(field) \ PARSE_STRING \ if (!lose) field = strtol(s, 0, 16); #define PARSE_FIELD_STR(field) \ PARSE_STRING \ if (!lose) field = s; PARSE_FIELD_STR(z.version); if (lose) return; if (strncmp(z.version, "ZEPH", 4)) return; PARSE_FIELD_INT(z.numfields); PARSE_FIELD_INT(z.kind); PARSE_FIELD_STR(z.uid); PARSE_FIELD_INT(z.port); PARSE_FIELD_INT(z.auth); PARSE_FIELD_INT(z.authlen); PARSE_FIELD_STR(z.authdata); PARSE_FIELD_STR(z.class); PARSE_FIELD_STR(z.inst); PARSE_FIELD_STR(z.opcode); PARSE_FIELD_STR(z.sender); PARSE_FIELD_STR(z.recipient); PARSE_FIELD_STR(z.format); PARSE_FIELD_INT(z.cksum); PARSE_FIELD_INT(z.multi); PARSE_FIELD_STR(z.multi_uid); if (lose) goto trunc; ND_PRINT((ndo, " zephyr")); if (strncmp(z.version+4, "0.2", 3)) { ND_PRINT((ndo, " v%s", z.version+4)); return; } ND_PRINT((ndo, " %s", tok2str(z_types, "type %d", z.kind))); if (z.kind == Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *ackdata = NULL; PARSE_FIELD_STR(ackdata); if (!lose && strcmp(ackdata, "SENT")) ND_PRINT((ndo, "/%s", str_to_lower(ackdata))); } if (*z.sender) ND_PRINT((ndo, " %s", z.sender)); if (!strcmp(z.class, "USER_LOCATE")) { if (!strcmp(z.opcode, "USER_HIDE")) ND_PRINT((ndo, " hide")); else if (!strcmp(z.opcode, "USER_UNHIDE")) ND_PRINT((ndo, " unhide")); else ND_PRINT((ndo, " locate %s", z.inst)); return; } if (!strcmp(z.class, "ZEPHYR_ADMIN")) { ND_PRINT((ndo, " zephyr-admin %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "ZEPHYR_CTL")) { if (!strcmp(z.inst, "CLIENT")) { if (!strcmp(z.opcode, "SUBSCRIBE") || !strcmp(z.opcode, "SUBSCRIBE_NODEFS") || !strcmp(z.opcode, "UNSUBSCRIBE")) { ND_PRINT((ndo, " %ssub%s", strcmp(z.opcode, "SUBSCRIBE") ? "un" : "", strcmp(z.opcode, "SUBSCRIBE_NODEFS") ? "" : "-nodefs")); if (z.kind != Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *c = NULL, *i = NULL, *r = NULL; PARSE_FIELD_STR(c); PARSE_FIELD_STR(i); PARSE_FIELD_STR(r); if (!lose) ND_PRINT((ndo, " %s", z_triple(c, i, r))); } return; } if (!strcmp(z.opcode, "GIMME")) { ND_PRINT((ndo, " ret")); return; } if (!strcmp(z.opcode, "GIMMEDEFS")) { ND_PRINT((ndo, " gimme-defs")); return; } if (!strcmp(z.opcode, "CLEARSUB")) { ND_PRINT((ndo, " clear-subs")); return; } ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "HM")) { ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "REALM")) { if (!strcmp(z.opcode, "ADD_SUBSCRIBE")) ND_PRINT((ndo, " realm add-subs")); if (!strcmp(z.opcode, "REQ_SUBSCRIBE")) ND_PRINT((ndo, " realm req-subs")); if (!strcmp(z.opcode, "RLM_SUBSCRIBE")) ND_PRINT((ndo, " realm rlm-sub")); if (!strcmp(z.opcode, "RLM_UNSUBSCRIBE")) ND_PRINT((ndo, " realm rlm-unsub")); return; } } if (!strcmp(z.class, "HM_CTL")) { ND_PRINT((ndo, " hm_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "HM_STAT")) { if (!strcmp(z.inst, "HMST_CLIENT") && !strcmp(z.opcode, "GIMMESTATS")) { ND_PRINT((ndo, " get-client-stats")); return; } } if (!strcmp(z.class, "WG_CTL")) { ND_PRINT((ndo, " wg_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "LOGIN")) { if (!strcmp(z.opcode, "USER_FLUSH")) { ND_PRINT((ndo, " flush_locs")); return; } if (!strcmp(z.opcode, "NONE") || !strcmp(z.opcode, "OPSTAFF") || !strcmp(z.opcode, "REALM-VISIBLE") || !strcmp(z.opcode, "REALM-ANNOUNCED") || !strcmp(z.opcode, "NET-VISIBLE") || !strcmp(z.opcode, "NET-ANNOUNCED")) { ND_PRINT((ndo, " set-exposure %s", str_to_lower(z.opcode))); return; } } if (!*z.recipient) z.recipient = "*"; ND_PRINT((ndo, " to %s", z_triple(z.class, z.inst, z.recipient))); if (*z.opcode) ND_PRINT((ndo, " op %s", z.opcode)); return; trunc: ND_PRINT((ndo, " [|zephyr] (%d)", length)); return; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2651_0
crossvul-cpp_data_good_2861_1
/* radare - LGPL - Copyright 2007-2017 - pancake */ #include <r_flag.h> #include <r_util.h> #include <r_cons.h> #include <stdio.h> R_LIB_VERSION(r_flag); #define ISNULLSTR(x) (!(x) || !*(x)) #define IS_IN_SPACE(f, i) ((f)->space_idx != -1 && (i)->space != (f)->space_idx) static const char *str_callback(RNum *user, ut64 off, int *ok) { const RList *list; RFlag *f = (RFlag*)user; RFlagItem *item; if (ok) { *ok = 0; } if (f) { list = r_flag_get_list (f, off); item = r_list_get_top (list); if (item) { if (ok) { *ok = true; } return item->name; } } return NULL; } static void flag_free_kv(HtKv *kv) { free (kv->key); //we do not free kv->value since there is a reference in other list free (kv); } static void flag_skiplist_free(void *data) { RFlagsAtOffset *item = (RFlagsAtOffset *)data; r_list_free (item->flags); free (data); } static int flag_skiplist_cmp(const void *va, const void *vb) { const RFlagsAtOffset *a = (RFlagsAtOffset *)va, *b = (RFlagsAtOffset *)vb; if (a->off == b->off) { return 0; } return a->off < b->off ? -1 : 1; } static ut64 num_callback(RNum *user, const char *name, int *ok) { RFlag *f = (RFlag*)user; RFlagItem *item; if (ok) { *ok = 0; } item = ht_find (f->ht_name, name, NULL); if (item) { // NOTE: to avoid warning infinite loop here we avoid recursivity if (item->alias) { return 0LL; } if (ok) { *ok = 1; } return item->offset; } return 0LL; } /* return the list of flag at the nearest position. dir == -1 -> result <= off dir == 0 -> result == off dir == 1 -> result >= off*/ static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; } static void remove_offsetmap(RFlag *f, RFlagItem *item) { RFlagsAtOffset *flags = r_flag_get_nearest_list (f, item->offset, 0); if (flags) { r_list_delete_data (flags->flags, item); if (r_list_empty (flags->flags)) { r_skiplist_delete (f->by_off, flags); } } } static int set_name(RFlagItem *item, const char *name) { if (item->name != item->realname) { free (item->name); } item->name = strdup (name); if (!item->name) { return false; } r_str_chop (item->name); r_name_filter (item->name, 0); // TODO: name_filter should be chopping already free (item->realname); item->realname = item->name; return true; } R_API RFlag * r_flag_new() { int i; RFlag *f = R_NEW0 (RFlag); if (!f) return NULL; f->num = r_num_new (&num_callback, &str_callback, f); if (!f->num) { r_flag_free (f); return NULL; } f->base = 0; f->cb_printf = (PrintfCallback)printf; #if R_FLAG_ZONE_USE_SDB f->zones = sdb_new0 (); #else f->zones = NULL; #endif f->flags = r_list_new (); if (!f->flags) { r_flag_free (f); return NULL; } f->flags->free = (RListFree) r_flag_item_free; f->space_idx = -1; f->spacestack = r_list_newf (NULL); if (!f->spacestack) { r_flag_free (f); return NULL; } f->ht_name = ht_new (NULL, flag_free_kv, NULL); f->by_off = r_skiplist_new (flag_skiplist_free, flag_skiplist_cmp); #if R_FLAG_ZONE_USE_SDB sdb_free (f->zones); #else r_list_free (f->zones); #endif for (i = 0; i < R_FLAG_SPACES_MAX; i++) { f->spaces[i] = NULL; } return f; } R_API void r_flag_item_free(RFlagItem *item) { if (item) { free (item->color); free (item->comment); free (item->alias); /* release only one of the two pointers if they are the same */ if (item->name != item->realname) { free (item->name); } free (item->realname); free (item); } } R_API RFlag *r_flag_free(RFlag *f) { int i; for (i = 0; i < R_FLAG_SPACES_MAX; i++) { free (f->spaces[i]); } r_skiplist_free (f->by_off); ht_free (f->ht_name); r_list_free (f->flags); r_list_free (f->spacestack); r_num_free (f->num); free (f); return NULL; } /* print with r_cons the flag items in the flag f, given as a parameter */ R_API void r_flag_list(RFlag *f, int rad, const char *pfx) { bool in_range = false; ut64 range_from = UT64_MAX; ut64 range_to = UT64_MAX; int fs = -1; RListIter *iter; RFlagItem *flag; if (rad == 'i') { char *sp, *arg = strdup (pfx + 1); sp = strchr (arg, ' '); if (sp) { *sp++ = 0; range_from = r_num_math (f->num, arg); range_to = r_num_math (f->num, sp); } else { const int bsize = 4096; range_from = r_num_math (f->num, arg); range_to = range_from + bsize; } in_range = true; free (arg); rad = pfx[0]; pfx = NULL; } if (pfx && !*pfx) { pfx = NULL; } switch (rad) { case 'j': { int first = 1; f->cb_printf ("["); r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } f->cb_printf ("%s{\"name\":\"%s\",\"size\":%"PFMT64d",", first?"":",", flag->name, flag->size); if (flag->alias) { f->cb_printf ("\"alias\":\"%s\"", flag->alias); } else { f->cb_printf ("\"offset\":%"PFMT64d, flag->offset); } if (flag->comment) f->cb_printf (",\"comment\":\"}"); else f->cb_printf ("}"); first = 0; } f->cb_printf ("]\n"); } break; case 1: case '*': r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (fs == -1 || flag->space != fs) { const char *flagspace; fs = flag->space; flagspace = r_flag_space_get_i (f, fs); if (!flagspace || !*flagspace) flagspace = "*"; f->cb_printf ("fs %s\n", flagspace); } if (flag->alias) { f->cb_printf ("fa %s %s\n", flag->name, flag->alias); if (flag->comment && *flag->comment) f->cb_printf ("\"fC %s %s\"\n", flag->name, flag->comment); } else { f->cb_printf ("f %s %"PFMT64d" 0x%08"PFMT64x"%s%s %s\n", flag->name, flag->size, flag->offset, pfx?"+":"", pfx?pfx:"", flag->comment? flag->comment:""); } } break; case 'n': // show original name r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (flag->alias) { f->cb_printf ("%s %"PFMT64d" %s\n", flag->alias, flag->size, flag->realname); } else { f->cb_printf ("0x%08"PFMT64x" %"PFMT64d" %s\n", flag->offset, flag->size, flag->realname); } } break; default: r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (flag->alias) { f->cb_printf ("%s %"PFMT64d" %s\n", flag->alias, flag->size, flag->name); } else { f->cb_printf ("0x%08"PFMT64x" %"PFMT64d" %s\n", flag->offset, flag->size, flag->name); } } break; } } static RFlagItem *evalFlag(RFlag *f, RFlagItem *item) { if (item && item->alias) { item->offset = r_num_math (f->num, item->alias); } return item; } /* return true if flag.* exist at offset. Otherwise, false is returned. * For example (f, "sym", 3, 0x1000)*/ R_API bool r_flag_exist_at(RFlag *f, const char *flag_prefix, ut16 fp_size, ut64 off) { RListIter *iter = NULL; RFlagItem *item = NULL; if (!f) { return false; } const RList *list = r_flag_get_list (f, off); if (!list) { return false; } r_list_foreach (list, iter, item) { if (item->name && !strncmp (item->name, flag_prefix, fp_size)) { return true; } } return false; } /* return the flag item with name "name" in the RFlag "f", if it exists. * Otherwise, NULL is returned. */ R_API RFlagItem *r_flag_get(RFlag *f, const char *name) { RFlagItem *r; if (!f) { return NULL; } r = ht_find (f->ht_name, name, NULL); return evalFlag (f, r); } /* return the first flag item that can be found at offset "off", or NULL otherwise */ R_API RFlagItem *r_flag_get_i(RFlag *f, ut64 off) { const RList *list; if (!f) { return NULL; } list = r_flag_get_list (f, off); return list ? evalFlag (f, r_list_get_top (list)) : NULL; } /* return the first flag item at offset "off" that doesn't start with "loc.", * "fcn.", "section." or NULL if such a flag doesn't exist. * * XXX: this function is buggy and it's not really clear what's the purpose */ R_API RFlagItem *r_flag_get_i2(RFlag *f, ut64 off) { RFlagItem *oitem = NULL, *item = NULL; RListIter *iter; const RList *list = r_flag_get_list (f, off); if (!list) { return NULL; } r_list_foreach (list, iter, item) { if (!item->name) { continue; } /* catch sym. first */ if (!strncmp (item->name, "loc.", 4)) { continue; } if (!strncmp (item->name, "fcn.", 4)) { continue; } if (!strncmp (item->name, "section.", 8)) { continue; } if (!strncmp (item->name, "section_end.", 12)) { continue; } if (r_str_nlen (item->name, 5) > 4 && item->name[3] == '.') { oitem = item; break; } oitem = item; if (strlen (item->name) < 5 || item->name[3]!='.') continue; oitem = item; } return evalFlag (f, oitem); } static bool isFunctionFlag(const char *n) { return (!strncmp (n, "sym.func.", 9) || !strncmp (n, "method.", 7) || !strncmp (n, "sym.", 7) || !strncmp (n, "func.", 5) || !strncmp (n, "fcn.0", 5)); } /* returns the last flag item defined before or at the given offset. * NULL is returned if such a item is not found. */ R_API RFlagItem *r_flag_get_at(RFlag *f, ut64 off, bool closest) { RFlagItem *item, *nice = NULL; RListIter *iter; const RFlagsAtOffset *flags_at = r_flag_get_nearest_list (f, off, -1); if (!flags_at) { return NULL; } if (flags_at->off == off) { r_list_foreach (flags_at->flags, iter, item) { if (f->space_idx != -1 && item->space != f->space_idx) { continue; } if (nice) { if (isFunctionFlag (nice->name)) { nice = item; } } else { nice = item; } } return nice; } if (!closest) { return NULL; } while (!nice && flags_at) { r_list_foreach (flags_at->flags, iter, item) { if (f->space_strict && IS_IN_SPACE (f, item)) { continue; } if (item->offset == off) { eprintf ("XXX Should never happend\n"); return evalFlag (f, item); } nice = item; break; } if (flags_at->off) { flags_at = r_flag_get_nearest_list (f, flags_at->off - 1, -1); } else { flags_at = NULL; } } return evalFlag (f, nice); } /* return the list of flag items that are associated with a given offset */ R_API const RList* /*<RFlagItem*>*/ r_flag_get_list(RFlag *f, ut64 off) { const RFlagsAtOffset *item = r_flag_get_nearest_list (f, off, 0); return item ? item->flags : NULL; } R_API char *r_flag_get_liststr(RFlag *f, ut64 off) { RFlagItem *fi; RListIter *iter; const RList *list = r_flag_get_list (f, off); char *p = NULL; r_list_foreach (list, iter, fi) { p = r_str_appendf (p, "%s%s", fi->realname, iter->n ? "," : ":"); } return p; } R_API RFlagItem *r_flag_set_next(RFlag *f, const char *name, ut64 off, ut32 size) { if (!r_flag_get (f, name)) { return r_flag_set (f, name, off, size); } int i, newNameSize = strlen (name); char *newName = malloc (newNameSize + 16); strcpy (newName, name); for (i = 0; ; i++) { snprintf (newName + newNameSize, 15, ".%d", i); if (!r_flag_get (f, newName)) { RFlagItem *fi = r_flag_set (f, newName, off, size); free (newName); return fi; } } return NULL; } /* create or modify an existing flag item with the given name and parameters. * The realname of the item will be the same as the name. * NULL is returned in case of any errors during the process. */ R_API RFlagItem *r_flag_set(RFlag *f, const char *name, ut64 off, ut32 size) { RFlagItem *item = NULL; RList *list; /* contract fail */ if (!name || !*name) { return NULL; } item = r_flag_get (f, name); if (item) { if (item->offset == off) { item->size = size; return item; } remove_offsetmap (f, item); } else { item = R_NEW0 (RFlagItem); if (!item) { return NULL; } if (!set_name (item, name)) { eprintf ("Invalid flag name '%s'.\n", name); r_flag_item_free (item); return NULL; } //item share ownership prone to uaf, that is why only //f->flags has set up free pointer ht_insert (f->ht_name, item->name, item); r_list_append (f->flags, item); } item->space = f->space_idx; item->offset = off + f->base; item->size = size; list = (RList *)r_flag_get_list (f, off); if (!list) { RFlagsAtOffset *flagsAtOffset = R_NEW (RFlagsAtOffset); list = r_list_new (); flagsAtOffset->flags = list; flagsAtOffset->off = off; // CID 1378268: Resource leaks (RESOURCE_LEAK) // Ignoring storage allocated by "r_skiplist_insert(f->by_off, flagsAtOffset)" leaks it. r_skiplist_insert (f->by_off, flagsAtOffset); } r_list_append (list, item); return item; } /* add/replace/remove the alias of a flag item */ R_API void r_flag_item_set_alias(RFlagItem *item, const char *alias) { if (item) { free (item->alias); item->alias = ISNULLSTR (alias)? NULL: strdup (alias); } } /* add/replace/remove the comment of a flag item */ R_API void r_flag_item_set_comment(RFlagItem *item, const char *comment) { if (item) { free (item->comment); item->comment = ISNULLSTR (comment) ? NULL : strdup (comment); } } /* add/replace/remove the realname of a flag item */ R_API void r_flag_item_set_realname(RFlagItem *item, const char *realname) { if (item) { if (item->name != item->realname) { free (item->realname); } item->realname = ISNULLSTR (realname) ? NULL : strdup (realname); } } /* change the name of a flag item, if the new name is available. * true is returned if everything works well, false otherwise */ R_API int r_flag_rename(RFlag *f, RFlagItem *item, const char *name) { if (!f || !item || !name || !*name) { return false; } #if 0 ut64 off = item->offset; int size = item->size; r_flag_unset (f, item); r_flag_set (f, name, off, size); return true; #else ht_delete (f->ht_name, item->name); if (!set_name (item, name)) { return false; } ht_insert (f->ht_name, item->name, item); #endif return true; } /* unset the given flag item. * returns true if the item is successfully unset, false otherwise. * * NOTE: the item is freed. */ R_API int r_flag_unset(RFlag *f, RFlagItem *item) { remove_offsetmap (f, item); ht_delete (f->ht_name, item->name); r_list_delete_data (f->flags, item); return true; } /* unset the first flag item found at offset off. * return true if such a flag is found and unset, false otherwise. */ R_API int r_flag_unset_off(RFlag *f, ut64 off) { RFlagItem *item = r_flag_get_i (f, off); if (item && r_flag_unset (f, item)) { return true; } return false; } /* unset all the flag items that satisfy the given glob. * return the number of unset items. */ R_API int r_flag_unset_glob(RFlag *f, const char *glob) { RListIter it, *iter; RFlagItem *flag; int n = 0; r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) continue; if (!glob || r_str_glob (flag->name, glob)) { it.n = iter->n; r_flag_unset (f, flag); iter = &it; n++; } } return n; } /* unset the flag item with the given name. * returns true if the item is found and unset, false otherwise. */ R_API int r_flag_unset_name(RFlag *f, const char *name) { RFlagItem *item = ht_find (f->ht_name, name, NULL); return item && r_flag_unset (f, item); } /* unset all flag items in the RFlag f */ R_API void r_flag_unset_all(RFlag *f) { f->space_idx = -1; r_list_free (f->flags); f->flags = r_list_newf ((RListFree)r_flag_item_free); if (!f->flags) { return; } ht_free (f->ht_name); //don't set free since f->flags will free up items when needed avoiding uaf f->ht_name = ht_new (NULL, flag_free_kv, NULL); r_skiplist_purge (f->by_off); r_flag_space_unset (f, NULL); } R_API int r_flag_relocate(RFlag *f, ut64 off, ut64 off_mask, ut64 to) { ut64 neg_mask = ~(off_mask); RFlagItem *item; RListIter *iter; int n = 0; r_list_foreach (f->flags, iter, item) { ut64 fn = item->offset & neg_mask; ut64 on = off & neg_mask; if (fn == on) { ut64 fm = item->offset & off_mask; ut64 om = to & off_mask; item->offset = (to&neg_mask) + fm + om; n++; } } return n; } R_API int r_flag_move(RFlag *f, ut64 at, ut64 to) { RFlagItem *item = r_flag_get_i (f, at); if (item) { r_flag_set (f, item->name, to, item->size); return true; } return false; } #ifdef MYTEST int main () { RFlagItem *i; RFlag *f = r_flag_new (); r_flag_set (f, "rip", 0xfff333999000LL, 1); r_flag_set (f, "rip", 0xfff333999002LL, 1); r_flag_unset (f, "rip", NULL); r_flag_set (f, "rip", 3, 4); r_flag_set (f, "rip", 4, 4); r_flag_set (f, "corwp", 300, 4); r_flag_set (f, "barp", 300, 4); r_flag_set (f, "rip", 3, 4); r_flag_set (f, "rip", 4, 4); i = r_flag_get (f, "rip"); if (i) printf ("nRIP: %p %llx\n", i, i->offset); else printf ("nRIP: null\n"); i = r_flag_get_i (f, 0xfff333999000LL); if (i) printf ("iRIP: %p %llx\n", i, i->offset); else printf ("iRIP: null\n"); } #endif R_API const char *r_flag_color(RFlag *f, RFlagItem *it, const char *color) { if (!f || !it) return NULL; if (!color) return it->color; free (it->color); it->color = *color ? strdup (color) : NULL; return it->color; } // BIND R_API int r_flag_bind(RFlag *f, RFlagBind *fb) { fb->f = f; fb->exist_at = r_flag_exist_at; fb->get = r_flag_get; fb->get_at = r_flag_get_at; fb->set = r_flag_set; fb->set_fs = r_flag_space_set; return 0; } R_API int r_flag_count(RFlag *f, const char *glob) { int count = 0; RFlagItem *flag; RListIter *iter; r_list_foreach (f->flags, iter, flag) { if (r_str_glob (flag->name, glob)) count ++; } return count; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2861_1
crossvul-cpp_data_bad_3190_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3190_2
crossvul-cpp_data_good_3946_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * Print Virtual Channel * * Copyright 2010-2011 Vic Lee * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * Copyright 2016 Armin Novak <armin.novak@gmail.com> * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <winpr/crt.h> #include <winpr/string.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/stream.h> #include <winpr/interlocked.h> #include <winpr/path.h> #include <freerdp/channels/rdpdr.h> #include <freerdp/crypto/crypto.h> #include "../printer.h" #include <freerdp/client/printer.h> #include <freerdp/channels/log.h> #define TAG CHANNELS_TAG("printer.client") typedef struct _PRINTER_DEVICE PRINTER_DEVICE; struct _PRINTER_DEVICE { DEVICE device; rdpPrinter* printer; WINPR_PSLIST_HEADER pIrpList; HANDLE event; HANDLE stopEvent; HANDLE thread; rdpContext* rdpcontext; char port[64]; }; typedef enum { PRN_CONF_PORT = 0, PRN_CONF_PNP = 1, PRN_CONF_DRIVER = 2, PRN_CONF_DATA = 3 } prn_conf_t; static const char* filemap[] = { "PortDosName", "PnPName", "DriverName", "CachedPrinterConfigData" }; static char* get_printer_config_path(const rdpSettings* settings, const WCHAR* name, size_t length) { char* dir = GetCombinedPath(settings->ConfigPath, "printers"); char* bname = crypto_base64_encode((const BYTE*)name, (int)length); char* config = GetCombinedPath(dir, bname); if (config && !PathFileExistsA(config)) { if (!PathMakePathA(config, NULL)) { free(config); config = NULL; } } free(dir); free(bname); return config; } static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* data, size_t length) { DWORD written = 0; BOOL rc = FALSE; HANDLE file; size_t b64len; char* base64 = NULL; const char* name = filemap[type]; char* abs = GetCombinedPath(path, name); if (!abs) return FALSE; file = CreateFileA(abs, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); free(abs); if (file == INVALID_HANDLE_VALUE) return FALSE; if (length > 0) { base64 = crypto_base64_encode(data, length); if (!base64) goto fail; /* base64 char represents 6bit -> 4*(n/3) is the length which is * always smaller than 2*n */ b64len = strnlen(base64, 2 * length); rc = WriteFile(file, base64, b64len, &written, NULL); if (b64len != written) rc = FALSE; } else rc = TRUE; fail: CloseHandle(file); free(base64); return rc; } static BOOL printer_config_valid(const char* path) { if (!path) return FALSE; if (!PathFileExistsA(path)) return FALSE; return TRUE; } static BOOL printer_read_setting(const char* path, prn_conf_t type, void** data, UINT32* length) { DWORD lowSize, highSize; DWORD read = 0; BOOL rc = FALSE; HANDLE file; char* fdata = NULL; const char* name = filemap[type]; char* abs = GetCombinedPath(path, name); if (!abs) return FALSE; file = CreateFileA(abs, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); free(abs); if (file == INVALID_HANDLE_VALUE) return FALSE; lowSize = GetFileSize(file, &highSize); if ((lowSize == INVALID_FILE_SIZE) || (highSize != 0)) goto fail; if (lowSize != 0) { fdata = malloc(lowSize); if (!fdata) goto fail; rc = ReadFile(file, fdata, lowSize, &read, NULL); if (lowSize != read) rc = FALSE; } fail: CloseHandle(file); if (rc && (lowSize <= INT_MAX)) { int blen = 0; crypto_base64_decode(fdata, (int)lowSize, (BYTE**)data, &blen); if (*data && (blen > 0)) *length = (UINT32)blen; else { rc = FALSE; *length = 0; } } else { *length = 0; *data = NULL; } free(fdata); return rc; } static BOOL printer_save_to_config(const rdpSettings* settings, const char* PortDosName, size_t PortDosNameLen, const WCHAR* PnPName, size_t PnPNameLen, const WCHAR* DriverName, size_t DriverNameLen, const WCHAR* PrinterName, size_t PrintNameLen, const BYTE* CachedPrinterConfigData, size_t CacheFieldsLen) { BOOL rc = FALSE; char* path = get_printer_config_path(settings, PrinterName, PrintNameLen); if (!path) goto fail; if (!printer_write_setting(path, PRN_CONF_PORT, PortDosName, PortDosNameLen)) goto fail; if (!printer_write_setting(path, PRN_CONF_PNP, PnPName, PnPNameLen)) goto fail; if (!printer_write_setting(path, PRN_CONF_DRIVER, DriverName, DriverNameLen)) goto fail; if (!printer_write_setting(path, PRN_CONF_DATA, CachedPrinterConfigData, CacheFieldsLen)) goto fail; fail: free(path); return rc; } static BOOL printer_update_to_config(const rdpSettings* settings, const WCHAR* name, size_t length, const BYTE* data, size_t datalen) { BOOL rc = FALSE; char* path = get_printer_config_path(settings, name, length); rc = printer_write_setting(path, PRN_CONF_DATA, data, datalen); free(path); return rc; } static BOOL printer_remove_config(const rdpSettings* settings, const WCHAR* name, size_t length) { BOOL rc = FALSE; char* path = get_printer_config_path(settings, name, length); if (!printer_config_valid(path)) goto fail; rc = RemoveDirectoryA(path); fail: free(path); return rc; } static BOOL printer_move_config(const rdpSettings* settings, const WCHAR* oldName, size_t oldLength, const WCHAR* newName, size_t newLength) { BOOL rc = FALSE; char* oldPath = get_printer_config_path(settings, oldName, oldLength); char* newPath = get_printer_config_path(settings, newName, newLength); if (printer_config_valid(oldPath)) rc = MoveFileA(oldPath, newPath); free(oldPath); free(newPath); return rc; } static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* printer, PRINTER_DEVICE* printer_dev) { BOOL res = FALSE; WCHAR* wname = NULL; size_t wlen; char* path = NULL; int rc; UINT32 flags = 0; void* DriverName = NULL; UINT32 DriverNameLen = 0; void* PnPName = NULL; UINT32 PnPNameLen = 0; void* CachedPrinterConfigData = NULL; UINT32 CachedFieldsLen = 0; UINT32 PrinterNameLen = 0; if (!settings || !printer) return FALSE; rc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0); if (rc <= 0) goto fail; wlen = _wcslen(wname) + 1; path = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR)); PrinterNameLen = (wlen + 1) * sizeof(WCHAR); if (!path) goto fail; if (printer->is_default) flags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER; if (!printer_read_setting(path, PRN_CONF_PNP, &PnPName, &PnPNameLen)) { } if (!printer_read_setting(path, PRN_CONF_DRIVER, &DriverName, &DriverNameLen)) { DriverNameLen = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, (LPWSTR*)&DriverName, 0) * 2 + 1; } if (!printer_read_setting(path, PRN_CONF_DATA, &CachedPrinterConfigData, &CachedFieldsLen)) { } Stream_SetPosition(printer_dev->device.data, 0); if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, 24)) goto fail; Stream_Write_UINT32(printer_dev->device.data, flags); Stream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */ Stream_Write_UINT32(printer_dev->device.data, PnPNameLen); /* PnPNameLen */ Stream_Write_UINT32(printer_dev->device.data, DriverNameLen); Stream_Write_UINT32(printer_dev->device.data, PrinterNameLen); Stream_Write_UINT32(printer_dev->device.data, CachedFieldsLen); if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PnPNameLen)) goto fail; if (PnPNameLen > 0) Stream_Write(printer_dev->device.data, PnPName, PnPNameLen); if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, DriverNameLen)) goto fail; Stream_Write(printer_dev->device.data, DriverName, DriverNameLen); if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PrinterNameLen)) goto fail; Stream_Write(printer_dev->device.data, wname, PrinterNameLen); if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, CachedFieldsLen)) goto fail; Stream_Write(printer_dev->device.data, CachedPrinterConfigData, CachedFieldsLen); res = TRUE; fail: free(path); free(wname); free(PnPName); free(DriverName); free(CachedPrinterConfigData); return res; } static BOOL printer_save_default_config(const rdpSettings* settings, rdpPrinter* printer) { BOOL res = FALSE; WCHAR* wname = NULL; WCHAR* driver = NULL; size_t wlen, dlen; char* path = NULL; int rc; if (!settings || !printer) return FALSE; rc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0); if (rc <= 0) goto fail; rc = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &driver, 0); if (rc <= 0) goto fail; wlen = _wcslen(wname) + 1; dlen = _wcslen(driver) + 1; path = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR)); if (!path) goto fail; if (dlen > 1) { if (!printer_write_setting(path, PRN_CONF_DRIVER, driver, dlen * sizeof(WCHAR))) goto fail; } res = TRUE; fail: free(path); free(wname); free(driver); return res; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_create(PRINTER_DEVICE* printer_dev, IRP* irp) { rdpPrintJob* printjob = NULL; if (printer_dev->printer) printjob = printer_dev->printer->CreatePrintJob(printer_dev->printer, irp->devman->id_sequence++); if (printjob) { Stream_Write_UINT32(irp->output, printjob->id); /* FileId */ } else { Stream_Write_UINT32(irp->output, 0); /* FileId */ irp->IoStatus = STATUS_PRINT_QUEUE_FULL; } return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_close(PRINTER_DEVICE* printer_dev, IRP* irp) { rdpPrintJob* printjob = NULL; if (printer_dev->printer) printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId); if (!printjob) { irp->IoStatus = STATUS_UNSUCCESSFUL; } else { printjob->Close(printjob); } Stream_Zero(irp->output, 4); /* Padding(4) */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp) { UINT32 Length; UINT64 Offset; rdpPrintJob* printjob = NULL; UINT error = CHANNEL_RC_OK; void* ptr; if (Stream_GetRemainingLength(irp->input) < 32) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); Stream_Seek(irp->input, 20); /* Padding */ ptr = Stream_Pointer(irp->input); if (!Stream_SafeSeek(irp->input, Length)) return ERROR_INVALID_DATA; if (printer_dev->printer) printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId); if (!printjob) { irp->IoStatus = STATUS_UNSUCCESSFUL; Length = 0; } else { error = printjob->Write(printjob, ptr, Length); } if (error) { WLog_ERR(TAG, "printjob->Write failed with error %" PRIu32 "!", error); return error; } Stream_Write_UINT32(irp->output, Length); Stream_Write_UINT8(irp->output, 0); /* Padding */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_device_control(PRINTER_DEVICE* printer_dev, IRP* irp) { Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp(PRINTER_DEVICE* printer_dev, IRP* irp) { UINT error; switch (irp->MajorFunction) { case IRP_MJ_CREATE: if ((error = printer_process_irp_create(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_create failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_CLOSE: if ((error = printer_process_irp_close(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_close failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_WRITE: if ((error = printer_process_irp_write(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_write failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_DEVICE_CONTROL: if ((error = printer_process_irp_device_control(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_device_control failed with error %" PRIu32 "!", error); return error; } break; default: irp->IoStatus = STATUS_NOT_SUPPORTED; return irp->Complete(irp); break; } return CHANNEL_RC_OK; } static DWORD WINAPI printer_thread_func(LPVOID arg) { IRP* irp; PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)arg; HANDLE obj[] = { printer_dev->event, printer_dev->stopEvent }; UINT error = CHANNEL_RC_OK; while (1) { DWORD rc = WaitForMultipleObjects(2, obj, FALSE, INFINITE); if (rc == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "!", error); break; } if (rc == WAIT_OBJECT_0 + 1) break; else if (rc != WAIT_OBJECT_0) continue; ResetEvent(printer_dev->event); irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList); if (irp == NULL) { WLog_ERR(TAG, "InterlockedPopEntrySList failed!"); error = ERROR_INTERNAL_ERROR; break; } if ((error = printer_process_irp(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp failed with error %" PRIu32 "!", error); break; } } if (error && printer_dev->rdpcontext) setChannelError(printer_dev->rdpcontext, error, "printer_thread_func reported an error"); ExitThread(error); return error; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_irp_request(DEVICE* device, IRP* irp) { PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device; InterlockedPushEntrySList(printer_dev->pIrpList, &(irp->ItemEntry)); SetEvent(printer_dev->event); return CHANNEL_RC_OK; } static UINT printer_custom_component(DEVICE* device, UINT16 component, UINT16 packetId, wStream* s) { UINT32 eventID; PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device; const rdpSettings* settings = printer_dev->rdpcontext->settings; if (component != RDPDR_CTYP_PRN) return ERROR_INVALID_DATA; if (Stream_GetRemainingLength(s) < 4) return ERROR_INVALID_DATA; Stream_Read_UINT32(s, eventID); switch (packetId) { case PAKID_PRN_CACHE_DATA: switch (eventID) { case RDPDR_ADD_PRINTER_EVENT: { char PortDosName[8]; UINT32 PnPNameLen, DriverNameLen, PrintNameLen, CacheFieldsLen; const WCHAR *PnPName, *DriverName, *PrinterName; const BYTE* CachedPrinterConfigData; if (Stream_GetRemainingLength(s) < 24) return ERROR_INVALID_DATA; Stream_Read(s, PortDosName, sizeof(PortDosName)); Stream_Read_UINT32(s, PnPNameLen); Stream_Read_UINT32(s, DriverNameLen); Stream_Read_UINT32(s, PrintNameLen); Stream_Read_UINT32(s, CacheFieldsLen); if (Stream_GetRemainingLength(s) < PnPNameLen) return ERROR_INVALID_DATA; PnPName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, PnPNameLen); if (Stream_GetRemainingLength(s) < DriverNameLen) return ERROR_INVALID_DATA; DriverName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, DriverNameLen); if (Stream_GetRemainingLength(s) < PrintNameLen) return ERROR_INVALID_DATA; PrinterName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, PrintNameLen); if (Stream_GetRemainingLength(s) < CacheFieldsLen) return ERROR_INVALID_DATA; CachedPrinterConfigData = Stream_Pointer(s); Stream_Seek(s, CacheFieldsLen); if (!printer_save_to_config(settings, PortDosName, sizeof(PortDosName), PnPName, PnPNameLen, DriverName, DriverNameLen, PrinterName, PrintNameLen, CachedPrinterConfigData, CacheFieldsLen)) return ERROR_INTERNAL_ERROR; } break; case RDPDR_UPDATE_PRINTER_EVENT: { UINT32 PrinterNameLen, ConfigDataLen; const WCHAR* PrinterName; const BYTE* ConfigData; if (Stream_GetRemainingLength(s) < 8) return ERROR_INVALID_DATA; Stream_Read_UINT32(s, PrinterNameLen); Stream_Read_UINT32(s, ConfigDataLen); if (Stream_GetRemainingLength(s) < PrinterNameLen) return ERROR_INVALID_DATA; PrinterName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, PrinterNameLen); if (Stream_GetRemainingLength(s) < ConfigDataLen) return ERROR_INVALID_DATA; ConfigData = Stream_Pointer(s); Stream_Seek(s, ConfigDataLen); if (!printer_update_to_config(settings, PrinterName, PrinterNameLen, ConfigData, ConfigDataLen)) return ERROR_INTERNAL_ERROR; } break; case RDPDR_DELETE_PRINTER_EVENT: { UINT32 PrinterNameLen; const WCHAR* PrinterName; if (Stream_GetRemainingLength(s) < 4) return ERROR_INVALID_DATA; Stream_Read_UINT32(s, PrinterNameLen); if (Stream_GetRemainingLength(s) < PrinterNameLen) return ERROR_INVALID_DATA; PrinterName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, PrinterNameLen); printer_remove_config(settings, PrinterName, PrinterNameLen); } break; case RDPDR_RENAME_PRINTER_EVENT: { UINT32 OldPrinterNameLen, NewPrinterNameLen; const WCHAR* OldPrinterName; const WCHAR* NewPrinterName; if (Stream_GetRemainingLength(s) < 8) return ERROR_INVALID_DATA; Stream_Read_UINT32(s, OldPrinterNameLen); Stream_Read_UINT32(s, NewPrinterNameLen); if (Stream_GetRemainingLength(s) < OldPrinterNameLen) return ERROR_INVALID_DATA; OldPrinterName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, OldPrinterNameLen); if (Stream_GetRemainingLength(s) < NewPrinterNameLen) return ERROR_INVALID_DATA; NewPrinterName = (const WCHAR*)Stream_Pointer(s); Stream_Seek(s, NewPrinterNameLen); if (!printer_move_config(settings, OldPrinterName, OldPrinterNameLen, NewPrinterName, NewPrinterNameLen)) return ERROR_INTERNAL_ERROR; } break; default: WLog_ERR(TAG, "Unknown cache data eventID: 0x%08" PRIX32 "", eventID); return ERROR_INVALID_DATA; } break; case PAKID_PRN_USING_XPS: { UINT32 flags; if (Stream_GetRemainingLength(s) < 4) return ERROR_INVALID_DATA; Stream_Read_UINT32(s, flags); WLog_ERR(TAG, "Ignoring unhandled message PAKID_PRN_USING_XPS [printerID=%08" PRIx32 ", flags=%08" PRIx32 "]", eventID, flags); } break; default: WLog_ERR(TAG, "Unknown printing component packetID: 0x%04" PRIX16 "", packetId); return ERROR_INVALID_DATA; } return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_free(DEVICE* device) { IRP* irp; PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device; UINT error; SetEvent(printer_dev->stopEvent); if (WaitForSingleObject(printer_dev->thread, INFINITE) == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error); /* The analyzer is confused by this premature return value. * Since this case can not be handled gracefully silence the * analyzer here. */ #ifndef __clang_analyzer__ return error; #endif } while ((irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList)) != NULL) irp->Discard(irp); CloseHandle(printer_dev->thread); CloseHandle(printer_dev->stopEvent); CloseHandle(printer_dev->event); _aligned_free(printer_dev->pIrpList); if (printer_dev->printer) printer_dev->printer->ReleaseRef(printer_dev->printer); Stream_Free(printer_dev->device.data, TRUE); free(printer_dev); return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinter* printer) { PRINTER_DEVICE* printer_dev; UINT error = ERROR_INTERNAL_ERROR; printer_dev = (PRINTER_DEVICE*)calloc(1, sizeof(PRINTER_DEVICE)); if (!printer_dev) { WLog_ERR(TAG, "calloc failed!"); return CHANNEL_RC_NO_MEMORY; } printer_dev->device.data = Stream_New(NULL, 1024); if (!printer_dev->device.data) goto error_out; sprintf_s(printer_dev->port, sizeof(printer_dev->port), "PRN%" PRIdz, printer->id); printer_dev->device.type = RDPDR_DTYP_PRINT; printer_dev->device.name = printer_dev->port; printer_dev->device.IRPRequest = printer_irp_request; printer_dev->device.CustomComponentRequest = printer_custom_component; printer_dev->device.Free = printer_free; printer_dev->rdpcontext = pEntryPoints->rdpcontext; printer_dev->printer = printer; printer_dev->pIrpList = (WINPR_PSLIST_HEADER)_aligned_malloc(sizeof(WINPR_SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT); if (!printer_dev->pIrpList) { WLog_ERR(TAG, "_aligned_malloc failed!"); error = CHANNEL_RC_NO_MEMORY; goto error_out; } if (!printer_load_from_config(pEntryPoints->rdpcontext->settings, printer, printer_dev)) goto error_out; InitializeSListHead(printer_dev->pIrpList); if (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL))) { WLog_ERR(TAG, "CreateEvent failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } if (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { WLog_ERR(TAG, "CreateEvent failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)printer_dev))) { WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error); goto error_out; } if (!(printer_dev->thread = CreateThread(NULL, 0, printer_thread_func, (void*)printer_dev, 0, NULL))) { WLog_ERR(TAG, "CreateThread failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } printer->AddRef(printer); return CHANNEL_RC_OK; error_out: printer_free(&printer_dev->device); return error; } static rdpPrinterDriver* printer_load_backend(const char* backend) { typedef rdpPrinterDriver* (*backend_load_t)(void); union { PVIRTUALCHANNELENTRY entry; backend_load_t backend; } fktconv; fktconv.entry = freerdp_load_channel_addin_entry("printer", backend, NULL, 0); if (!fktconv.entry) return NULL; return fktconv.backend(); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ UINT #ifdef BUILTIN_CHANNELS printer_DeviceServiceEntry #else FREERDP_API DeviceServiceEntry #endif (PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints) { int i; char* name; char* driver_name; BOOL default_backend = TRUE; RDPDR_PRINTER* device = NULL; rdpPrinterDriver* driver = NULL; UINT error = CHANNEL_RC_OK; if (!pEntryPoints || !pEntryPoints->device) return ERROR_INVALID_PARAMETER; device = (RDPDR_PRINTER*)pEntryPoints->device; name = device->Name; driver_name = device->DriverName; /* Secondary argument is one of the following: * * <driver_name> ... name of a printer driver * <driver_name>:<backend_name> ... name of a printer driver and local printer backend to use */ if (driver_name) { char* sep = strstr(driver_name, ":"); if (sep) { const char* backend = sep + 1; *sep = '\0'; driver = printer_load_backend(backend); default_backend = FALSE; } } if (!driver && default_backend) { const char* backend = #if defined(WITH_CUPS) "cups" #elif defined(_WIN32) "win" #else "" #endif ; driver = printer_load_backend(backend); } if (!driver) { WLog_ERR(TAG, "Could not get a printer driver!"); return CHANNEL_RC_INITIALIZATION_ERROR; } if (name && name[0]) { rdpPrinter* printer = driver->GetPrinter(driver, name, driver_name); if (!printer) { WLog_ERR(TAG, "Could not get printer %s!", name); error = CHANNEL_RC_INITIALIZATION_ERROR; goto fail; } if (!printer_save_default_config(pEntryPoints->rdpcontext->settings, printer)) { error = CHANNEL_RC_INITIALIZATION_ERROR; printer->ReleaseRef(printer); goto fail; } if ((error = printer_register(pEntryPoints, printer))) { WLog_ERR(TAG, "printer_register failed with error %" PRIu32 "!", error); printer->ReleaseRef(printer); goto fail; } } else { rdpPrinter** printers = driver->EnumPrinters(driver); rdpPrinter** current = printers; for (i = 0; current[i]; i++) { rdpPrinter* printer = current[i]; if ((error = printer_register(pEntryPoints, printer))) { WLog_ERR(TAG, "printer_register failed with error %" PRIu32 "!", error); break; } } driver->ReleaseEnumPrinters(printers); } fail: driver->ReleaseRef(driver); return error; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3946_1
crossvul-cpp_data_good_5302_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M EEEEE TTTTT AAA % % MM MM E T A A % % M M M EEE T AAAAA % % M M E T A A % % M M EEEEE T A A % % % % % % Read/Write Embedded Image Profiles. % % % % Software Design % % William Radcliffe % % July 2001 % % % % % % 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/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/channel.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/profile.h" #include "MagickCore/splay-tree.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" /* Forward declarations. */ static MagickBooleanType WriteMETAImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M E T A % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMETA() returns MagickTrue if the image format type, identified by the % magick string, is META. % % The format of the IsMETA method is: % % MagickBooleanType IsMETA(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. % % */ #ifdef IMPLEMENT_IS_FUNCTION static MagickBooleanType IsMETA(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"8BIM",4) == 0) return(MagickTrue); if (LocaleNCompare((char *) magick,"APP1",4) == 0) return(MagickTrue); if (LocaleNCompare((char *) magick,"\034\002",2) == 0) return(MagickTrue); return(MagickFalse); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMETAImage() reads a META 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 ReadMETAImage method is: % % Image *ReadMETAImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image: Method ReadMETAImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or % if the image cannot be read. % % o image_info: Specifies a pointer to an ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ typedef struct _html_code { const short len; const char *code, val; } html_code; static const html_code html_codes[] = { #ifdef HANDLE_GT_LT { 4,"&lt;",'<' }, { 4,"&gt;",'>' }, #endif { 5,"&amp;",'&' }, { 6,"&quot;",'"' }, { 6,"&apos;",'\''} }; static int stringnicmp(const char *p,const char *q,size_t n) { register ssize_t i, j; if (p == q) return(0); if (p == (char *) NULL) return(-1); if (q == (char *) NULL) return(1); while ((*p != '\0') && (*q != '\0')) { if ((*p == '\0') || (*q == '\0')) break; i=(*p); if (islower(i)) i=toupper(i); j=(*q); if (islower(j)) j=toupper(j); if (i != j) break; n--; if (n == 0) break; p++; q++; } return(toupper((int) *p)-toupper((int) *q)); } static int convertHTMLcodes(char *s, int len) { if (len <=0 || s==(char*) NULL || *s=='\0') return 0; if (s[1] == '#') { int val, o; if (sscanf(s,"&#%d;",&val) == 1) { o = 3; while (s[o] != ';') { o++; if (o > 5) break; } if (o < 6) (void) memmove(s+1,s+1+o,strlen(s+1+o)+1); *s = val; return o; } } else { int i, codes = (int) (sizeof(html_codes) / sizeof(html_code)); for (i=0; i < codes; i++) { if (html_codes[i].len <= len) if (stringnicmp(s,html_codes[i].code,(size_t) html_codes[i].len) == 0) { (void) memmove(s+1,s+html_codes[i].len, strlen(s+html_codes[i].len)+1); *s=html_codes[i].val; return html_codes[i].len-1; } } } return 0; } static char *super_fgets(char **b, int *blen, Image *file) { int c, len; unsigned char *p, *q; len=*blen; p=(unsigned char *) (*b); for (q=p; ; q++) { c=ReadBlobByte(file); if (c == EOF || c == '\n') break; if ((q-p+1) >= (int) len) { int tlen; tlen=q-p; len<<=1; p=(unsigned char *) ResizeQuantumMemory(p,(size_t) len+2UL,sizeof(*p)); *b=(char *) p; if (p == (unsigned char *) NULL) break; q=p+tlen; } *q=(unsigned char) c; } *blen=0; if (p != (unsigned char *) NULL) { int tlen; tlen=q-p; if (tlen == 0) return (char *) NULL; p[tlen] = '\0'; *blen=++tlen; } return((char *) p); } #define IPTC_ID 1028 #define THUMBNAIL_ID 1033 static ssize_t parse8BIM(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MagickPathExtent; MagickOffsetType savedpos, currentpos; ssize_t savedolen = 0L, outputlen = 0L; TokenInfo *token_info; dataset = 0; recnum = 0; line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets(&line,&inputlen,ifile)!=NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0, &brkused,&next,&quoted)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#", "", 0,&brkused,&next,&quoted)==0) { switch (state) { case 0: if (strcmp(newstr,"8BIM")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum = (unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent, sizeof(*name)); if (name) (void) strcpy(name,newstr); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&", "",0,&brkused,&next,&quoted)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,"8BIM"); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,nlen); outputlen++; for (i=0; i<nlen; i++) (void) WriteBlobByte(ofile,(unsigned char) name[i]); outputlen += nlen; if ((nlen & 0x01) == 0) { (void) WriteBlobByte(ofile,0x00); outputlen++; } if (recnum != IPTC_ID) { (void) WriteBlobMSBLong(ofile, (unsigned int) len); outputlen += 4; next=0; outputlen += len; while (len-- > 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,(unsigned char) dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len-- > 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return outputlen; } static char *super_fgets_w(char **b, int *blen, Image *file) { int c, len; unsigned char *p, *q; len=*blen; p=(unsigned char *) (*b); for (q=p; ; q++) { c=(int) ReadBlobLSBShort(file); if ((c == -1) || (c == '\n')) break; if (EOFBlob(file)) break; if ((q-p+1) >= (int) len) { int tlen; tlen=q-p; len<<=1; p=(unsigned char *) ResizeQuantumMemory(p,(size_t) (len+2),sizeof(*p)); *b=(char *) p; if (p == (unsigned char *) NULL) break; q=p+tlen; } *q=(unsigned char) c; } *blen=0; if ((*b) != (char *) NULL) { int tlen; tlen=q-p; if (tlen == 0) return (char *) NULL; p[tlen] = '\0'; *blen=++tlen; } return((char *) p); } static ssize_t parse8BIMW(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MagickPathExtent; ssize_t savedolen = 0L, outputlen = 0L; MagickOffsetType savedpos, currentpos; TokenInfo *token_info; dataset = 0; recnum = 0; line=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets_w(&line,&inputlen,ifile) != NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0, &brkused,&next,&quoted)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#", "",0,&brkused,&next,&quoted)==0) { switch (state) { case 0: if (strcmp(newstr,"8BIM")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum=(unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent, sizeof(*name)); if (name) (void) CopyMagickString(name,newstr,strlen(newstr)+MagickPathExtent); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&", "",0,&brkused,&next,&quoted)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,"8BIM"); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,(unsigned char) nlen); outputlen++; for (i=0; i<nlen; i++) (void) WriteBlobByte(ofile,(unsigned char) name[i]); outputlen += nlen; if ((nlen & 0x01) == 0) { (void) WriteBlobByte(ofile,0x00); outputlen++; } if (recnum != IPTC_ID) { (void) WriteBlobMSBLong(ofile,(unsigned int) len); outputlen += 4; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return(outputlen); } /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef static int jpeg_transfer_1(Image *ifile, Image *ofile) { int c; c = ReadBlobByte(ifile); if (c == EOF) return EOF; (void) WriteBlobByte(ofile,(unsigned char) c); return c; } #if defined(future) static int jpeg_skip_1(Image *ifile) { int c; c = ReadBlobByte(ifile); if (c == EOF) return EOF; return c; } #endif static int jpeg_read_remaining(Image *ifile, Image *ofile) { int c; while ((c = jpeg_transfer_1(ifile, ofile)) != EOF) continue; return M_EOI; } static int jpeg_skip_variable(Image *ifile, Image *ofile) { unsigned int length; int c1,c2; if ((c1 = jpeg_transfer_1(ifile, ofile)) == EOF) return M_EOI; if ((c2 = jpeg_transfer_1(ifile, ofile)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) if (jpeg_transfer_1(ifile, ofile) == EOF) return M_EOI; return 0; } static int jpeg_skip_variable2(Image *ifile, Image *ofile) { unsigned int length; int c1,c2; (void) ofile; if ((c1 = ReadBlobByte(ifile)) == EOF) return M_EOI; if ((c2 = ReadBlobByte(ifile)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) if (ReadBlobByte(ifile) == EOF) return M_EOI; return 0; } static int jpeg_nextmarker(Image *ifile, Image *ofile) { int c; /* transfer anything until we hit 0xff */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c != 0xff) (void) WriteBlobByte(ofile,(unsigned char) c); } while (c != 0xff); /* get marker byte, swallowing possible padding */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ } while (c == 0xff); return c; } #if defined(future) static int jpeg_skip_till_marker(Image *ifile, int marker) { int c, i; do { /* skip anything until we hit 0xff */ i = 0; do { c = ReadBlobByte(ifile); i++; if (c == EOF) return M_EOI; /* we hit EOF */ } while (c != 0xff); /* get marker byte, swallowing possible padding */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ } while (c == 0xff); } while (c != marker); return c; } #endif /* Embed binary IPTC data into a JPEG image. */ static int jpeg_embed(Image *ifile, Image *ofile, Image *iptc) { unsigned int marker; unsigned int done = 0; unsigned int len; int inx; if (jpeg_transfer_1(ifile, ofile) != 0xFF) return 0; if (jpeg_transfer_1(ifile, ofile) != M_SOI) return 0; while (done == MagickFalse) { marker=(unsigned int) jpeg_nextmarker(ifile, ofile); if (marker == M_EOI) { /* EOF */ break; } else { if (marker != M_APP13) { (void) WriteBlobByte(ofile,0xff); (void) WriteBlobByte(ofile,(unsigned char) marker); } } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ jpeg_skip_variable2(ifile, ofile); break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ jpeg_skip_variable(ifile, ofile); if (iptc != (Image *) NULL) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\0" "8BIM\x04\x04\0\0\0\0"; len=(unsigned int) GetBlobSize(iptc); if (len & 1) len++; /* make the length even */ psheader[2]=(char) ((len+16)>>8); psheader[3]=(char) ((len+16)&0xff); for (inx = 0; inx < 18; inx++) (void) WriteBlobByte(ofile,(unsigned char) psheader[inx]); jpeg_read_remaining(iptc, ofile); len=(unsigned int) GetBlobSize(iptc); if (len & 1) (void) WriteBlobByte(ofile,0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ jpeg_read_remaining(ifile, ofile); done = 1; break; default: jpeg_skip_variable(ifile, ofile); break; } } return 1; } /* handle stripping the APP13 data out of a JPEG */ #if defined(future) static void jpeg_strip(Image *ifile, Image *ofile) { unsigned int marker; marker = jpeg_skip_till_marker(ifile, M_SOI); if (marker == M_SOI) { (void) WriteBlobByte(ofile,0xff); (void) WriteBlobByte(ofile,M_SOI); jpeg_read_remaining(ifile, ofile); } } /* Extract any APP13 binary data into a file. */ static int jpeg_extract(Image *ifile, Image *ofile) { unsigned int marker; unsigned int done = 0; if (jpeg_skip_1(ifile) != 0xff) return 0; if (jpeg_skip_1(ifile) != M_SOI) return 0; while (done == MagickFalse) { marker = jpeg_skip_till_marker(ifile, M_APP13); if (marker == M_APP13) { marker = jpeg_nextmarker(ifile, ofile); break; } } return 1; } #endif static inline void CopyBlob(Image *source,Image *destination) { ssize_t i; unsigned char *buffer; ssize_t count, length; buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent, sizeof(*buffer)); if (buffer != (unsigned char *) NULL) { i=0; while ((length=ReadBlob(source,MagickMaxBufferExtent,buffer)) != 0) { count=0; for (i=0; i < (ssize_t) length; i+=count) { count=WriteBlob(destination,(size_t) (length-i),buffer+i); if (count <= 0) break; } if (i < (ssize_t) length) break; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); } } static Image *ReadMETAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *buff, *image; MagickBooleanType status; StringInfo *profile; size_t length; void *blob; /* Open file containing binary metadata */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=1; image->rows=1; if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } length=1; if (LocaleNCompare(image_info->magick,"8BIM",4) == 0) { /* Read 8BIM binary metadata. */ buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0) { length=(size_t) parse8BIM(image, buff); if (length & 1) (void) WriteBlobByte(buff,0x0); } else if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0) { length=(size_t) parse8BIMW(image, buff); if (length & 1) (void) WriteBlobByte(buff,0x0); } else CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleNCompare(image_info->magick,"APP1",4) == 0) { char name[MagickPathExtent]; (void) FormatLocaleString(name,MagickPathExtent,"APP%d",1); buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); if (LocaleCompare(image_info->magick,"APP1JPEG") == 0) { Image *iptc; int result; if (image_info->profile == (void *) NULL) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(CoderError,"NoIPTCProfileAvailable"); } profile=CloneStringInfo((StringInfo *) image_info->profile); iptc=AcquireImage((ImageInfo *) NULL,exception); if (iptc == (Image *) NULL) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(iptc->blob,GetStringInfoDatum(profile), GetStringInfoLength(profile)); result=jpeg_embed(image,buff,iptc); blob=DetachBlob(iptc->blob); blob=RelinquishMagickMemory(blob); iptc=DestroyImage(iptc); if (result == 0) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(CoderError,"JPEGEmbeddingFailed"); } } else CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if ((LocaleCompare(image_info->magick,"ICC") == 0) || (LocaleCompare(image_info->magick,"ICM") == 0)) { buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleCompare(image_info->magick,"IPTC") == 0) { buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleCompare(image_info->magick,"XMP") == 0) { buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"xmp",profile,exception); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMETAImage() adds attributes for the META image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMETAImage method is: % % size_t RegisterMETAImage(void) % */ ModuleExport size_t RegisterMETAImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("META","8BIM","Photoshop resource format"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","8BIMTEXT","Photoshop resource text format"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","8BIMWTEXT", "Photoshop resource wide text format"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","APP1","Raw application information"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","APP1JPEG","Raw JPEG binary data"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","EXIF","Exif digital camera binary data"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","XMP","Adobe XML metadata"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","ICM","ICC Color Profile"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","ICC","ICC Color Profile"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","IPTC","IPTC Newsphoto"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","IPTCTEXT","IPTC Newsphoto text format"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("META","IPTCWTEXT","IPTC Newsphoto text format"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderStealthFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMETAImage() removes format registrations made by the % META module from the list of supported formats. % % The format of the UnregisterMETAImage method is: % % UnregisterMETAImage(void) % */ ModuleExport void UnregisterMETAImage(void) { (void) UnregisterMagickInfo("8BIM"); (void) UnregisterMagickInfo("8BIMTEXT"); (void) UnregisterMagickInfo("8BIMWTEXT"); (void) UnregisterMagickInfo("EXIF"); (void) UnregisterMagickInfo("APP1"); (void) UnregisterMagickInfo("APP1JPEG"); (void) UnregisterMagickInfo("ICCTEXT"); (void) UnregisterMagickInfo("ICM"); (void) UnregisterMagickInfo("ICC"); (void) UnregisterMagickInfo("IPTC"); (void) UnregisterMagickInfo("IPTCTEXT"); (void) UnregisterMagickInfo("IPTCWTEXT"); (void) UnregisterMagickInfo("XMP"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMETAImage() writes a META image to a file. % % The format of the WriteMETAImage method is: % % MagickBooleanType WriteMETAImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % Compression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: Specifies a pointer to an ImageInfo structure. % % o image: A pointer to a Image structure. % % o exception: return any errors or warnings in this structure. % */ static size_t GetIPTCStream(unsigned char **info,size_t length) { int c; register ssize_t i; register unsigned char *p; size_t extent, info_length; unsigned int marker; size_t tag_length; p=(*info); extent=length; if ((*p == 0x1c) && (*(p+1) == 0x02)) return(length); /* Extract IPTC from 8BIM resource block. */ while (extent >= 12) { if (strncmp((const char *) p,"8BIM",4)) break; p+=4; extent-=4; marker=(unsigned int) (*p) << 8 | *(p+1); p+=2; extent-=2; c=*p++; extent--; c|=0x01; if ((size_t) c >= extent) break; p+=c; extent-=c; if (extent < 4) break; tag_length=(((size_t) *p) << 24) | (((size_t) *(p+1)) << 16) | (((size_t) *(p+2)) << 8) | ((size_t) *(p+3)); p+=4; extent-=4; if (tag_length > extent) break; if (marker == IPTC_ID) { *info=p; return(tag_length); } if ((tag_length & 0x01) != 0) tag_length++; p+=tag_length; extent-=tag_length; } /* Find the beginning of the IPTC info. */ p=(*info); tag_length=0; iptc_find: info_length=0; marker=MagickFalse; while (length != 0) { c=(*p++); length--; if (length == 0) break; if (c == 0x1c) { p--; *info=p; /* let the caller know were it is */ break; } } /* Determine the length of the IPTC info. */ while (length != 0) { c=(*p++); length--; if (length == 0) break; if (c == 0x1c) marker=MagickTrue; else if (marker) break; else continue; info_length++; /* Found the 0x1c tag; skip the dataset and record number tags. */ c=(*p++); /* should be 2 */ length--; if (length == 0) break; if ((info_length == 1) && (c != 2)) goto iptc_find; info_length++; c=(*p++); /* should be 0 */ length--; if (length == 0) break; if ((info_length == 2) && (c != 0)) goto iptc_find; info_length++; /* Decode the length of the block that follows - ssize_t or short format. */ c=(*p++); length--; if (length == 0) break; info_length++; if ((c & 0x80) != 0) { /* Long format. */ tag_length=0; for (i=0; i < 4; i++) { tag_length<<=8; tag_length|=(*p++); length--; if (length == 0) break; info_length++; } } else { /* Short format. */ tag_length=((long) c) << 8; c=(*p++); length--; if (length == 0) break; info_length++; tag_length|=(long) c; } if (tag_length > (length+1)) break; p+=tag_length; length-=tag_length; if (length == 0) break; info_length+=tag_length; } return(info_length); } static void formatString(Image *ofile, const char *s, int len) { char temp[MagickPathExtent]; (void) WriteBlobByte(ofile,'"'); for (; len > 0; len--, s++) { int c = (*s) & 255; switch (c) { case '&': (void) WriteBlobString(ofile,"&amp;"); break; #ifdef HANDLE_GT_LT case '<': (void) WriteBlobString(ofile,"&lt;"); break; case '>': (void) WriteBlobString(ofile,"&gt;"); break; #endif case '"': (void) WriteBlobString(ofile,"&quot;"); break; default: if (isprint(c)) (void) WriteBlobByte(ofile,(unsigned char) *s); else { (void) FormatLocaleString(temp,MagickPathExtent,"&#%d;", c & 255); (void) WriteBlobString(ofile,temp); } break; } } #if defined(MAGICKCORE_WINDOWS_SUPPORT) (void) WriteBlobString(ofile,"\"\r\n"); #else #if defined(macintosh) (void) WriteBlobString(ofile,"\"\r"); #else (void) WriteBlobString(ofile,"\"\n"); #endif #endif } typedef struct _tag_spec { const short id; const char *name; } tag_spec; static const tag_spec tags[] = { { 5, "Image Name" }, { 7, "Edit Status" }, { 10, "Priority" }, { 15, "Category" }, { 20, "Supplemental Category" }, { 22, "Fixture Identifier" }, { 25, "Keyword" }, { 30, "Release Date" }, { 35, "Release Time" }, { 40, "Special Instructions" }, { 45, "Reference Service" }, { 47, "Reference Date" }, { 50, "Reference Number" }, { 55, "Created Date" }, { 60, "Created Time" }, { 65, "Originating Program" }, { 70, "Program Version" }, { 75, "Object Cycle" }, { 80, "Byline" }, { 85, "Byline Title" }, { 90, "City" }, { 92, "Sub-Location" }, { 95, "Province State" }, { 100, "Country Code" }, { 101, "Country" }, { 103, "Original Transmission Reference" }, { 105, "Headline" }, { 110, "Credit" }, { 115, "Source" }, { 116, "Copyright String" }, { 120, "Caption" }, { 121, "Image Orientation" }, { 122, "Caption Writer" }, { 131, "Local Caption" }, { 200, "Custom Field 1" }, { 201, "Custom Field 2" }, { 202, "Custom Field 3" }, { 203, "Custom Field 4" }, { 204, "Custom Field 5" }, { 205, "Custom Field 6" }, { 206, "Custom Field 7" }, { 207, "Custom Field 8" }, { 208, "Custom Field 9" }, { 209, "Custom Field 10" }, { 210, "Custom Field 11" }, { 211, "Custom Field 12" }, { 212, "Custom Field 13" }, { 213, "Custom Field 14" }, { 214, "Custom Field 15" }, { 215, "Custom Field 16" }, { 216, "Custom Field 17" }, { 217, "Custom Field 18" }, { 218, "Custom Field 19" }, { 219, "Custom Field 20" } }; static int formatIPTC(Image *ifile, Image *ofile) { char temp[MagickPathExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ c = ReadBlobByte(ifile); while (c != EOF) { if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return(-1); else { c=0; continue; } } /* we found the 0x1c tag and now grab the dataset and record number tags */ c = ReadBlobByte(ifile); if (c == EOF) return -1; dataset = (unsigned char) c; c = ReadBlobByte(ifile); if (c == EOF) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) { if (tags[i].id == (short) recnum) break; } if (i < tagcount) readable = (unsigned char *) tags[i].name; else readable = (unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=ReadBlobByte(ifile); if (c == EOF) return -1; if (c & (unsigned char) 0x80) return 0; else { int c0; c0=ReadBlobByte(ifile); if (c0 == EOF) return -1; taglen = (c << 8) | c0; } if (taglen < 0) return -1; /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent), sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (tagindx=0; tagindx<taglen; tagindx++) { c=ReadBlobByte(ifile); if (c == EOF) return -1; str[tagindx] = (unsigned char) c; } str[taglen] = 0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=", (unsigned int) dataset, (unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; c=ReadBlobByte(ifile); } return((int) tagsfound); } static int readWordFromBuffer(char **s, ssize_t *len) { unsigned char buffer[2]; int i, c; for (i=0; i<2; i++) { c = *(*s)++; (*len)--; if (*len < 0) return -1; buffer[i] = (unsigned char) c; } return (((int) buffer[ 0 ]) << 8) | (((int) buffer[ 1 ])); } static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MagickPathExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent), sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (tagindx=0; tagindx<taglen; tagindx++) { c = *s++; len--; if (len < 0) return(-1); str[tagindx]=(unsigned char) c; } str[taglen]=0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); } static int format8BIM(Image *ifile, Image *ofile) { char temp[MagickPathExtent]; unsigned int foundOSType; int ID, resCount, i, c; ssize_t count; unsigned char *PString, *str; resCount=0; foundOSType=0; /* found the OSType */ (void) foundOSType; c=ReadBlobByte(ifile); while (c != EOF) { if (c == '8') { unsigned char buffer[5]; buffer[0]=(unsigned char) c; for (i=1; i<4; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); buffer[i] = (unsigned char) c; } buffer[4]=0; if (strcmp((const char *)buffer, "8BIM") == 0) foundOSType=1; else continue; } else { c=ReadBlobByte(ifile); continue; } /* We found the OSType (8BIM) and now grab the ID, PString, and Size fields. */ ID=(int) ReadBlobMSBShort(ifile); if (ID < 0) return(-1); { unsigned char plen; c=ReadBlobByte(ifile); if (c == EOF) return(-1); plen = (unsigned char) c; PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+ MagickPathExtent),sizeof(*PString)); if (PString == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (i=0; i<plen; i++) { c=ReadBlobByte(ifile); if (c == EOF) return -1; PString[i] = (unsigned char) c; } PString[ plen ] = 0; if ((plen & 0x01) == 0) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); } } count = (int) ReadBlobMSBLong(ifile); if (count < 0) return -1; /* make a buffer to hold the datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (i=0; i < (ssize_t) count; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); str[i]=(unsigned char) c; } /* we currently skip thumbnails, since it does not make * any sense preserving them in a real world application */ if (ID != THUMBNAIL_ID) { /* now finish up by formatting this binary data into * ASCII equivalent */ if (strlen((const char *)PString) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID, PString); else (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID); (void) WriteBlobString(ofile,temp); if (ID == IPTC_ID) { formatString(ofile, "IPTC", 4); formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count); } else formatString(ofile, (char *)str, (ssize_t) count); } str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); resCount++; c=ReadBlobByte(ifile); } return resCount; } static MagickBooleanType WriteMETAImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *profile; MagickBooleanType status; size_t length; /* Open 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); length=0; if (LocaleCompare(image_info->magick,"8BIM") == 0) { /* Write 8BIM image. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"iptc") == 0) { size_t length; unsigned char *info; profile=GetImageProfile(image,"iptc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); info=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); length=GetIPTCStream(&info,length); if (length == 0) ThrowWriterException(CoderError,"NoIPTCProfileAvailable"); (void) WriteBlob(image,length,info); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0) { Image *buff; profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); AttachBlob(buff->blob,GetStringInfoDatum(profile), GetStringInfoLength(profile)); format8BIM(buff,image); (void) DetachBlob(buff->blob); buff=DestroyImage(buff); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0) return(MagickFalse); if (LocaleCompare(image_info->magick,"IPTCTEXT") == 0) { Image *buff; unsigned char *info; profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); info=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); length=GetIPTCStream(&info,length); if (length == 0) ThrowWriterException(CoderError,"NoIPTCProfileAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); buff=AcquireImage((ImageInfo *) NULL,exception); if (buff == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); AttachBlob(buff->blob,info,length); formatIPTC(buff,image); (void) DetachBlob(buff->blob); buff=DestroyImage(buff); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"IPTCWTEXT") == 0) return(MagickFalse); if ((LocaleCompare(image_info->magick,"APP1") == 0) || (LocaleCompare(image_info->magick,"EXIF") == 0) || (LocaleCompare(image_info->magick,"XMP") == 0)) { /* (void) Write APP1 image. */ profile=GetImageProfile(image,image_info->magick); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"NoAPP1DataIsAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } if ((LocaleCompare(image_info->magick,"ICC") == 0) || (LocaleCompare(image_info->magick,"ICM") == 0)) { /* Write ICM image. */ profile=GetImageProfile(image,"icc"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"NoColorProfileIsAvailable"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } return(MagickFalse); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5302_0
crossvul-cpp_data_bad_2644_3
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Ethernet printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ethertype.h" #include "ether.h" const struct tok ethertype_values[] = { { ETHERTYPE_IP, "IPv4" }, { ETHERTYPE_MPLS, "MPLS unicast" }, { ETHERTYPE_MPLS_MULTI, "MPLS multicast" }, { ETHERTYPE_IPV6, "IPv6" }, { ETHERTYPE_8021Q, "802.1Q" }, { ETHERTYPE_8021Q9100, "802.1Q-9100" }, { ETHERTYPE_8021QinQ, "802.1Q-QinQ" }, { ETHERTYPE_8021Q9200, "802.1Q-9200" }, { ETHERTYPE_VMAN, "VMAN" }, { ETHERTYPE_PUP, "PUP" }, { ETHERTYPE_ARP, "ARP"}, { ETHERTYPE_REVARP, "Reverse ARP"}, { ETHERTYPE_NS, "NS" }, { ETHERTYPE_SPRITE, "Sprite" }, { ETHERTYPE_TRAIL, "Trail" }, { ETHERTYPE_MOPDL, "MOP DL" }, { ETHERTYPE_MOPRC, "MOP RC" }, { ETHERTYPE_DN, "DN" }, { ETHERTYPE_LAT, "LAT" }, { ETHERTYPE_SCA, "SCA" }, { ETHERTYPE_TEB, "TEB" }, { ETHERTYPE_LANBRIDGE, "Lanbridge" }, { ETHERTYPE_DECDNS, "DEC DNS" }, { ETHERTYPE_DECDTS, "DEC DTS" }, { ETHERTYPE_VEXP, "VEXP" }, { ETHERTYPE_VPROD, "VPROD" }, { ETHERTYPE_ATALK, "Appletalk" }, { ETHERTYPE_AARP, "Appletalk ARP" }, { ETHERTYPE_IPX, "IPX" }, { ETHERTYPE_PPP, "PPP" }, { ETHERTYPE_MPCP, "MPCP" }, { ETHERTYPE_SLOW, "Slow Protocols" }, { ETHERTYPE_PPPOED, "PPPoE D" }, { ETHERTYPE_PPPOES, "PPPoE S" }, { ETHERTYPE_EAPOL, "EAPOL" }, { ETHERTYPE_RRCP, "RRCP" }, { ETHERTYPE_MS_NLB_HB, "MS NLB heartbeat" }, { ETHERTYPE_JUMBO, "Jumbo" }, { ETHERTYPE_NSH, "NSH" }, { ETHERTYPE_LOOPBACK, "Loopback" }, { ETHERTYPE_ISO, "OSI" }, { ETHERTYPE_GRE_ISO, "GRE-OSI" }, { ETHERTYPE_CFM_OLD, "CFM (old)" }, { ETHERTYPE_CFM, "CFM" }, { ETHERTYPE_IEEE1905_1, "IEEE1905.1" }, { ETHERTYPE_LLDP, "LLDP" }, { ETHERTYPE_TIPC, "TIPC"}, { ETHERTYPE_GEONET_OLD, "GeoNet (old)"}, { ETHERTYPE_GEONET, "GeoNet"}, { ETHERTYPE_CALM_FAST, "CALM FAST"}, { ETHERTYPE_AOE, "AoE" }, { ETHERTYPE_MEDSA, "MEDSA" }, { 0, NULL} }; static inline void ether_hdr_print(netdissect_options *ndo, const u_char *bp, u_int length) { register const struct ether_header *ep; uint16_t length_type; ep = (const struct ether_header *)bp; ND_PRINT((ndo, "%s > %s", etheraddr_string(ndo, ESRC(ep)), etheraddr_string(ndo, EDST(ep)))); length_type = EXTRACT_16BITS(&ep->ether_length_type); if (!ndo->ndo_qflag) { if (length_type <= ETHERMTU) { ND_PRINT((ndo, ", 802.3")); length = length_type; } else ND_PRINT((ndo, ", ethertype %s (0x%04x)", tok2str(ethertype_values,"Unknown", length_type), length_type)); } else { if (length_type <= ETHERMTU) { ND_PRINT((ndo, ", 802.3")); length = length_type; } else ND_PRINT((ndo, ", %s", tok2str(ethertype_values,"Unknown Ethertype (0x%04x)", length_type))); } ND_PRINT((ndo, ", length %u: ", length)); } /* * Print an Ethernet frame. * This might be encapsulated within another frame; we might be passed * a pointer to a function that can print header information for that * frame's protocol, and an argument to pass to that function. * * FIXME: caplen can and should be derived from ndo->ndo_snapend and p. */ u_int ether_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen, void (*print_encap_header)(netdissect_options *ndo, const u_char *), const u_char *encap_header_arg) { const struct ether_header *ep; u_int orig_length; u_short length_type; u_int hdrlen; int llc_hdrlen; struct lladdr_info src, dst; if (caplen < ETHER_HDRLEN) { ND_PRINT((ndo, "[|ether]")); return (caplen); } if (length < ETHER_HDRLEN) { ND_PRINT((ndo, "[|ether]")); return (length); } if (ndo->ndo_eflag) { if (print_encap_header != NULL) (*print_encap_header)(ndo, encap_header_arg); ether_hdr_print(ndo, p, length); } orig_length = length; length -= ETHER_HDRLEN; caplen -= ETHER_HDRLEN; ep = (const struct ether_header *)p; p += ETHER_HDRLEN; hdrlen = ETHER_HDRLEN; src.addr = ESRC(ep); src.addr_string = etheraddr_string; dst.addr = EDST(ep); dst.addr_string = etheraddr_string; length_type = EXTRACT_16BITS(&ep->ether_length_type); recurse: /* * Is it (gag) an 802.3 encapsulation? */ if (length_type <= ETHERMTU) { /* Try to print the LLC-layer header & higher layers */ llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* packet type not known, print raw packet */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } else if (length_type == ETHERTYPE_8021Q || length_type == ETHERTYPE_8021Q9100 || length_type == ETHERTYPE_8021Q9200 || length_type == ETHERTYPE_8021QinQ) { /* * Print VLAN information, and then go back and process * the enclosed type field. */ if (caplen < 4) { ND_PRINT((ndo, "[|vlan]")); return (hdrlen + caplen); } if (length < 4) { ND_PRINT((ndo, "[|vlan]")); return (hdrlen + length); } if (ndo->ndo_eflag) { uint16_t tag = EXTRACT_16BITS(p); ND_PRINT((ndo, "%s, ", ieee8021q_tci_string(tag))); } length_type = EXTRACT_16BITS(p + 2); if (ndo->ndo_eflag && length_type > ETHERMTU) ND_PRINT((ndo, "ethertype %s, ", tok2str(ethertype_values,"0x%04x", length_type))); p += 4; length -= 4; caplen -= 4; hdrlen += 4; goto recurse; } else if (length_type == ETHERTYPE_JUMBO) { /* * Alteon jumbo frames. * See * * http://tools.ietf.org/html/draft-ietf-isis-ext-eth-01 * * which indicates that, following the type field, * there's an LLC header and payload. */ /* Try to print the LLC-layer header & higher layers */ llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* packet type not known, print raw packet */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } else { if (ethertype_print(ndo, length_type, p, length, caplen, &src, &dst) == 0) { /* type not known, print raw packet */ if (!ndo->ndo_eflag) { if (print_encap_header != NULL) (*print_encap_header)(ndo, encap_header_arg); ether_hdr_print(ndo, (const u_char *)ep, orig_length); } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } } return (hdrlen); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. */ u_int ether_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return (ether_print(ndo, p, h->len, h->caplen, NULL, NULL)); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. * * This is for DLT_NETANALYZER, which has a 4-byte pseudo-header * before the Ethernet header. */ u_int netanalyzer_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { /* * Fail if we don't have enough data for the Hilscher pseudo-header. */ if (h->len < 4 || h->caplen < 4) { ND_PRINT((ndo, "[|netanalyzer]")); return (h->caplen); } /* Skip the pseudo-header. */ return (4 + ether_print(ndo, p + 4, h->len - 4, h->caplen - 4, NULL, NULL)); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. * * This is for DLT_NETANALYZER_TRANSPARENT, which has a 4-byte * pseudo-header, a 7-byte Ethernet preamble, and a 1-byte Ethernet SOF * before the Ethernet header. */ u_int netanalyzer_transparent_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { /* * Fail if we don't have enough data for the Hilscher pseudo-header, * preamble, and SOF. */ if (h->len < 12 || h->caplen < 12) { ND_PRINT((ndo, "[|netanalyzer-transparent]")); return (h->caplen); } /* Skip the pseudo-header, preamble, and SOF. */ return (12 + ether_print(ndo, p + 12, h->len - 12, h->caplen - 12, NULL, NULL)); } /* * Prints the packet payload, given an Ethernet type code for the payload's * protocol. * * Returns non-zero if it can do so, zero if the ethertype is unknown. */ int ethertype_print(netdissect_options *ndo, u_short ether_type, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { switch (ether_type) { case ETHERTYPE_IP: ip_print(ndo, p, length); return (1); case ETHERTYPE_IPV6: ip6_print(ndo, p, length); return (1); case ETHERTYPE_ARP: case ETHERTYPE_REVARP: arp_print(ndo, p, length, caplen); return (1); case ETHERTYPE_DN: decnet_print(ndo, p, length, caplen); return (1); case ETHERTYPE_ATALK: if (ndo->ndo_vflag) ND_PRINT((ndo, "et1 ")); atalk_print(ndo, p, length); return (1); case ETHERTYPE_AARP: aarp_print(ndo, p, length); return (1); case ETHERTYPE_IPX: ND_PRINT((ndo, "(NOV-ETHII) ")); ipx_print(ndo, p, length); return (1); case ETHERTYPE_ISO: if (length == 0 || caplen == 0) { ND_PRINT((ndo, " [|osi]")); return (1); } isoclns_print(ndo, p + 1, length - 1, caplen - 1); return(1); case ETHERTYPE_PPPOED: case ETHERTYPE_PPPOES: case ETHERTYPE_PPPOED2: case ETHERTYPE_PPPOES2: pppoe_print(ndo, p, length); return (1); case ETHERTYPE_EAPOL: eap_print(ndo, p, length); return (1); case ETHERTYPE_RRCP: rrcp_print(ndo, p, length, src, dst); return (1); case ETHERTYPE_PPP: if (length) { ND_PRINT((ndo, ": ")); ppp_print(ndo, p, length); } return (1); case ETHERTYPE_MPCP: mpcp_print(ndo, p, length); return (1); case ETHERTYPE_SLOW: slow_print(ndo, p, length); return (1); case ETHERTYPE_CFM: case ETHERTYPE_CFM_OLD: cfm_print(ndo, p, length); return (1); case ETHERTYPE_LLDP: lldp_print(ndo, p, length); return (1); case ETHERTYPE_NSH: nsh_print(ndo, p, length); return (1); case ETHERTYPE_LOOPBACK: loopback_print(ndo, p, length); return (1); case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); return (1); case ETHERTYPE_TIPC: tipc_print(ndo, p, length, caplen); return (1); case ETHERTYPE_MS_NLB_HB: msnlb_print(ndo, p); return (1); case ETHERTYPE_GEONET_OLD: case ETHERTYPE_GEONET: geonet_print(ndo, p, length, src); return (1); case ETHERTYPE_CALM_FAST: calm_fast_print(ndo, p, length, src); return (1); case ETHERTYPE_AOE: aoe_print(ndo, p, length); return (1); case ETHERTYPE_MEDSA: medsa_print(ndo, p, length, caplen, src, dst); return (1); case ETHERTYPE_LAT: case ETHERTYPE_SCA: case ETHERTYPE_MOPRC: case ETHERTYPE_MOPDL: case ETHERTYPE_IEEE1905_1: /* default_print for now */ default: return (0); } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_3
crossvul-cpp_data_good_2946_0
#ifndef IGNOREALL /* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.476 $ $Date: 2015/05/25 02:29:14 $ */ /*@out DEFINES #ifndef USE_JPEG #define NO_JPEG #endif #ifndef USE_JASPER #define NO_JASPER #endif @end DEFINES */ #define NO_LCMS #define DCRAW_VERBOSE //@out DEFINES #define DCRAW_VERSION "9.26" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _USE_MATH_DEFINES #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> //@end DEFINES #if defined(DJGPP) || defined(__MINGW32__) #define fseeko fseek #define ftello ftell #else #define fgetc getc_unlocked #endif //@out DEFINES #ifdef __CYGWIN__ #include <io.h> #endif #if defined WIN32 || defined(__MINGW32__) #include <sys/utime.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define snprintf _snprintf #define strcasecmp stricmp #define strncasecmp strnicmp //@end DEFINES typedef __int64 INT64; typedef unsigned __int64 UINT64; //@out DEFINES #else #include <unistd.h> #include <utime.h> #include <netinet/in.h> typedef long long INT64; typedef unsigned long long UINT64; #endif #ifdef NODEPS #define NO_JASPER #define NO_JPEG #define NO_LCMS #endif #ifndef NO_JASPER #include <jasper/jasper.h> /* Decode Red camera movies */ #endif #ifndef NO_JPEG #include <jpeglib.h> /* Decode compressed Kodak DC120 photos */ #endif /* and Adobe Lossy DNGs */ #ifndef NO_LCMS #ifdef USE_LCMS #include <lcms.h> /* Support color profiles */ #else #include <lcms2.h> /* Support color profiles */ #endif #endif #ifdef LOCALEDIR #include <libintl.h> #define _(String) gettext(String) #else #define _(String) (String) #endif #ifdef LJPEG_DECODE #error Please compile dcraw.c by itself. #error Do not link it with ljpeg_decode. #endif #ifndef LONG_BIT #define LONG_BIT (8 * sizeof(long)) #endif //@end DEFINES #if !defined(uchar) #define uchar unsigned char #endif #if !defined(ushort) #define ushort unsigned short #endif /* All global variables are defined here, and all functions that access them are prefixed with "CLASS". Note that a thread-safe C++ class cannot have non-const static local variables. */ FILE *ifp, *ofp; short order; const char *ifname; char *meta_data, xtrans[6][6], xtrans_abs[6][6]; char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64]; float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len; time_t timestamp; off_t strip_offset, data_offset; off_t thumb_offset, meta_offset, profile_offset; unsigned shot_order, kodak_cbpp, exif_cfa, unique_id; unsigned thumb_length, meta_length, profile_length; unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0; unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress; unsigned black, maximum, mix_green, raw_color, zero_is_bad; unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error; unsigned tile_width, tile_length, gpsdata[32], load_flags; unsigned flip, tiff_flip, filters, colors; ushort raw_height, raw_width, height, width, top_margin, left_margin; ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height; ushort *raw_image, (*image)[4], cblack[4102]; ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4]; double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0; int mask[8][4]; int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0; int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1; int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0; int no_auto_bright = 0; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4]; const double xyz_rgb[3][3] = {/* XYZ from RGB */ {0.412453, 0.357580, 0.180423}, {0.212671, 0.715160, 0.072169}, {0.019334, 0.119193, 0.950227}}; const float d65_white[3] = {0.950456, 1, 1.088754}; int histogram[4][0x2000]; void (*write_thumb)(), (*write_fun)(); void (*load_raw)(), (*thumb_load_raw)(); jmp_buf failure; struct decode { struct decode *branch[2]; int leaf; } first_decode[2048], *second_decode, *free_decode; struct tiff_ifd { int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes; int t_tile_width, t_tile_length, sample_format, predictor; float t_shutter; } tiff_ifd[10]; struct ph1 { int format, key_off, tag_21a; int t_black, split_col, black_col, split_row, black_row; float tag_210; } ph1; #define CLASS //@out DEFINES #define FORC(cnt) for (c = 0; c < cnt; c++) #define FORC3 FORC(3) #define FORC4 FORC(4) #define FORCC for (c = 0; c < colors && c < 4; c++) #define SQR(x) ((x) * (x)) #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM((int)(x), 0, 65535) #define CLIP15(x) LIM((int)(x), 0, 32767) #define SWAP(a, b) \ { \ a = a + b; \ b = a - b; \ a = a - b; \ } #define my_swap(type, i, j) \ { \ type t = i; \ i = j; \ j = t; \ } static float fMAX(float a, float b) { return MAX(a, b); } /* In order to inline this calculation, I make the risky assumption that all filter patterns can be described by a repeating pattern of eight rows and two columns Do not use the FC or BAYER macros with the Leaf CatchLight, because its pattern is 16x16, not 2x8. Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2 PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1 0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M 1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C 2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y 3 C Y C Y C Y 3 G M G M G M 3 G M G M G M 4 C Y C Y C Y 4 Y C Y C Y C PowerShot A5 5 G M G M G M 5 G M G M G M 0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y 7 M G M G M G 7 M G M G M G 0 1 2 3 4 5 0 C Y C Y C Y 1 G M G M G M 2 C Y C Y C Y 3 M G M G M G All RGB cameras use one of these Bayer grids: 0x16161616: 0x61616161: 0x49494949: 0x94949494: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G 1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B 2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G 3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B */ #define RAW(row, col) raw_image[(row)*raw_width + (col)] //@end DEFINES #define FC(row, col) (filters >> ((((row) << 1 & 14) + ((col)&1)) << 1) & 3) //@out DEFINES #define BAYER(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][FC(row, col)] #define BAYER2(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][fcol(row, col)] //@end DEFINES /* @out COMMON #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end COMMON */ //@out COMMON int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) //@end COMMON void CLASS merror(void *ptr, const char *where) { if (ptr) return; fprintf(stderr, _("%s: Out of memory in %s\n"), ifname, where); longjmp(failure, 1); } void CLASS derror() { if (!data_error) { fprintf(stderr, "%s: ", ifname); if (feof(ifp)) fprintf(stderr, _("Unexpected end of file\n")); else fprintf(stderr, _("Corrupt data near 0x%llx\n"), (INT64)ftello(ifp)); } data_error++; } //@out COMMON ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, int count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } //@end COMMON struct jhead { int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6]; ushort quant[64], idct[64], *huff[20], *free[20], *row; }; //@out COMMON int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width * 3 * tiff_bps / 8; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } //@end COMMON void CLASS jpeg_thumb(); //@out COMMON void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS panasonic_16x10_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_DECODE_RAW; #endif } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } //@end COMMON /* RESTRICTED code starts here */ void CLASS foveon_decoder(unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i = 0; i < size; i++) huff[i] = get4(); memset(first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode + 2048) { fprintf(stderr, _("%s: decoder table overflow\n"), ifname); longjmp(failure, 2); } if (code) for (i = 0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len + 1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder(size, code); cur->branch[1] = free_decode; foveon_decoder(size, code + 1); } void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf = 0, bit = 1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width * 3) return; buf = (char *)malloc(bwide); merror(buf, "foveon_thumb()"); for (row = 0; row < thumb_height; row++) { fread(buf, 1, bwide, ifp); fwrite(buf, 3, thumb_width, ofp); } free(buf); return; } foveon_decoder(256, 0); for (row = 0; row < thumb_height; row++) { memset(pred, 0, sizeof pred); if (!bit) get4(); for (bit = col = 0; col < thumb_width; col++) FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc(pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { struct decode *dindex; short diff[1024]; unsigned bitbuf = 0; int pred[3], row, col, bit = -1, c, i; read_shorts((ushort *)diff, 1024); if (!load_flags) foveon_decoder(1024, 0); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model + 2) < 14) get4(); for (col = bit = 0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2 - c] += diff[bitbuf >> c * 10 & 0x3ff]; } else FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row * width + col][c] = pred[c]; } } } void CLASS foveon_huff(ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i = 0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j = 0; j<256>> clen;) huff[code + ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek(ifp, 8, SEEK_CUR); foveon_huff(huff); roff[0] = 48; FORC3 roff[c + 1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek(ifp, data_offset + roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row * width + col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512, 512}, {512, 512}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread(meta_data, 1, meta_length, ifp); for (i = 0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64)301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free(meta_data); meta_data = (char *)malloc(meta_length = wide * high * 3 / 2); merror(meta_data, "foveon_load_camf()"); foveon_huff(huff); get4(); getbits(-1); for (j = row = 0; row < high; row++) { for (col = 0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("%s has unknown CAMF type %d.\n"), ifname, type); #endif } const char *CLASS foveon_camf_param(const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp(block, pos + sget4(pos + 12))) continue; cp = pos + sget4(pos + 16); num = sget4(cp); dp = pos + sget4(cp + 4); while (num--) { cp += 8; if (!strcmp(param, dp + sget4(cp))) return dp + sget4(cp + 4); } } return 0; } void *CLASS foveon_camf_matrix(unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp(name, pos + sget4(pos + 12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos + 16); type = sget4(cp); if ((ndim = sget4(cp + 4)) > 3) break; dp = pos + sget4(cp + 8); for (i = ndim; i--;) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double)dim[0] * dim[1] * dim[2]) > meta_length / 4) break; mat = (unsigned *)malloc((size = dsize) * 4); merror(mat, "foveon_camf_matrix()"); for (i = 0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i * 4); else mat[i] = sget4(dp + i * 2) & 0xffff; return mat; } #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: \"%s\" matrix not found!\n"), ifname, name); #endif return 0; } int CLASS foveon_fixed(void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix(dim, name); if (!dp) return 0; memcpy(ptr, dp, size * 4); free(dp); return 1; } float CLASS foveon_avg(short *pix, int range[2], float cfilt) { int i; float val, min = FLT_MAX, max = -FLT_MAX, sum = 0; for (i = range[0]; i <= range[1]; i++) { sum += val = pix[i * 4] + (pix[i * 4] - pix[(i - 1) * 4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum / 2; return (sum - min - max) / (range[1] - range[0] - 1); } short *CLASS foveon_make_curve(double max, double mul, double filt) { short *curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4 * M_PI * max / filt; if (size == UINT_MAX) size--; curve = (short *)calloc(size + 1, sizeof *curve); merror(curve, "foveon_make_curve()"); curve[0] = size; for (i = 0; i < size; i++) { x = i * filt / max / 4; curve[i + 1] = (cos(x) + 1) / 2 * tanh(i * filt / mul) * mul + 0.5; } return curve; } void CLASS foveon_make_curves(short **curvep, float dq[3], float div[3], float filt) { double mul[3], max = 0; int c; FORC3 mul[c] = dq[c] / div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve(max, mul[c], filt); } int CLASS foveon_apply_curve(short *curve, int i) { if (abs(i) >= curve[0]) return 0; return i < 0 ? -curve[1 - i] : curve[1 + i]; } #define image ((short(*)[4])image) void CLASS foveon_interpolate() { static const short hood[] = {-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1}; short *pix, prev[3], *curve[8], (*shrink)[3]; float cfilt = 0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float(*black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p = 0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum = 0, trsum[3]; char str[128]; const char *cp; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Foveon interpolation...\n")); #endif foveon_load_camf(); foveon_fixed(dscr, 4, "DarkShieldColRange"); foveon_fixed(ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed(satlev, 3, "SaturationLevel"); foveon_fixed(keep, 4, "KeepImageArea"); foveon_fixed(active, 4, "ActiveImageArea"); foveon_fixed(chroma_dq, 3, "ChromaDQ"); foveon_fixed(color_dq, 3, foveon_camf_param("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param("IncludeBlocks", "ColumnFilter")) foveon_fixed(&cfilt, 1, "ColumnFilter"); memset(ddft, 0, sizeof ddft); if (!foveon_camf_param("IncludeBlocks", "DarkDrift") || !foveon_fixed(ddft[1][0], 12, "DarkDrift")) for (i = 0; i < 2; i++) { foveon_fixed(dstb, 4, i ? "DarkShieldBottom" : "DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i + 1][c][1] += (short)image[row * width + col][c]; FORC3 ddft[i + 1][c][1] /= (dstb[3] - dstb[1] + 1) * (dstb[2] - dstb[0] + 1); } if (!(cp = foveon_camf_param("WhiteBalanceIlluminants", model2))) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Invalid white balance \"%s\"\n"), ifname, model2); #endif return; } foveon_fixed(cam_xyz, 9, cp); foveon_fixed(correct, 9, foveon_camf_param("WhiteBalanceCorrections", model2)); memset(last, 0, sizeof last); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x, y) last[(i + x) % 3][(c + y) % 3] for (i = 0; i < 3; i++) FORC3 diag[c][i] = LAST(1, 1) * LAST(2, 2) - LAST(1, 2) * LAST(2, 1); #undef LAST FORC3 div[c] = diag[c][0] * 0.3127 + diag[c][1] * 0.329 + diag[c][2] * 0.3583; sprintf(str, "%sRGBNeutral", model2); if (foveon_camf_param("IncludeBlocks", str)) foveon_fixed(div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6 * trsum[0] + 11 * trsum[1] + 3 * trsum[2]) / 20; for (i = 0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += (i == c ? 32 : -1) * last[c][j] / 30; foveon_make_curves(curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves(curve + 3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; curve[6] = foveon_make_curve(dsum, dsum, cfilt); curve[7] = foveon_make_curve(dsum * 2, dsum * 2, cfilt); sgain = (float(*)[3])foveon_camf_matrix(dim, "SpatialGain"); if (!sgain) return; sgrow = (float(*)[3])calloc(dim[1], sizeof *sgrow); sgx = (width + dim[1] - 2) / (dim[1] - 1); black = (float(*)[3])calloc(height, sizeof *black); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); FORC3 black[row][c] = (foveon_avg(image[row * width] + c, dscr[0], cfilt) + foveon_avg(image[row * width] + c, dscr[1], cfilt) * 3 - ddft[0][c][0]) / 4 - ddft[0][c][1]; } memcpy(black, black + 8, sizeof *black * 8); memcpy(black + height - 11, black + height - 22, 11 * sizeof *black); memcpy(last, black, sizeof last); for (row = 1; row < height - 1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) black[row][c] = (last[0][c] > last[2][c]) ? last[0][c] : last[2][c]; } else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c] : last[2][c]; memmove(last, last + 1, 2 * sizeof last[0]); memcpy(last[2], black[row + 1], sizeof last[2]); } FORC3 black[row][c] = (last[0][c] + last[1][c]) / 2; FORC3 black[0][c] = (black[1][c] + black[3][c]) / 2; val = 1 - exp(-1 / 24.0); memcpy(fsum, black, sizeof fsum); for (row = 1; row < height; row++) FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row - 1][c]) * val + black[row - 1][c]; memcpy(last[0], black[height - 1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--;) FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c]) * val + last[0][c]; memset(total, 0, sizeof total); for (row = 2; row < height; row += 4) for (col = 2; col < width; col += 4) { FORC3 total[c] += (short)image[row * width + col][c]; total[3]++; } for (row = 0; row < height; row++) FORC3 black[row][c] += fsum[c] / 2 + total[c] / (total[3] * 100.0); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); pix = image[row * width]; memcpy(prev, pix, sizeof prev); frow = row / (height - 1.0) * (dim[2] - 1); if ((irow = frow) == dim[2] - 1) irow--; frow -= irow; for (i = 0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[irow * dim[1] + i][c] * (1 - frow) + sgain[(irow + 1) * dim[1] + i][c] * frow; for (col = 0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor((diff + (diff * diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float)col / width - 0.5) - black[row][c]); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2 - c] = ipix[(c + 1) % 3] * ipix[(c + 2) % 3] >> 14; } FORC3 { for (val = i = 0; i < 3; i++) for (j = 0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor((ipix[c] + floor(val)) * (sgrow[col / sgx][c] * (sgx - col % sgx) + sgrow[col / sgx + 1][c] * (col % sgx)) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free(black); free(sgrow); free(sgain); if ((badpix = (unsigned *)foveon_camf_matrix(dim, "BadPixels"))) { for (i = 0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20) - keep[1]; if ((unsigned)(row - 1) > height - 3 || (unsigned)(col - 1) > width - 3) continue; memset(fsum, 0, sizeof fsum); for (sum = j = 0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short)image[(row + hood[j * 2]) * width + col + hood[j * 2 + 1]][c]; sum++; } if (sum) FORC3 image[row * width + col][c] = fsum[c] / sum; } free(badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int(*)[3])calloc(width * 5, sizeof **smrow); merror(smrow[6], "foveon_interpolate()"); for (i = 0; i < 5; i++) smrow[i] = smrow[6] + i * width; /* Sharpen the reds against these Gaussian averages */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { smrow[4][col][0] = (pix[0] * 6 + (pix[-4] + pix[4]) * 4 + pix[-8] + pix[8] + 8) >> 4; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { smred = (6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred * 7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix = image[0]; pix < image[height * width]; pix += 4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c = 1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit * 2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i * i >> 14); i = i * i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 4] + 2 * pix[c] + pix[c + 4] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 dev[c] = -foveon_apply_curve(curve[7], pix[c] - ((smrow[1][col][c] + 2 * smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 8] + pix[c - 4] + pix[c] + pix[c + 4] + pix[c + 8] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { for (total[3] = 375, sum = 60, c = 0; c < 3; c++) { for (total[c] = i = 0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve(curve[6], ((j * total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix = image[0]; pix < image[height * width]; pix += 4) { FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c]); sum = (pix[0] + pix[1] + pix[1] + pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c] - sum); FORC3 { for (dsum = i = 0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ shrink = (short(*)[3])calloc((height / 4), (width / 4) * sizeof *shrink); merror(shrink, "foveon_interpolate()"); for (row = height / 4; row--;) for (col = 0; col < width / 4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) FORC3 ipix[c] += image[(row * 4 + i) * width + col * 4 + j][c]; FORC3 if (row + 2 > height / 4) shrink[row * (width / 4) + col][c] = ipix[c] >> 4; else shrink[row * (width / 4) + col][c] = (shrink[(row + 1) * (width / 4) + col][c] * 1840 + ipix[c] * 141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row = 0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3; col--;) FORC3 smrow[0][col][c] = ipix[c] = (shrink[(row / 4) * (width / 4) + col / 4][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col = 0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy(smrow[2], smrow[1], sizeof **smrow * width); else for (col = 0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c] * 6707 + smrow[1][col][c] * 1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col = 0; col < (width & ~3); col++) { for (i = j = 30, c = 0; c < 3; c++) { i += smrow[2][col][c]; j += image[row * width + col][c]; } j = (j << 16) / i; for (sum = c = 0; c < 3; c++) { ipix[c] = foveon_apply_curve(curve[c + 3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row * width + col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row * width + col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row * width + col][c] = i; } } } free(shrink); free(smrow[6]); for (i = 0; i < 8; i++) free(curve[i]); /* Trim off the black border */ active[1] -= keep[1]; active[3] -= 2; i = active[2] - active[0]; for (row = 0; row < active[3] - active[1]; row++) memcpy(image[row * i], image[(row + active[1]) * width + active[0]], i * sizeof *image); width = i; height = row; } #undef image /* RESTRICTED code ends here */ //@out COMMON void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } //@end COMMON /* @out FILEIO #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end FILEIO */ // @out FILEIO /* Seach from the current directory up to the root looking for a ".badpixels" file, and fix those pixels now. */ void CLASS bad_pixels(const char *cfname) { FILE *fp = NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed = 0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 0, 2); #endif if (cfname) fp = fopen(cfname, "r"); // @end FILEIO else { for (len = 32;; len *= 2) { fname = (char *)malloc(len); if (!fname) return; if (getcwd(fname, len - 16)) break; free(fname); if (errno != ERANGE) return; } #if defined(WIN32) || defined(DJGPP) if (fname[1] == ':') memmove(fname, fname + 2, len - 2); for (cp = fname; *cp; cp++) if (*cp == '\\') *cp = '/'; #endif cp = fname + strlen(fname); if (cp[-1] == '/') cp--; while (*fname == '/') { strcpy(cp, "/.badpixels"); if ((fp = fopen(fname, "r"))) break; if (cp == fname) break; while (*--cp != '/') ; } free(fname); } // @out FILEIO if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets(line, 128, fp)) { cp = strchr(line, '#'); if (cp) *cp = 0; if (sscanf(line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned)col >= width || (unsigned)row >= height) continue; if (time > timestamp) continue; for (tot = n = 0, rad = 1; rad < 3 && n == 0; rad++) for (r = row - rad; r <= row + rad; r++) for (c = col - rad; c <= col + rad; c++) if ((unsigned)r < height && (unsigned)c < width && (r != row || c != col) && fcol(r, c) == fcol(row, col)) { tot += BAYER2(r, c); n++; } BAYER2(row, col) = tot / n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf(stderr, _("Fixed dead pixels at:")); fprintf(stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc('\n', stderr); #endif fclose(fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 1, 2); #endif } void CLASS subtract(const char *fname) { FILE *fp; int dim[3] = {0, 0, 0}, comment = 0, number = 0, error = 0, nd = 0, c, row, col; ushort *pixel; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 0, 2); #endif if (!(fp = fopen(fname, "rb"))) { #ifdef DCRAW_VERBOSE perror(fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE; #endif return; } if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1; while (!error && nd < 3 && (c = fgetc(fp)) != EOF) { if (c == '#') comment = 1; if (c == '\n') comment = 0; if (comment) continue; if (isdigit(c)) number = 1; if (number) { if (isdigit(c)) dim[nd] = dim[nd] * 10 + c - '0'; else if (isspace(c)) { number = 0; nd++; } else error = 1; } } if (error || nd < 3) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s is not a valid PGM file!\n"), fname); #endif fclose(fp); return; } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has the wrong dimensions!\n"), fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM; #endif fclose(fp); return; } pixel = (ushort *)calloc(width, sizeof *pixel); merror(pixel, "subtract()"); for (row = 0; row < height; row++) { fread(pixel, 2, width, fp); for (col = 0; col < width; col++) BAYER(row, col) = MAX(BAYER(row, col) - ntohs(pixel[col]), 0); } free(pixel); fclose(fp); memset(cblack, 0, sizeof cblack); black = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 1, 2); #endif } //@end FILEIO //@out COMMON static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } //@end COMMON int CLASS parse_tiff_ifd(int base); //@out COMMON static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float powf64(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-3)<<2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-1)<<2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-2)<<2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-4)<<2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy (model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp-128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x231 << 1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 358) || // ILCE-9 (id == 362) || // ILCE-7RM3 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 358) || (id == 360) || (id == 362)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, unsigned id) { if ((id == 257) || (id == 262) || (id == 269) || (id == 270)) imgdata.other.BatteryTemperature = (float) (buf[1]-32) / 1.8f; else if ((id != 263) && (id != 264) && (id != 265) && (id != 266)) imgdata.other.BatteryTemperature = (float) (buf[2]-32) / 1.8f; return; } void CLASS process_Sony_0x9402(uchar *buf) { if (buf[2] != 0xff) return; short bufx = SonySubstitution[buf[0]]; if ((bufx < 0x0f) || (bufx > 0x1a) || (bufx == 0x16) || (bufx == 0x18)) return; imgdata.other.AmbientTemperature = (float) ((short) SonySubstitution[buf[4]]); return; } void CLASS process_Sony_0x9403(uchar *buf) { short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float) ((short) SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf) { short bufx = SonySubstitution[buf[0]]; if ((bufx != 0x00) && (bufx == 0x01) && (bufx == 0x03)) return; bufx = SonySubstitution[buf[2]]; if ((bufx != 0x02) && (bufx == 0x03)) return; imgdata.other.BatteryTemperature = (float) (SonySubstitution[buf[5]]-32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050(uchar *buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_present, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_present, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_present, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_present) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_present) { process_Sony_0x0116(table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x9402_present) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } if (table_buf_0x9403_present) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } if (table_buf_0x9406_present) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_present = 1; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116 (table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_present = 1; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_present = 1; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_present = 1; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) continue; tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */} #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = powf64(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; pos = strtok(ccms, ","); for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok(NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif //@end COMMON void CLASS parse_minolta(int base); int CLASS parse_tiff(int base); //@out COMMON int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > fsize * 2) continue; // skip tag pointing out of 2xfile if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width * raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) load_flags = 24; if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(), get4()))); aperture = powf64(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = powf64(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } //@end COMMON char *CLASS foveon_gets(int offset, char *str, int len) { int i; fseek(ifp, offset, SEEK_SET); for (i = 0; i < len - 1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek(ifp, 36, SEEK_SET); flip = get4(); fseek(ifp, -4, SEEK_END); fseek(ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(), get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek(ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek(ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off + 28; is_foveon = 1; } fseek(ifp, off + 28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28) { thumb_offset = off + 28; thumb_length = len - 28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off + 24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off + 8; meta_length = len - 28; break; case 0x504f5250: /* PROP */ pent = (get4(), get4()); fseek(ifp, 12, SEEK_CUR); off += pent * 8 + 24; if ((unsigned)pent > 256) pent = 256; for (i = 0; i < pent * 2; i++) ((int *)poff)[i] = off + get4() * 2; for (i = 0; i < pent; i++) { foveon_gets(poff[i][0], name, 64); foveon_gets(poff[i][1], value, 64); if (!strcmp(name, "ISO")) iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(make, value); if (!strcmp(name, "CAMMODEL")) strcpy(model, value); if (!strcmp(name, "WB_DESC")) strcpy(model2, value); if (!strcmp(name, "TIME")) timestamp = atoi(value); if (!strcmp(name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp(name, "APERTURE")) aperture = atof(value); if (!strcmp(name, "FLENGTH")) focal_len = atof(value); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } #endif } #ifdef LOCALTIME timestamp = mktime(gmtime(&timestamp)); #endif } fseek(ifp, save, SEEK_SET); } } //@out COMMON /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, /* temp */ { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, /* prelim */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, /* temp */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace(string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread(head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head + 0x1c); memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if(width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width*height) || i > (2* width*height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) strcpy(model, model + 8); if (!strncmp(model, "Digital Camera ", 15)) strcpy(model, model + 15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2)) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; #ifdef LIBRAW_LIBRARY_BUILD float fratio = float(data_size) / (float(raw_height) * float(raw_width)); if(!(raw_width % 10) && !(data_size % 16384) && fratio >= 1.6f && fratio <= 1.6001f) { load_raw = &CLASS panasonic_16x10_load_raw; zero_is_bad = 0; } #endif if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } //@end COMMON //@out FILEIO #ifndef NO_LCMS void CLASS apply_profile(const char *input, const char *output) { char *prof; cmsHPROFILE hInProfile = 0, hOutProfile = 0; cmsHTRANSFORM hTransform; FILE *fp; unsigned size; if (strcmp(input, "embed")) hInProfile = cmsOpenProfileFromFile(input, "r"); else if (profile_length) { #ifndef LIBRAW_LIBRARY_BUILD prof = (char *)malloc(profile_length); merror(prof, "apply_profile()"); fseek(ifp, profile_offset, SEEK_SET); fread(prof, 1, profile_length, ifp); hInProfile = cmsOpenProfileFromMem(prof, profile_length); free(prof); #else hInProfile = cmsOpenProfileFromMem(imgdata.color.profile, profile_length); #endif } else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has no embedded profile.\n"), ifname); #endif } if (!hInProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE; #endif return; } if (!output) hOutProfile = cmsCreate_sRGBProfile(); else if ((fp = fopen(output, "rb"))) { fread(&size, 4, 1, fp); fseek(fp, 0, SEEK_SET); oprof = (unsigned *)malloc(size = ntohl(size)); merror(oprof, "apply_profile()"); fread(oprof, 1, size, fp); fclose(fp); if (!(hOutProfile = cmsOpenProfileFromMem(oprof, size))) { free(oprof); oprof = 0; } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("Cannot open file %s!\n"), output); #endif if (!hOutProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE; #endif goto quit; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Applying color profile...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 0, 2); #endif hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0); cmsDoTransform(hTransform, image, image, width * height); raw_color = 1; /* Don't use rgb_cam with a profile */ cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); quit: cmsCloseProfile(hInProfile); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 1, 2); #endif } #endif //@end FILEIO //@out COMMON void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } //@end COMMON struct tiff_tag { ushort tag, type; int count; union { char c[4]; short s[2]; int i; } val; }; struct tiff_hdr { ushort t_order, magic; int ifd; ushort pad, ntag; struct tiff_tag tag[23]; int nextifd; ushort pad2, nexif; struct tiff_tag exif[4]; ushort pad3, ngps; struct tiff_tag gpst[10]; short bps[4]; int rat[10]; unsigned gps[26]; char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64]; }; //@out COMMON void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); } //@end COMMON int CLASS main(int argc, const char **argv) { int arg, status = 0, quality, i, c; int timestamp_only = 0, thumbnail_only = 0, identify_only = 0; int user_qual = -1, user_black = -1, user_sat = -1, user_flip = -1; int use_fuji_rotate = 1, write_to_stdout = 0, read_from_stdin = 0; const char *sp, *bpfile = 0, *dark_frame = 0, *write_ext; char opm, opt, *ofname, *cp; struct utimbuf ut; #ifndef NO_LCMS const char *cam_profile = 0, *out_profile = 0; #endif #ifndef LOCALTIME putenv((char *)"TZ=UTC"); #endif #ifdef LOCALEDIR setlocale(LC_CTYPE, ""); setlocale(LC_MESSAGES, ""); bindtextdomain("dcraw", LOCALEDIR); textdomain("dcraw"); #endif if (argc == 1) { printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION); printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n")); printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]); puts(_("-v Print verbose messages")); puts(_("-c Write image data to standard output")); puts(_("-e Extract embedded thumbnail image")); puts(_("-i Identify files without decoding them")); puts(_("-i -v Identify files and show metadata")); puts(_("-z Change file dates to camera timestamp")); puts(_("-w Use camera white balance, if possible")); puts(_("-a Average the whole image for white balance")); puts(_("-A <x y w h> Average a grey box for white balance")); puts(_("-r <r g b g> Set custom white balance")); puts(_("+M/-M Use/don't use an embedded color matrix")); puts(_("-C <r b> Correct chromatic aberration")); puts(_("-P <file> Fix the dead pixels listed in this file")); puts(_("-K <file> Subtract dark frame (16-bit raw PGM)")); puts(_("-k <num> Set the darkness level")); puts(_("-S <num> Set the saturation level")); puts(_("-n <num> Set threshold for wavelet denoising")); puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)")); puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)")); puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)")); #ifndef NO_LCMS puts(_("-o <file> Apply output ICC profile from file")); puts(_("-p <file> Apply camera ICC profile from file or \"embed\"")); #endif puts(_("-d Document mode (no color, no interpolation)")); puts(_("-D Document mode without scaling (totally raw)")); puts(_("-j Don't stretch or rotate raw pixels")); puts(_("-W Don't automatically brighten the image")); puts(_("-b <num> Adjust brightness (default = 1.0)")); puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)")); puts(_("-q [0-3] Set the interpolation quality")); puts(_("-h Half-size color image (twice as fast as \"-q 0\")")); puts(_("-f Interpolate RGGB as four colors")); puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G")); puts(_("-s [0..N-1] Select one raw image or \"all\" from each file")); puts(_("-6 Write 16-bit instead of 8-bit")); puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\"")); puts(_("-T Write TIFF instead of PPM")); puts(""); return 1; } argv[argc] = ""; for (arg = 1; (((opm = argv[arg][0]) - 2) | 2) == '+';) { opt = argv[arg++][1]; if ((cp = (char *)strchr(sp = "nbrkStqmHACg", opt))) for (i = 0; i < "114111111422"[cp - sp] - '0'; i++) if (!isdigit(argv[arg + i][0])) { fprintf(stderr, _("Non-numeric argument to \"-%c\"\n"), opt); return 1; } switch (opt) { case 'n': threshold = atof(argv[arg++]); break; case 'b': bright = atof(argv[arg++]); break; case 'r': FORC4 user_mul[c] = atof(argv[arg++]); break; case 'C': aber[0] = 1 / atof(argv[arg++]); aber[2] = 1 / atof(argv[arg++]); break; case 'g': gamm[0] = atof(argv[arg++]); gamm[1] = atof(argv[arg++]); if (gamm[0]) gamm[0] = 1 / gamm[0]; break; case 'k': user_black = atoi(argv[arg++]); break; case 'S': user_sat = atoi(argv[arg++]); break; case 't': user_flip = atoi(argv[arg++]); break; case 'q': user_qual = atoi(argv[arg++]); break; case 'm': med_passes = atoi(argv[arg++]); break; case 'H': highlight = atoi(argv[arg++]); break; case 's': shot_select = abs(atoi(argv[arg])); multi_out = !strcmp(argv[arg++], "all"); break; case 'o': if (isdigit(argv[arg][0]) && !argv[arg][1]) output_color = atoi(argv[arg++]); #ifndef NO_LCMS else out_profile = argv[arg++]; break; case 'p': cam_profile = argv[arg++]; #endif break; case 'P': bpfile = argv[arg++]; break; case 'K': dark_frame = argv[arg++]; break; case 'z': timestamp_only = 1; break; case 'e': thumbnail_only = 1; break; case 'i': identify_only = 1; break; case 'c': write_to_stdout = 1; break; case 'v': verbose = 1; break; case 'h': half_size = 1; break; case 'f': four_color_rgb = 1; break; case 'A': FORC4 greybox[c] = atoi(argv[arg++]); case 'a': use_auto_wb = 1; break; case 'w': use_camera_wb = 1; break; case 'M': use_camera_matrix = 3 * (opm == '+'); break; case 'I': read_from_stdin = 1; break; case 'E': document_mode++; case 'D': document_mode++; case 'd': document_mode++; case 'j': use_fuji_rotate = 0; break; case 'W': no_auto_bright = 1; break; case 'T': output_tiff = 1; break; case '4': gamm[0] = gamm[1] = no_auto_bright = 1; case '6': output_bps = 16; break; default: fprintf(stderr, _("Unknown option \"-%c\".\n"), opt); return 1; } } if (arg == argc) { fprintf(stderr, _("No files to process.\n")); return 1; } if (write_to_stdout) { if (isatty(1)) { fprintf(stderr, _("Will not write an image to the terminal!\n")); return 1; } #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) if (setmode(1, O_BINARY) < 0) { perror("setmode()"); return 1; } #endif } for (; arg < argc; arg++) { status = 1; raw_image = 0; image = 0; oprof = 0; meta_data = ofname = 0; ofp = stdout; if (setjmp(failure)) { if (fileno(ifp) > 2) fclose(ifp); if (fileno(ofp) > 2) fclose(ofp); status = 1; goto cleanup; } ifname = argv[arg]; if (!(ifp = fopen(ifname, "rb"))) { perror(ifname); continue; } status = (identify(), !is_raw); if (user_flip >= 0) flip = user_flip; switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; } if (timestamp_only) { if ((status = !timestamp)) fprintf(stderr, _("%s has no timestamp.\n"), ifname); else if (identify_only) printf("%10ld%10d %s\n", (long)timestamp, shot_order, ifname); else { if (verbose) fprintf(stderr, _("%s time set to %d.\n"), ifname, (int)timestamp); ut.actime = ut.modtime = timestamp; utime(ifname, &ut); } goto next; } write_fun = &CLASS write_ppm_tiff; if (thumbnail_only) { if ((status = !thumb_offset)) { fprintf(stderr, _("%s has no thumbnail.\n"), ifname); goto next; } else if (thumb_load_raw) { load_raw = thumb_load_raw; data_offset = thumb_offset; height = thumb_height; width = thumb_width; filters = 0; colors = 3; } else { fseek(ifp, thumb_offset, SEEK_SET); write_fun = write_thumb; goto thumbnail; } } if (load_raw == &CLASS kodak_ycbcr_load_raw) { height += height & 1; width += width & 1; } if (identify_only && verbose && make[0]) { printf(_("\nFilename: %s\n"), ifname); printf(_("Timestamp: %s"), ctime(&timestamp)); printf(_("Camera: %s %s\n"), make, model); if (artist[0]) printf(_("Owner: %s\n"), artist); if (dng_version) { printf(_("DNG Version: ")); for (i = 24; i >= 0; i -= 8) printf("%d%c", dng_version >> i & 255, i ? '.' : '\n'); } printf(_("ISO speed: %d\n"), (int)iso_speed); printf(_("Shutter: ")); if (shutter > 0 && shutter < 1) shutter = (printf("1/"), 1 / shutter); printf(_("%0.1f sec\n"), shutter); printf(_("Aperture: f/%0.1f\n"), aperture); printf(_("Focal length: %0.1f mm\n"), focal_len); printf(_("Embedded ICC profile: %s\n"), profile_length ? _("yes") : _("no")); printf(_("Number of raw images: %d\n"), is_raw); if (pixel_aspect != 1) printf(_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect); if (thumb_offset) printf(_("Thumb size: %4d x %d\n"), thumb_width, thumb_height); printf(_("Full size: %4d x %d\n"), raw_width, raw_height); } else if (!is_raw) fprintf(stderr, _("Cannot decode file %s\n"), ifname); if (!is_raw) goto next; shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1))); iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (identify_only) { if (verbose) { if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (use_fuji_rotate) { if (fuji_width) { fuji_width = (fuji_width - 1 + shrink) >> shrink; iwidth = fuji_width / sqrt(0.5); iheight = (iheight - fuji_width) / sqrt(0.5); } else { if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5; if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5; } } if (flip & 4) SWAP(iheight, iwidth); printf(_("Image size: %4d x %d\n"), width, height); printf(_("Output size: %4d x %d\n"), iwidth, iheight); printf(_("Raw colors: %d"), colors); if (filters) { int fhigh = 2, fwide = 2; if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4; if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8; if (filters == 1) fhigh = fwide = 16; if (filters == 9) fhigh = fwide = 6; printf(_("\nFilter pattern: ")); for (i = 0; i < fhigh; i++) for (c = i && putchar('/') && 0; c < fwide; c++) putchar(cdesc[fcol(i, c)]); } printf(_("\nDaylight multipliers:")); FORCC printf(" %f", pre_mul[c]); if (cam_mul[0] > 0) { printf(_("\nCamera multipliers:")); FORC4 printf(" %f", cam_mul[c]); } putchar('\n'); } else printf(_("%s is a %s %s image.\n"), ifname, make, model); next: fclose(ifp); continue; } if (meta_length) { meta_data = (char *)malloc(meta_length); merror(meta_data, "main()"); } if (filters || colors == 1) { raw_image = (ushort *)calloc((raw_height + 7), raw_width * 2); merror(raw_image, "main()"); } else { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); } if (verbose) fprintf(stderr, _("Loading %s %s image from %s ...\n"), make, model, ifname); if (shot_select >= is_raw) fprintf(stderr, _("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select); fseeko(ifp, data_offset, SEEK_SET); if (raw_image && read_from_stdin) fread(raw_image, 2, raw_height * raw_width, stdin); else (*load_raw)(); if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (raw_image) { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); crop_masked_pixels(); free(raw_image); } if (zero_is_bad) remove_zeroes(); bad_pixels(bpfile); if (dark_frame) subtract(dark_frame); quality = 2 + !fuji_width; if (user_qual >= 0) quality = user_qual; i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; i = cblack[6]; FORC(cblack[4] * cblack[5]) if (i > cblack[6 + c]) i = cblack[6 + c]; FORC(cblack[4] * cblack[5]) cblack[6 + c] -= i; black += i; if (user_black >= 0) black = user_black; FORC4 cblack[c] += black; if (user_sat > 0) maximum = user_sat; #ifdef COLORCHECK colorcheck(); #endif if (is_foveon) { if (document_mode || load_raw == &CLASS foveon_dp_load_raw) { for (i = 0; i < height * width * 4; i++) if ((short)image[0][i] < 0) image[0][i] = 0; } else foveon_interpolate(); } else if (document_mode < 2) scale_colors(); pre_interpolate(); if (filters && !document_mode) { if (quality == 0) lin_interpolate(); else if (quality == 1 || colors > 3) vng_interpolate(); else if (quality == 2 && filters > 1000) ppg_interpolate(); else if (filters == 9) xtrans_interpolate(quality * 2 - 3); else ahd_interpolate(); } if (mix_green) for (colors = 3, i = 0; i < height * width; i++) image[i][1] = (image[i][1] + image[i][3]) >> 1; if (!is_foveon && colors == 3) median_filter(); if (!is_foveon && highlight == 2) blend_highlights(); if (!is_foveon && highlight > 2) recover_highlights(); if (use_fuji_rotate) fuji_rotate(); #ifndef NO_LCMS if (cam_profile) apply_profile(cam_profile, out_profile); #endif convert_to_rgb(); if (use_fuji_rotate) stretch(); thumbnail: if (write_fun == &CLASS jpeg_thumb) write_ext = ".jpg"; else if (output_tiff && write_fun == &CLASS write_ppm_tiff) write_ext = ".tiff"; else write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors * 5 - 5; ofname = (char *)malloc(strlen(ifname) + 64); merror(ofname, "main()"); if (write_to_stdout) strcpy(ofname, _("standard output")); else { strcpy(ofname, ifname); if ((cp = strrchr(ofname, '.'))) *cp = 0; if (multi_out) sprintf(ofname + strlen(ofname), "_%0*d", snprintf(0, 0, "%d", is_raw - 1), shot_select); if (thumbnail_only) strcat(ofname, ".thumb"); strcat(ofname, write_ext); ofp = fopen(ofname, "wb"); if (!ofp) { status = 1; perror(ofname); goto cleanup; } } if (verbose) fprintf(stderr, _("Writing data to %s ...\n"), ofname); (*write_fun)(); fclose(ifp); if (ofp != stdout) fclose(ofp); cleanup: if (meta_data) free(meta_data); if (ofname) free(ofname); if (oprof) free(oprof); if (image) free(image); if (multi_out) { if (++shot_select < is_raw) arg--; else shot_select = 0; } } return status; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_2946_0
crossvul-cpp_data_good_2666_0
/* NetBSD: print-juniper.c,v 1.2 2007/07/24 11:53:45 drochner Exp */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: DLT_JUNIPER_* printers */ #ifndef lint #else __RCSID("NetBSD: print-juniper.c,v 1.3 2007/07/25 06:31:32 dogcow Exp "); #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ppp.h" #include "llc.h" #include "nlpid.h" #include "ethertype.h" #include "atm.h" #define JUNIPER_BPF_OUT 0 /* Outgoing packet */ #define JUNIPER_BPF_IN 1 /* Incoming packet */ #define JUNIPER_BPF_PKT_IN 0x1 /* Incoming packet */ #define JUNIPER_BPF_NO_L2 0x2 /* L2 header stripped */ #define JUNIPER_BPF_IIF 0x4 /* IIF is valid */ #define JUNIPER_BPF_FILTER 0x40 /* BPF filtering is supported */ #define JUNIPER_BPF_EXT 0x80 /* extensions present */ #define JUNIPER_MGC_NUMBER 0x4d4743 /* = "MGC" */ #define JUNIPER_LSQ_COOKIE_RE (1 << 3) #define JUNIPER_LSQ_COOKIE_DIR (1 << 2) #define JUNIPER_LSQ_L3_PROTO_SHIFT 4 #define JUNIPER_LSQ_L3_PROTO_MASK (0x17 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV4 (0 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV6 (1 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_MPLS (2 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_ISO (3 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define AS_PIC_COOKIE_LEN 8 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE 1 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE 2 #define JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE 3 #define JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE 4 #define JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE 5 static const struct tok juniper_ipsec_type_values[] = { { JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE, "ESP ENCR-AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE, "ESP ENCR-AH AUTH" }, { JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE, "ESP AUTH" }, { JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE, "AH AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE, "ESP ENCR" }, { 0, NULL} }; static const struct tok juniper_direction_values[] = { { JUNIPER_BPF_IN, "In"}, { JUNIPER_BPF_OUT, "Out"}, { 0, NULL} }; /* codepoints for encoding extensions to a .pcap file */ enum { JUNIPER_EXT_TLV_IFD_IDX = 1, JUNIPER_EXT_TLV_IFD_NAME = 2, JUNIPER_EXT_TLV_IFD_MEDIATYPE = 3, JUNIPER_EXT_TLV_IFL_IDX = 4, JUNIPER_EXT_TLV_IFL_UNIT = 5, JUNIPER_EXT_TLV_IFL_ENCAPS = 6, JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE = 7, JUNIPER_EXT_TLV_TTP_IFL_ENCAPS = 8 }; /* 1 byte type and 1-byte length */ #define JUNIPER_EXT_TLV_OVERHEAD 2U static const struct tok jnx_ext_tlv_values[] = { { JUNIPER_EXT_TLV_IFD_IDX, "Device Interface Index" }, { JUNIPER_EXT_TLV_IFD_NAME,"Device Interface Name" }, { JUNIPER_EXT_TLV_IFD_MEDIATYPE, "Device Media Type" }, { JUNIPER_EXT_TLV_IFL_IDX, "Logical Interface Index" }, { JUNIPER_EXT_TLV_IFL_UNIT,"Logical Unit Number" }, { JUNIPER_EXT_TLV_IFL_ENCAPS, "Logical Interface Encapsulation" }, { JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE, "TTP derived Device Media Type" }, { JUNIPER_EXT_TLV_TTP_IFL_ENCAPS, "TTP derived Logical Interface Encapsulation" }, { 0, NULL } }; static const struct tok jnx_flag_values[] = { { JUNIPER_BPF_EXT, "Ext" }, { JUNIPER_BPF_FILTER, "Filter" }, { JUNIPER_BPF_IIF, "IIF" }, { JUNIPER_BPF_NO_L2, "no-L2" }, { JUNIPER_BPF_PKT_IN, "In" }, { 0, NULL } }; #define JUNIPER_IFML_ETHER 1 #define JUNIPER_IFML_FDDI 2 #define JUNIPER_IFML_TOKENRING 3 #define JUNIPER_IFML_PPP 4 #define JUNIPER_IFML_FRAMERELAY 5 #define JUNIPER_IFML_CISCOHDLC 6 #define JUNIPER_IFML_SMDSDXI 7 #define JUNIPER_IFML_ATMPVC 8 #define JUNIPER_IFML_PPP_CCC 9 #define JUNIPER_IFML_FRAMERELAY_CCC 10 #define JUNIPER_IFML_IPIP 11 #define JUNIPER_IFML_GRE 12 #define JUNIPER_IFML_PIM 13 #define JUNIPER_IFML_PIMD 14 #define JUNIPER_IFML_CISCOHDLC_CCC 15 #define JUNIPER_IFML_VLAN_CCC 16 #define JUNIPER_IFML_MLPPP 17 #define JUNIPER_IFML_MLFR 18 #define JUNIPER_IFML_ML 19 #define JUNIPER_IFML_LSI 20 #define JUNIPER_IFML_DFE 21 #define JUNIPER_IFML_ATM_CELLRELAY_CCC 22 #define JUNIPER_IFML_CRYPTO 23 #define JUNIPER_IFML_GGSN 24 #define JUNIPER_IFML_LSI_PPP 25 #define JUNIPER_IFML_LSI_CISCOHDLC 26 #define JUNIPER_IFML_PPP_TCC 27 #define JUNIPER_IFML_FRAMERELAY_TCC 28 #define JUNIPER_IFML_CISCOHDLC_TCC 29 #define JUNIPER_IFML_ETHERNET_CCC 30 #define JUNIPER_IFML_VT 31 #define JUNIPER_IFML_EXTENDED_VLAN_CCC 32 #define JUNIPER_IFML_ETHER_OVER_ATM 33 #define JUNIPER_IFML_MONITOR 34 #define JUNIPER_IFML_ETHERNET_TCC 35 #define JUNIPER_IFML_VLAN_TCC 36 #define JUNIPER_IFML_EXTENDED_VLAN_TCC 37 #define JUNIPER_IFML_CONTROLLER 38 #define JUNIPER_IFML_MFR 39 #define JUNIPER_IFML_LS 40 #define JUNIPER_IFML_ETHERNET_VPLS 41 #define JUNIPER_IFML_ETHERNET_VLAN_VPLS 42 #define JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS 43 #define JUNIPER_IFML_LT 44 #define JUNIPER_IFML_SERVICES 45 #define JUNIPER_IFML_ETHER_VPLS_OVER_ATM 46 #define JUNIPER_IFML_FR_PORT_CCC 47 #define JUNIPER_IFML_FRAMERELAY_EXT_CCC 48 #define JUNIPER_IFML_FRAMERELAY_EXT_TCC 49 #define JUNIPER_IFML_FRAMERELAY_FLEX 50 #define JUNIPER_IFML_GGSNI 51 #define JUNIPER_IFML_ETHERNET_FLEX 52 #define JUNIPER_IFML_COLLECTOR 53 #define JUNIPER_IFML_AGGREGATOR 54 #define JUNIPER_IFML_LAPD 55 #define JUNIPER_IFML_PPPOE 56 #define JUNIPER_IFML_PPP_SUBORDINATE 57 #define JUNIPER_IFML_CISCOHDLC_SUBORDINATE 58 #define JUNIPER_IFML_DFC 59 #define JUNIPER_IFML_PICPEER 60 static const struct tok juniper_ifmt_values[] = { { JUNIPER_IFML_ETHER, "Ethernet" }, { JUNIPER_IFML_FDDI, "FDDI" }, { JUNIPER_IFML_TOKENRING, "Token-Ring" }, { JUNIPER_IFML_PPP, "PPP" }, { JUNIPER_IFML_PPP_SUBORDINATE, "PPP-Subordinate" }, { JUNIPER_IFML_FRAMERELAY, "Frame-Relay" }, { JUNIPER_IFML_CISCOHDLC, "Cisco-HDLC" }, { JUNIPER_IFML_SMDSDXI, "SMDS-DXI" }, { JUNIPER_IFML_ATMPVC, "ATM-PVC" }, { JUNIPER_IFML_PPP_CCC, "PPP-CCC" }, { JUNIPER_IFML_FRAMERELAY_CCC, "Frame-Relay-CCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_CCC, "Extended FR-CCC" }, { JUNIPER_IFML_IPIP, "IP-over-IP" }, { JUNIPER_IFML_GRE, "GRE" }, { JUNIPER_IFML_PIM, "PIM-Encapsulator" }, { JUNIPER_IFML_PIMD, "PIM-Decapsulator" }, { JUNIPER_IFML_CISCOHDLC_CCC, "Cisco-HDLC-CCC" }, { JUNIPER_IFML_VLAN_CCC, "VLAN-CCC" }, { JUNIPER_IFML_EXTENDED_VLAN_CCC, "Extended-VLAN-CCC" }, { JUNIPER_IFML_MLPPP, "Multilink-PPP" }, { JUNIPER_IFML_MLFR, "Multilink-FR" }, { JUNIPER_IFML_MFR, "Multilink-FR-UNI-NNI" }, { JUNIPER_IFML_ML, "Multilink" }, { JUNIPER_IFML_LS, "LinkService" }, { JUNIPER_IFML_LSI, "LSI" }, { JUNIPER_IFML_ATM_CELLRELAY_CCC, "ATM-CCC-Cell-Relay" }, { JUNIPER_IFML_CRYPTO, "IPSEC-over-IP" }, { JUNIPER_IFML_GGSN, "GGSN" }, { JUNIPER_IFML_PPP_TCC, "PPP-TCC" }, { JUNIPER_IFML_FRAMERELAY_TCC, "Frame-Relay-TCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_TCC, "Extended FR-TCC" }, { JUNIPER_IFML_CISCOHDLC_TCC, "Cisco-HDLC-TCC" }, { JUNIPER_IFML_ETHERNET_CCC, "Ethernet-CCC" }, { JUNIPER_IFML_VT, "VPN-Loopback-tunnel" }, { JUNIPER_IFML_ETHER_OVER_ATM, "Ethernet-over-ATM" }, { JUNIPER_IFML_ETHER_VPLS_OVER_ATM, "Ethernet-VPLS-over-ATM" }, { JUNIPER_IFML_MONITOR, "Monitor" }, { JUNIPER_IFML_ETHERNET_TCC, "Ethernet-TCC" }, { JUNIPER_IFML_VLAN_TCC, "VLAN-TCC" }, { JUNIPER_IFML_EXTENDED_VLAN_TCC, "Extended-VLAN-TCC" }, { JUNIPER_IFML_CONTROLLER, "Controller" }, { JUNIPER_IFML_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFML_ETHERNET_VLAN_VPLS, "VLAN-VPLS" }, { JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS, "Extended-VLAN-VPLS" }, { JUNIPER_IFML_LT, "Logical-tunnel" }, { JUNIPER_IFML_SERVICES, "General-Services" }, { JUNIPER_IFML_PPPOE, "PPPoE" }, { JUNIPER_IFML_ETHERNET_FLEX, "Flexible-Ethernet-Services" }, { JUNIPER_IFML_FRAMERELAY_FLEX, "Flexible-FrameRelay" }, { JUNIPER_IFML_COLLECTOR, "Flow-collection" }, { JUNIPER_IFML_PICPEER, "PIC Peer" }, { JUNIPER_IFML_DFC, "Dynamic-Flow-Capture" }, {0, NULL} }; #define JUNIPER_IFLE_ATM_SNAP 2 #define JUNIPER_IFLE_ATM_NLPID 3 #define JUNIPER_IFLE_ATM_VCMUX 4 #define JUNIPER_IFLE_ATM_LLC 5 #define JUNIPER_IFLE_ATM_PPP_VCMUX 6 #define JUNIPER_IFLE_ATM_PPP_LLC 7 #define JUNIPER_IFLE_ATM_PPP_FUNI 8 #define JUNIPER_IFLE_ATM_CCC 9 #define JUNIPER_IFLE_FR_NLPID 10 #define JUNIPER_IFLE_FR_SNAP 11 #define JUNIPER_IFLE_FR_PPP 12 #define JUNIPER_IFLE_FR_CCC 13 #define JUNIPER_IFLE_ENET2 14 #define JUNIPER_IFLE_IEEE8023_SNAP 15 #define JUNIPER_IFLE_IEEE8023_LLC 16 #define JUNIPER_IFLE_PPP 17 #define JUNIPER_IFLE_CISCOHDLC 18 #define JUNIPER_IFLE_PPP_CCC 19 #define JUNIPER_IFLE_IPIP_NULL 20 #define JUNIPER_IFLE_PIM_NULL 21 #define JUNIPER_IFLE_GRE_NULL 22 #define JUNIPER_IFLE_GRE_PPP 23 #define JUNIPER_IFLE_PIMD_DECAPS 24 #define JUNIPER_IFLE_CISCOHDLC_CCC 25 #define JUNIPER_IFLE_ATM_CISCO_NLPID 26 #define JUNIPER_IFLE_VLAN_CCC 27 #define JUNIPER_IFLE_MLPPP 28 #define JUNIPER_IFLE_MLFR 29 #define JUNIPER_IFLE_LSI_NULL 30 #define JUNIPER_IFLE_AGGREGATE_UNUSED 31 #define JUNIPER_IFLE_ATM_CELLRELAY_CCC 32 #define JUNIPER_IFLE_CRYPTO 33 #define JUNIPER_IFLE_GGSN 34 #define JUNIPER_IFLE_ATM_TCC 35 #define JUNIPER_IFLE_FR_TCC 36 #define JUNIPER_IFLE_PPP_TCC 37 #define JUNIPER_IFLE_CISCOHDLC_TCC 38 #define JUNIPER_IFLE_ETHERNET_CCC 39 #define JUNIPER_IFLE_VT 40 #define JUNIPER_IFLE_ATM_EOA_LLC 41 #define JUNIPER_IFLE_EXTENDED_VLAN_CCC 42 #define JUNIPER_IFLE_ATM_SNAP_TCC 43 #define JUNIPER_IFLE_MONITOR 44 #define JUNIPER_IFLE_ETHERNET_TCC 45 #define JUNIPER_IFLE_VLAN_TCC 46 #define JUNIPER_IFLE_EXTENDED_VLAN_TCC 47 #define JUNIPER_IFLE_MFR 48 #define JUNIPER_IFLE_ETHERNET_VPLS 49 #define JUNIPER_IFLE_ETHERNET_VLAN_VPLS 50 #define JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS 51 #define JUNIPER_IFLE_SERVICES 52 #define JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC 53 #define JUNIPER_IFLE_FR_PORT_CCC 54 #define JUNIPER_IFLE_ATM_MLPPP_LLC 55 #define JUNIPER_IFLE_ATM_EOA_CCC 56 #define JUNIPER_IFLE_LT_VLAN 57 #define JUNIPER_IFLE_COLLECTOR 58 #define JUNIPER_IFLE_AGGREGATOR 59 #define JUNIPER_IFLE_LAPD 60 #define JUNIPER_IFLE_ATM_PPPOE_LLC 61 #define JUNIPER_IFLE_ETHERNET_PPPOE 62 #define JUNIPER_IFLE_PPPOE 63 #define JUNIPER_IFLE_PPP_SUBORDINATE 64 #define JUNIPER_IFLE_CISCOHDLC_SUBORDINATE 65 #define JUNIPER_IFLE_DFC 66 #define JUNIPER_IFLE_PICPEER 67 static const struct tok juniper_ifle_values[] = { { JUNIPER_IFLE_AGGREGATOR, "Aggregator" }, { JUNIPER_IFLE_ATM_CCC, "CCC over ATM" }, { JUNIPER_IFLE_ATM_CELLRELAY_CCC, "ATM CCC Cell Relay" }, { JUNIPER_IFLE_ATM_CISCO_NLPID, "CISCO compatible NLPID" }, { JUNIPER_IFLE_ATM_EOA_CCC, "Ethernet over ATM CCC" }, { JUNIPER_IFLE_ATM_EOA_LLC, "Ethernet over ATM LLC" }, { JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC, "Ethernet VPLS over ATM LLC" }, { JUNIPER_IFLE_ATM_LLC, "ATM LLC" }, { JUNIPER_IFLE_ATM_MLPPP_LLC, "MLPPP over ATM LLC" }, { JUNIPER_IFLE_ATM_NLPID, "ATM NLPID" }, { JUNIPER_IFLE_ATM_PPPOE_LLC, "PPPoE over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_FUNI, "PPP over FUNI" }, { JUNIPER_IFLE_ATM_PPP_LLC, "PPP over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_VCMUX, "PPP over ATM VCMUX" }, { JUNIPER_IFLE_ATM_SNAP, "ATM SNAP" }, { JUNIPER_IFLE_ATM_SNAP_TCC, "ATM SNAP TCC" }, { JUNIPER_IFLE_ATM_TCC, "ATM VCMUX TCC" }, { JUNIPER_IFLE_ATM_VCMUX, "ATM VCMUX" }, { JUNIPER_IFLE_CISCOHDLC, "C-HDLC" }, { JUNIPER_IFLE_CISCOHDLC_CCC, "C-HDLC CCC" }, { JUNIPER_IFLE_CISCOHDLC_SUBORDINATE, "C-HDLC via dialer" }, { JUNIPER_IFLE_CISCOHDLC_TCC, "C-HDLC TCC" }, { JUNIPER_IFLE_COLLECTOR, "Collector" }, { JUNIPER_IFLE_CRYPTO, "Crypto" }, { JUNIPER_IFLE_ENET2, "Ethernet" }, { JUNIPER_IFLE_ETHERNET_CCC, "Ethernet CCC" }, { JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS, "Extended VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_PPPOE, "PPPoE over Ethernet" }, { JUNIPER_IFLE_ETHERNET_TCC, "Ethernet TCC" }, { JUNIPER_IFLE_ETHERNET_VLAN_VPLS, "VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFLE_EXTENDED_VLAN_CCC, "Extended VLAN CCC" }, { JUNIPER_IFLE_EXTENDED_VLAN_TCC, "Extended VLAN TCC" }, { JUNIPER_IFLE_FR_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_NLPID, "FR NLPID" }, { JUNIPER_IFLE_FR_PORT_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_PPP, "FR PPP" }, { JUNIPER_IFLE_FR_SNAP, "FR SNAP" }, { JUNIPER_IFLE_FR_TCC, "FR TCC" }, { JUNIPER_IFLE_GGSN, "GGSN" }, { JUNIPER_IFLE_GRE_NULL, "GRE NULL" }, { JUNIPER_IFLE_GRE_PPP, "PPP over GRE" }, { JUNIPER_IFLE_IPIP_NULL, "IPIP" }, { JUNIPER_IFLE_LAPD, "LAPD" }, { JUNIPER_IFLE_LSI_NULL, "LSI Null" }, { JUNIPER_IFLE_LT_VLAN, "LT VLAN" }, { JUNIPER_IFLE_MFR, "MFR" }, { JUNIPER_IFLE_MLFR, "MLFR" }, { JUNIPER_IFLE_MLPPP, "MLPPP" }, { JUNIPER_IFLE_MONITOR, "Monitor" }, { JUNIPER_IFLE_PIMD_DECAPS, "PIMd" }, { JUNIPER_IFLE_PIM_NULL, "PIM Null" }, { JUNIPER_IFLE_PPP, "PPP" }, { JUNIPER_IFLE_PPPOE, "PPPoE" }, { JUNIPER_IFLE_PPP_CCC, "PPP CCC" }, { JUNIPER_IFLE_PPP_SUBORDINATE, "" }, { JUNIPER_IFLE_PPP_TCC, "PPP TCC" }, { JUNIPER_IFLE_SERVICES, "General Services" }, { JUNIPER_IFLE_VLAN_CCC, "VLAN CCC" }, { JUNIPER_IFLE_VLAN_TCC, "VLAN TCC" }, { JUNIPER_IFLE_VT, "VT" }, {0, NULL} }; struct juniper_cookie_table_t { uint32_t pictype; /* pic type */ uint8_t cookie_len; /* cookie len */ const char *s; /* pic name */ }; static const struct juniper_cookie_table_t juniper_cookie_table[] = { #ifdef DLT_JUNIPER_ATM1 { DLT_JUNIPER_ATM1, 4, "ATM1"}, #endif #ifdef DLT_JUNIPER_ATM2 { DLT_JUNIPER_ATM2, 8, "ATM2"}, #endif #ifdef DLT_JUNIPER_MLPPP { DLT_JUNIPER_MLPPP, 2, "MLPPP"}, #endif #ifdef DLT_JUNIPER_MLFR { DLT_JUNIPER_MLFR, 2, "MLFR"}, #endif #ifdef DLT_JUNIPER_MFR { DLT_JUNIPER_MFR, 4, "MFR"}, #endif #ifdef DLT_JUNIPER_PPPOE { DLT_JUNIPER_PPPOE, 0, "PPPoE"}, #endif #ifdef DLT_JUNIPER_PPPOE_ATM { DLT_JUNIPER_PPPOE_ATM, 0, "PPPoE ATM"}, #endif #ifdef DLT_JUNIPER_GGSN { DLT_JUNIPER_GGSN, 8, "GGSN"}, #endif #ifdef DLT_JUNIPER_MONITOR { DLT_JUNIPER_MONITOR, 8, "MONITOR"}, #endif #ifdef DLT_JUNIPER_SERVICES { DLT_JUNIPER_SERVICES, 8, "AS"}, #endif #ifdef DLT_JUNIPER_ES { DLT_JUNIPER_ES, 0, "ES"}, #endif { 0, 0, NULL } }; struct juniper_l2info_t { uint32_t length; uint32_t caplen; uint32_t pictype; uint8_t direction; uint8_t header_len; uint8_t cookie_len; uint8_t cookie_type; uint8_t cookie[8]; uint8_t bundle; uint16_t proto; uint8_t flags; }; #define LS_COOKIE_ID 0x54 #define AS_COOKIE_ID 0x47 #define LS_MLFR_COOKIE_LEN 4 #define ML_MLFR_COOKIE_LEN 2 #define LS_MFR_COOKIE_LEN 6 #define ATM1_COOKIE_LEN 4 #define ATM2_COOKIE_LEN 8 #define ATM2_PKT_TYPE_MASK 0x70 #define ATM2_GAP_COUNT_MASK 0x3F #define JUNIPER_PROTO_NULL 1 #define JUNIPER_PROTO_IPV4 2 #define JUNIPER_PROTO_IPV6 6 #define MFR_BE_MASK 0xc0 static const struct tok juniper_protocol_values[] = { { JUNIPER_PROTO_NULL, "Null" }, { JUNIPER_PROTO_IPV4, "IPv4" }, { JUNIPER_PROTO_IPV6, "IPv6" }, { 0, NULL} }; static int ip_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_ppp_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_parse_header(netdissect_options *, const u_char *, const struct pcap_pkthdr *, struct juniper_l2info_t *); #ifdef DLT_JUNIPER_GGSN u_int juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; ND_TCHECK(*gh); if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ES u_int juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; ND_TCHECK(*ih); switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MONITOR u_int juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; ND_TCHECK(*mh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_SERVICES u_int juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; ND_TCHECK(*sh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE u_int juniper_pppoe_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPPOE; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ETHER u_int juniper_ether_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ETHER; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw Ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPP u_int juniper_ppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ppp frames */ ppp_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_FRELAY u_int juniper_frelay_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_FRELAY; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw frame-relay frames */ fr_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_CHDLC u_int juniper_chdlc_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_CHDLC; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw c-hdlc frames */ chdlc_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE_ATM u_int juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ND_TCHECK2(p[0], 2); extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_pppoe_atm]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLPPP u_int juniper_mlppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLPPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link * best indicator if the cookie looks like a proto */ if (ndo->ndo_eflag && EXTRACT_16BITS(&l2info.cookie) != PPP_OSI && EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL)) ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle)); p+=l2info.header_len; /* first try the LSQ protos */ switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: /* IP traffic going to the RE would not have a cookie * -> this must be incoming IS-IS over PPP */ if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR)) ppp_print(ndo, p, l2info.length); else ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } /* zero length cookie ? */ switch (EXTRACT_16BITS(&l2info.cookie)) { case PPP_OSI: ppp_print(ndo, p - 2, l2info.length + 2); break; case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */ default: ppp_print(ndo, p, l2info.length); break; } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MFR u_int juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLFR u_int juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif /* * ATM1 PIC cookie format * * +-----+-------------------------+-------------------------------+ * |fmtid| vc index | channel ID | * +-----+-------------------------+-------------------------------+ */ #ifdef DLT_JUNIPER_ATM1 u_int juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } ND_TCHECK2(p[0], 3); if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_atm1]")); return l2info.header_len; } #endif /* * ATM2 PIC cookie format * * +-------------------------------+---------+---+-----+-----------+ * | channel ID | reserv |AAL| CCRQ| gap cnt | * +-------------------------------+---------+---+-----+-----------+ */ #ifdef DLT_JUNIPER_ATM2 u_int juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } ND_TCHECK2(p[0], 3); if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_atm2]")); return l2info.header_len; } #endif /* try to guess, based on all PPP protos that are supported in * a juniper router if the payload data is encapsulated using PPP */ static int juniper_ppp_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(EXTRACT_16BITS(p)) { case PPP_IP : case PPP_OSI : case PPP_MPLS_UCAST : case PPP_MPLS_MCAST : case PPP_IPCP : case PPP_OSICP : case PPP_MPLSCP : case PPP_LCP : case PPP_PAP : case PPP_CHAP : case PPP_ML : case PPP_IPV6 : case PPP_IPV6CP : ppp_print(ndo, p, length); break; default: return 0; /* did not find a ppp header */ break; } return 1; /* we printed a ppp packet */ } static int ip_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(p[0]) { case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: ip_print(ndo, p, length); break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: ip6_print(ndo, p, length); break; default: return 0; /* did not find a ip header */ break; } return 1; /* we printed an v4/v6 packet */ } static int juniper_read_tlv_value(const u_char *p, u_int tlv_type, u_int tlv_len) { int tlv_value; /* TLVs < 128 are little endian encoded */ if (tlv_type < 128) { switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_LE_16BITS(p); break; case 3: tlv_value = EXTRACT_LE_24BITS(p); break; case 4: tlv_value = EXTRACT_LE_32BITS(p); break; default: tlv_value = -1; break; } } else { /* TLVs >= 128 are big endian encoded */ switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_16BITS(p); break; case 3: tlv_value = EXTRACT_24BITS(p); break; case 4: tlv_value = EXTRACT_32BITS(p); break; default: tlv_value = -1; break; } } return tlv_value; } static int juniper_parse_header(netdissect_options *ndo, const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info) { const struct juniper_cookie_table_t *lp = juniper_cookie_table; u_int idx, jnx_ext_len, jnx_header_len = 0; uint8_t tlv_type,tlv_len; uint32_t control_word; int tlv_value; const u_char *tptr; l2info->header_len = 0; l2info->cookie_len = 0; l2info->proto = 0; l2info->length = h->len; l2info->caplen = h->caplen; ND_TCHECK2(p[0], 4); l2info->flags = p[3]; l2info->direction = p[3]&JUNIPER_BPF_PKT_IN; if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */ ND_PRINT((ndo, "no magic-number found!")); return 0; } if (ndo->ndo_eflag) /* print direction */ ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction))); /* magic number + flags */ jnx_header_len = 4; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]", bittok2str(jnx_flag_values, "none", l2info->flags))); /* extensions present ? - calculate how much bytes to skip */ if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) { tptr = p+jnx_header_len; /* ok to read extension length ? */ ND_TCHECK2(tptr[0], 2); jnx_ext_len = EXTRACT_16BITS(tptr); jnx_header_len += 2; tptr +=2; /* nail up the total length - * just in case something goes wrong * with TLV parsing */ jnx_header_len += jnx_ext_len; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len)); ND_TCHECK2(tptr[0], jnx_ext_len); while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) { tlv_type = *(tptr++); tlv_len = *(tptr++); tlv_value = 0; /* sanity checks */ if (tlv_type == 0 || tlv_len == 0) break; if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len) goto trunc; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ", tok2str(jnx_ext_tlv_values,"Unknown",tlv_type), tlv_type, tlv_len)); tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len); switch (tlv_type) { case JUNIPER_EXT_TLV_IFD_NAME: /* FIXME */ break; case JUNIPER_EXT_TLV_IFD_MEDIATYPE: case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifmt_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_ENCAPS: case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifle_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */ case JUNIPER_EXT_TLV_IFL_UNIT: case JUNIPER_EXT_TLV_IFD_IDX: default: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%u", tlv_value)); } break; } tptr+=tlv_len; jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD; } if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); } if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) { if (ndo->ndo_eflag) ND_PRINT((ndo, "no-L2-hdr, ")); /* there is no link-layer present - * perform the v4/v6 heuristics * to figure out what it is */ ND_TCHECK2(p[jnx_header_len + 4], 1); if (ip_heuristic_guess(ndo, p + jnx_header_len + 4, l2info->length - (jnx_header_len + 4)) == 0) ND_PRINT((ndo, "no IP-hdr found!")); l2info->header_len=jnx_header_len+4; return 0; /* stop parsing the output further */ } l2info->header_len = jnx_header_len; p+=l2info->header_len; l2info->length -= l2info->header_len; l2info->caplen -= l2info->header_len; /* search through the cookie table and copy values matching for our PIC type */ ND_TCHECK(p[0]); while (lp->s != NULL) { if (lp->pictype == l2info->pictype) { l2info->cookie_len += lp->cookie_len; switch (p[0]) { case LS_COOKIE_ID: l2info->cookie_type = LS_COOKIE_ID; l2info->cookie_len += 2; break; case AS_COOKIE_ID: l2info->cookie_type = AS_COOKIE_ID; l2info->cookie_len = 8; break; default: l2info->bundle = l2info->cookie[0]; break; } #ifdef DLT_JUNIPER_MFR /* MFR child links don't carry cookies */ if (l2info->pictype == DLT_JUNIPER_MFR && (p[0] & MFR_BE_MASK) == MFR_BE_MASK) { l2info->cookie_len = 0; } #endif l2info->header_len += l2info->cookie_len; l2info->length -= l2info->cookie_len; l2info->caplen -= l2info->cookie_len; if (ndo->ndo_eflag) ND_PRINT((ndo, "%s-PIC, cookie-len %u", lp->s, l2info->cookie_len)); if (l2info->cookie_len > 0) { ND_TCHECK2(p[0], l2info->cookie_len); if (ndo->ndo_eflag) ND_PRINT((ndo, ", cookie 0x")); for (idx = 0; idx < l2info->cookie_len; idx++) { l2info->cookie[idx] = p[idx]; /* copy cookie data */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx])); } } if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/ l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len); break; } ++lp; } p+=l2info->cookie_len; /* DLT_ specific parsing */ switch(l2info->pictype) { #ifdef DLT_JUNIPER_MLPPP case DLT_JUNIPER_MLPPP: switch (l2info->cookie_type) { case LS_COOKIE_ID: l2info->bundle = l2info->cookie[1]; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_MLFR case DLT_JUNIPER_MLFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: ND_TCHECK2(p[0], 2); l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; } break; #endif #ifdef DLT_JUNIPER_MFR case DLT_JUNIPER_MFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: ND_TCHECK2(p[0], 2); l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_ATM2 case DLT_JUNIPER_ATM2: ND_TCHECK2(p[0], 4); /* ATM cell relay control word present ? */ if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) { control_word = EXTRACT_32BITS(p); /* some control word heuristics */ switch(control_word) { case 0: /* zero control word */ case 0x08000000: /* < JUNOS 7.4 control-word */ case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/ l2info->header_len += 4; break; default: break; } if (ndo->ndo_eflag) ND_PRINT((ndo, "control-word 0x%08x ", control_word)); } break; #endif #ifdef DLT_JUNIPER_GGSN case DLT_JUNIPER_GGSN: break; #endif #ifdef DLT_JUNIPER_ATM1 case DLT_JUNIPER_ATM1: break; #endif #ifdef DLT_JUNIPER_PPP case DLT_JUNIPER_PPP: break; #endif #ifdef DLT_JUNIPER_CHDLC case DLT_JUNIPER_CHDLC: break; #endif #ifdef DLT_JUNIPER_ETHER case DLT_JUNIPER_ETHER: break; #endif #ifdef DLT_JUNIPER_FRELAY case DLT_JUNIPER_FRELAY: break; #endif default: ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype)); break; } if (ndo->ndo_eflag > 1) ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto)); return 1; /* everything went ok so far. continue parsing */ trunc: ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len)); return 0; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2666_0
crossvul-cpp_data_bad_391_0
/* * Copyright (c) 2008-2017 Nicira, Inc. * * 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 <config.h> #include <netinet/in.h> #include "bundle.h" #include "byte-order.h" #include "colors.h" #include "compiler.h" #include "dummy.h" #include "openvswitch/hmap.h" #include "learn.h" #include "multipath.h" #include "nx-match.h" #include "odp-netlink.h" #include "openvswitch/dynamic-string.h" #include "openvswitch/meta-flow.h" #include "openvswitch/ofp-actions.h" #include "openvswitch/ofp-util.h" #include "openvswitch/ofp-parse.h" #include "openvswitch/ofp-prop.h" #include "openvswitch/ofpbuf.h" #include "openvswitch/vlog.h" #include "unaligned.h" #include "util.h" #include "vl-mff-map.h" VLOG_DEFINE_THIS_MODULE(ofp_actions); static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5); struct ofp_action_header; /* Header for Open vSwitch and ONF vendor extension actions. * * This is the entire header for a few Open vSwitch vendor extension actions, * the ones that either have no arguments or for which variable-length * arguments follow the header. * * This cannot be used as an entirely generic vendor extension action header, * because OpenFlow does not specify the location or size of the action * subtype; it just happens that ONF extensions and Nicira extensions share * this format. */ struct ext_action_header { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 16. */ ovs_be32 vendor; /* NX_VENDOR_ID or ONF_VENDOR_ID. */ ovs_be16 subtype; /* See enum ofp_raw_action_type. */ uint8_t pad[6]; }; OFP_ASSERT(sizeof(struct ext_action_header) == 16); /* Raw identifiers for OpenFlow actions. * * Decoding and encoding OpenFlow actions across multiple versions is difficult * to do in a clean, consistent way. This enumeration lays out all of the * forms of actions that Open vSwitch supports. * * The comments here must follow a stylized form because the * "extract-ofp-actions" program parses them at build time to generate data * tables. * * - The first part of each comment specifies the vendor, OpenFlow versions, * and type for each protocol that supports the action: * * # The vendor is OF for standard OpenFlow actions, NX for Nicira * extension actions. (Support for other vendors can be added, but * it can't be done just based on a vendor ID definition alone * because OpenFlow doesn't define a standard way to specify a * subtype for vendor actions, so other vendors might do it different * from Nicira.) * * # The version can specify a specific OpenFlow version, a version * range delimited by "-", or an open-ended range with "+". * * # The type, in parentheses, is the action type number (for standard * OpenFlow actions) or subtype (for vendor extension actions). * * # Optionally one may add "is deprecated" followed by a * human-readable reason in parentheses (which will be used in log * messages), if a particular action should no longer be used. * * Multiple such specifications may be separated by commas. * * - The second part describes the action's wire format. It may be: * * # "struct <name>": The struct fully specifies the wire format. The * action is exactly the size of the struct. (Thus, the struct must * be an exact multiple of 8 bytes in size.) * * # "struct <name>, ...": The struct specifies the beginning of the * wire format. An instance of the action is either the struct's * exact size, or a multiple of 8 bytes longer. * * # "uint<N>_t" or "ovs_be<N>": The action consists of a (standard or * vendor extension) header, followed by 0 or more pad bytes to align * to a multiple of <N> bits, followed by an argument of the given * type, followed by 0 or more pad bytes to bring the total action up * to a multiple of 8 bytes. * * # "void": The action is just a (standard or vendor extension) * header. * * # Optionally, one may add "VLMFF" in the end of the second part if * the Openflow action may use a variable length meta-flow field * (i.e. tun_metadata). Adding "VLMFF" will pass the per-switch based * variable length meta-flow field mapping map (struct vl_mff_map) to * the corresponding action decoding function. * * - Optional additional text enclosed in square brackets is commentary for * the human reader. */ enum ofp_raw_action_type { /* ## ----------------- ## */ /* ## Standard actions. ## */ /* ## ----------------- ## */ /* OF1.0(0): struct ofp10_action_output. */ OFPAT_RAW10_OUTPUT, /* OF1.1+(0): struct ofp11_action_output. */ OFPAT_RAW11_OUTPUT, /* OF1.0(1): uint16_t. */ OFPAT_RAW10_SET_VLAN_VID, /* OF1.0(2): uint8_t. */ OFPAT_RAW10_SET_VLAN_PCP, /* OF1.1(1), OF1.2+(1) is deprecated (use Set-Field): uint16_t. * * [Semantics differ slightly between the 1.0 and 1.1 versions of the VLAN * modification actions: the 1.0 versions push a VLAN header if none is * present, but the 1.1 versions do not. That is the only reason that we * distinguish their raw action types.] */ OFPAT_RAW11_SET_VLAN_VID, /* OF1.1(2), OF1.2+(2) is deprecated (use Set-Field): uint8_t. */ OFPAT_RAW11_SET_VLAN_PCP, /* OF1.1+(17): ovs_be16. * * [The argument is the Ethertype, e.g. ETH_TYPE_VLAN_8021Q, not the VID or * TCI.] */ OFPAT_RAW11_PUSH_VLAN, /* OF1.0(3): void. */ OFPAT_RAW10_STRIP_VLAN, /* OF1.1+(18): void. */ OFPAT_RAW11_POP_VLAN, /* OF1.0(4), OF1.1(3), OF1.2+(3) is deprecated (use Set-Field): struct * ofp_action_dl_addr. */ OFPAT_RAW_SET_DL_SRC, /* OF1.0(5), OF1.1(4), OF1.2+(4) is deprecated (use Set-Field): struct * ofp_action_dl_addr. */ OFPAT_RAW_SET_DL_DST, /* OF1.0(6), OF1.1(5), OF1.2+(5) is deprecated (use Set-Field): * ovs_be32. */ OFPAT_RAW_SET_NW_SRC, /* OF1.0(7), OF1.1(6), OF1.2+(6) is deprecated (use Set-Field): * ovs_be32. */ OFPAT_RAW_SET_NW_DST, /* OF1.0(8), OF1.1(7), OF1.2+(7) is deprecated (use Set-Field): uint8_t. */ OFPAT_RAW_SET_NW_TOS, /* OF1.1(8), OF1.2+(8) is deprecated (use Set-Field): uint8_t. */ OFPAT_RAW11_SET_NW_ECN, /* OF1.0(9), OF1.1(9), OF1.2+(9) is deprecated (use Set-Field): * ovs_be16. */ OFPAT_RAW_SET_TP_SRC, /* OF1.0(10), OF1.1(10), OF1.2+(10) is deprecated (use Set-Field): * ovs_be16. */ OFPAT_RAW_SET_TP_DST, /* OF1.0(11): struct ofp10_action_enqueue. */ OFPAT_RAW10_ENQUEUE, /* NX1.0(30), OF1.1(13), OF1.2+(13) is deprecated (use Set-Field): * ovs_be32. */ OFPAT_RAW_SET_MPLS_LABEL, /* NX1.0(31), OF1.1(14), OF1.2+(14) is deprecated (use Set-Field): * uint8_t. */ OFPAT_RAW_SET_MPLS_TC, /* NX1.0(25), OF1.1(15), OF1.2+(15) is deprecated (use Set-Field): * uint8_t. */ OFPAT_RAW_SET_MPLS_TTL, /* NX1.0(26), OF1.1+(16): void. */ OFPAT_RAW_DEC_MPLS_TTL, /* NX1.0(23), OF1.1+(19): ovs_be16. * * [The argument is the Ethertype, e.g. ETH_TYPE_MPLS, not the label.] */ OFPAT_RAW_PUSH_MPLS, /* NX1.0(24), OF1.1+(20): ovs_be16. * * [The argument is the Ethertype, e.g. ETH_TYPE_IPV4 if at BoS or * ETH_TYPE_MPLS otherwise, not the label.] */ OFPAT_RAW_POP_MPLS, /* NX1.0(4), OF1.1+(21): uint32_t. */ OFPAT_RAW_SET_QUEUE, /* NX1.0(40), OF1.1+(22): uint32_t. */ OFPAT_RAW_GROUP, /* OF1.1+(23): uint8_t. */ OFPAT_RAW11_SET_NW_TTL, /* NX1.0(18), OF1.1+(24): void. */ OFPAT_RAW_DEC_NW_TTL, /* NX1.0+(21): struct nx_action_cnt_ids, ... */ NXAST_RAW_DEC_TTL_CNT_IDS, /* OF1.2-1.4(25): struct ofp12_action_set_field, ... VLMFF */ OFPAT_RAW12_SET_FIELD, /* OF1.5+(25): struct ofp12_action_set_field, ... VLMFF */ OFPAT_RAW15_SET_FIELD, /* NX1.0-1.4(7): struct nx_action_reg_load. VLMFF * * [In OpenFlow 1.5, set_field is a superset of reg_load functionality, so * we drop reg_load.] */ NXAST_RAW_REG_LOAD, /* NX1.0-1.4(33): struct ext_action_header, ... VLMFF * * [In OpenFlow 1.5, set_field is a superset of reg_load2 functionality, so * we drop reg_load2.] */ NXAST_RAW_REG_LOAD2, /* OF1.5+(28): struct ofp15_action_copy_field, ... VLMFF */ OFPAT_RAW15_COPY_FIELD, /* ONF1.3-1.4(3200): struct onf_action_copy_field, ... VLMFF */ ONFACT_RAW13_COPY_FIELD, /* NX1.0-1.4(6): struct nx_action_reg_move, ... VLMFF */ NXAST_RAW_REG_MOVE, /* ## ------------------------- ## */ /* ## Nicira extension actions. ## */ /* ## ------------------------- ## */ /* Actions similar to standard actions are listed with the standard actions. */ /* NX1.0+(1): uint16_t. */ NXAST_RAW_RESUBMIT, /* NX1.0+(14): struct nx_action_resubmit. */ NXAST_RAW_RESUBMIT_TABLE, /* NX1.0+(2): uint32_t. */ NXAST_RAW_SET_TUNNEL, /* NX1.0+(9): uint64_t. */ NXAST_RAW_SET_TUNNEL64, /* NX1.0+(5): void. */ NXAST_RAW_POP_QUEUE, /* NX1.0+(8): struct nx_action_note, ... */ NXAST_RAW_NOTE, /* NX1.0+(10): struct nx_action_multipath. VLMFF */ NXAST_RAW_MULTIPATH, /* NX1.0+(12): struct nx_action_bundle, ... */ NXAST_RAW_BUNDLE, /* NX1.0+(13): struct nx_action_bundle, ... VLMFF */ NXAST_RAW_BUNDLE_LOAD, /* NX1.0+(15): struct nx_action_output_reg. VLMFF */ NXAST_RAW_OUTPUT_REG, /* NX1.0+(32): struct nx_action_output_reg2. VLMFF */ NXAST_RAW_OUTPUT_REG2, /* NX1.0+(16): struct nx_action_learn, ... VLMFF */ NXAST_RAW_LEARN, /* NX1.0+(17): void. */ NXAST_RAW_EXIT, /* NX1.0+(19): struct nx_action_fin_timeout. */ NXAST_RAW_FIN_TIMEOUT, /* NX1.0+(20): struct nx_action_controller. */ NXAST_RAW_CONTROLLER, /* NX1.0+(37): struct ext_action_header, ... */ NXAST_RAW_CONTROLLER2, /* NX1.0+(22): struct nx_action_write_metadata. */ NXAST_RAW_WRITE_METADATA, /* NX1.0+(27): struct nx_action_stack. VLMFF */ NXAST_RAW_STACK_PUSH, /* NX1.0+(28): struct nx_action_stack. VLMFF */ NXAST_RAW_STACK_POP, /* NX1.0+(29): struct nx_action_sample. */ NXAST_RAW_SAMPLE, /* NX1.0+(38): struct nx_action_sample2. */ NXAST_RAW_SAMPLE2, /* NX1.0+(41): struct nx_action_sample2. */ NXAST_RAW_SAMPLE3, /* NX1.0+(34): struct nx_action_conjunction. */ NXAST_RAW_CONJUNCTION, /* NX1.0+(35): struct nx_action_conntrack, ... VLMFF */ NXAST_RAW_CT, /* NX1.0+(36): struct nx_action_nat, ... */ NXAST_RAW_NAT, /* NX1.0+(39): struct nx_action_output_trunc. */ NXAST_RAW_OUTPUT_TRUNC, /* NX1.0+(42): struct ext_action_header, ... VLMFF */ NXAST_RAW_CLONE, /* NX1.0+(43): void. */ NXAST_RAW_CT_CLEAR, /* ## ------------------ ## */ /* ## Debugging actions. ## */ /* ## ------------------ ## */ /* These are intentionally undocumented, subject to change, and ovs-vswitchd */ /* accepts them only if started with --enable-dummy. */ /* NX1.0+(255): void. */ NXAST_RAW_DEBUG_RECIRC, }; /* OpenFlow actions are always a multiple of 8 bytes in length. */ #define OFP_ACTION_ALIGN 8 /* Define a few functions for working with instructions. */ #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \ static inline const struct STRUCT * OVS_UNUSED \ instruction_get_##ENUM(const struct ofp11_instruction *inst)\ { \ ovs_assert(inst->type == htons(ENUM)); \ return ALIGNED_CAST(struct STRUCT *, inst); \ } \ \ static inline void OVS_UNUSED \ instruction_init_##ENUM(struct STRUCT *s) \ { \ memset(s, 0, sizeof *s); \ s->type = htons(ENUM); \ s->len = htons(sizeof *s); \ } \ \ static inline struct STRUCT * OVS_UNUSED \ instruction_put_##ENUM(struct ofpbuf *buf) \ { \ struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s); \ instruction_init_##ENUM(s); \ return s; \ } OVS_INSTRUCTIONS #undef DEFINE_INST static void ofpacts_update_instruction_actions(struct ofpbuf *openflow, size_t ofs); static void pad_ofpat(struct ofpbuf *openflow, size_t start_ofs); static enum ofperr ofpacts_verify(const struct ofpact[], size_t ofpacts_len, uint32_t allowed_ovsinsts, enum ofpact_type outer_action); static void put_set_field(struct ofpbuf *openflow, enum ofp_version, enum mf_field_id, uint64_t value); static void put_reg_load(struct ofpbuf *openflow, const struct mf_subfield *, uint64_t value); static enum ofperr ofpact_pull_raw(struct ofpbuf *, enum ofp_version, enum ofp_raw_action_type *, uint64_t *arg); static void *ofpact_put_raw(struct ofpbuf *, enum ofp_version, enum ofp_raw_action_type, uint64_t arg); static char *OVS_WARN_UNUSED_RESULT ofpacts_parse( char *str, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols, bool allow_instructions, enum ofpact_type outer_action); static enum ofperr ofpacts_pull_openflow_actions__( struct ofpbuf *openflow, unsigned int actions_len, enum ofp_version version, uint32_t allowed_ovsinsts, struct ofpbuf *ofpacts, enum ofpact_type outer_action, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap); static char * OVS_WARN_UNUSED_RESULT ofpacts_parse_copy( const char *s_, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols, bool allow_instructions, enum ofpact_type outer_action); /* Returns the ofpact following 'ofpact', except that if 'ofpact' contains * nested ofpacts it returns the first one. */ struct ofpact * ofpact_next_flattened(const struct ofpact *ofpact) { switch (ofpact->type) { case OFPACT_OUTPUT: case OFPACT_GROUP: case OFPACT_CONTROLLER: case OFPACT_ENQUEUE: case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_BUNDLE: case OFPACT_SET_FIELD: case OFPACT_SET_VLAN_VID: case OFPACT_SET_VLAN_PCP: case OFPACT_STRIP_VLAN: case OFPACT_PUSH_VLAN: case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: case OFPACT_REG_MOVE: case OFPACT_STACK_PUSH: case OFPACT_STACK_POP: case OFPACT_DEC_TTL: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: case OFPACT_PUSH_MPLS: case OFPACT_POP_MPLS: case OFPACT_SET_TUNNEL: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_FIN_TIMEOUT: case OFPACT_RESUBMIT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_EXIT: case OFPACT_SAMPLE: case OFPACT_UNROLL_XLATE: case OFPACT_CT_CLEAR: case OFPACT_DEBUG_RECIRC: case OFPACT_METER: case OFPACT_CLEAR_ACTIONS: case OFPACT_WRITE_METADATA: case OFPACT_GOTO_TABLE: case OFPACT_NAT: return ofpact_next(ofpact); case OFPACT_CLONE: return ofpact_get_CLONE(ofpact)->actions; case OFPACT_CT: return ofpact_get_CT(ofpact)->actions; case OFPACT_WRITE_ACTIONS: return ofpact_get_WRITE_ACTIONS(ofpact)->actions; } OVS_NOT_REACHED(); } /* Pull off existing actions or instructions. Used by nesting actions to keep * ofpacts_parse() oblivious of actions nesting. * * Push the actions back on after nested parsing, e.g.: * * size_t ofs = ofpacts_pull(ofpacts); * ...nested parsing... * ofpbuf_push_uninit(ofpacts, ofs); */ static size_t ofpacts_pull(struct ofpbuf *ofpacts) { size_t ofs; ofs = ofpacts->size; ofpbuf_pull(ofpacts, ofs); return ofs; } #include "ofp-actions.inc1" /* Output actions. */ /* Action structure for OFPAT10_OUTPUT, which sends packets out 'port'. * When the 'port' is the OFPP_CONTROLLER, 'max_len' indicates the max * number of bytes to send. A 'max_len' of zero means no bytes of the * packet should be sent. */ struct ofp10_action_output { ovs_be16 type; /* OFPAT10_OUTPUT. */ ovs_be16 len; /* Length is 8. */ ovs_be16 port; /* Output port. */ ovs_be16 max_len; /* Max length to send to controller. */ }; OFP_ASSERT(sizeof(struct ofp10_action_output) == 8); /* Action structure for OFPAT_OUTPUT, which sends packets out 'port'. * When the 'port' is the OFPP_CONTROLLER, 'max_len' indicates the max * number of bytes to send. A 'max_len' of zero means no bytes of the * packet should be sent.*/ struct ofp11_action_output { ovs_be16 type; /* OFPAT11_OUTPUT. */ ovs_be16 len; /* Length is 16. */ ovs_be32 port; /* Output port. */ ovs_be16 max_len; /* Max length to send to controller. */ uint8_t pad[6]; /* Pad to 64 bits. */ }; OFP_ASSERT(sizeof(struct ofp11_action_output) == 16); static enum ofperr decode_OFPAT_RAW10_OUTPUT(const struct ofp10_action_output *oao, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_output *output; output = ofpact_put_OUTPUT(out); output->port = u16_to_ofp(ntohs(oao->port)); output->max_len = ntohs(oao->max_len); return ofpact_check_output_port(output->port, OFPP_MAX); } static enum ofperr decode_OFPAT_RAW11_OUTPUT(const struct ofp11_action_output *oao, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_output *output; enum ofperr error; output = ofpact_put_OUTPUT(out); output->max_len = ntohs(oao->max_len); error = ofputil_port_from_ofp11(oao->port, &output->port); if (error) { return error; } return ofpact_check_output_port(output->port, OFPP_MAX); } static void encode_OUTPUT(const struct ofpact_output *output, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { struct ofp10_action_output *oao; oao = put_OFPAT10_OUTPUT(out); oao->port = htons(ofp_to_u16(output->port)); oao->max_len = htons(output->max_len); } else { struct ofp11_action_output *oao; oao = put_OFPAT11_OUTPUT(out); oao->port = ofputil_port_to_ofp11(output->port); oao->max_len = htons(output->max_len); } } static char * OVS_WARN_UNUSED_RESULT parse_truncate_subfield(struct ofpact_output_trunc *output_trunc, const char *arg_) { char *key, *value; char *arg = CONST_CAST(char *, arg_); while (ofputil_parse_key_value(&arg, &key, &value)) { if (!strcmp(key, "port")) { if (!ofputil_port_from_string(value, &output_trunc->port)) { return xasprintf("output to unknown truncate port: %s", value); } if (ofp_to_u16(output_trunc->port) > ofp_to_u16(OFPP_MAX)) { if (output_trunc->port != OFPP_LOCAL && output_trunc->port != OFPP_IN_PORT) return xasprintf("output to unsupported truncate port: %s", value); } } else if (!strcmp(key, "max_len")) { char *err; err = str_to_u32(value, &output_trunc->max_len); if (err) { return err; } } else { return xasprintf("invalid key '%s' in output_trunc argument", key); } } return NULL; } static char * OVS_WARN_UNUSED_RESULT parse_OUTPUT(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { if (strstr(arg, "port") && strstr(arg, "max_len")) { struct ofpact_output_trunc *output_trunc; output_trunc = ofpact_put_OUTPUT_TRUNC(ofpacts); return parse_truncate_subfield(output_trunc, arg); } ofp_port_t port; if (ofputil_port_from_string(arg, &port)) { struct ofpact_output *output = ofpact_put_OUTPUT(ofpacts); output->port = port; output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0; return NULL; } struct mf_subfield src; char *error = mf_parse_subfield(&src, arg); if (!error) { struct ofpact_output_reg *output_reg; output_reg = ofpact_put_OUTPUT_REG(ofpacts); output_reg->max_len = UINT16_MAX; output_reg->src = src; return NULL; } free(error); return xasprintf("%s: output to unknown port", arg); } static void format_OUTPUT(const struct ofpact_output *a, struct ds *s) { if (ofp_to_u16(a->port) < ofp_to_u16(OFPP_MAX)) { ds_put_format(s, "%soutput:%s%"PRIu32, colors.special, colors.end, a->port); } else { ofputil_format_port(a->port, s); if (a->port == OFPP_CONTROLLER) { ds_put_format(s, ":%"PRIu16, a->max_len); } } } /* Group actions. */ static enum ofperr decode_OFPAT_RAW_GROUP(uint32_t group_id, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_GROUP(out)->group_id = group_id; return 0; } static void encode_GROUP(const struct ofpact_group *group, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_GROUP(out, ofp_version, group->group_id); } static char * OVS_WARN_UNUSED_RESULT parse_GROUP(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_u32(arg, &ofpact_put_GROUP(ofpacts)->group_id); } static void format_GROUP(const struct ofpact_group *a, struct ds *s) { ds_put_format(s, "%sgroup:%s%"PRIu32, colors.special, colors.end, a->group_id); } /* Action structure for NXAST_CONTROLLER. * * This generalizes using OFPAT_OUTPUT to send a packet to OFPP_CONTROLLER. In * addition to the 'max_len' that OFPAT_OUTPUT supports, it also allows * specifying: * * - 'reason': The reason code to use in the ofp_packet_in or nx_packet_in. * * - 'controller_id': The ID of the controller connection to which the * ofp_packet_in should be sent. The ofp_packet_in or nx_packet_in is * sent only to controllers that have the specified controller connection * ID. See "struct nx_controller_id" for more information. */ struct nx_action_controller { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_CONTROLLER. */ ovs_be16 max_len; /* Maximum length to send to controller. */ ovs_be16 controller_id; /* Controller ID to send packet-in. */ uint8_t reason; /* enum ofp_packet_in_reason (OFPR_*). */ uint8_t zero; /* Must be zero. */ }; OFP_ASSERT(sizeof(struct nx_action_controller) == 16); /* Properties for NXAST_CONTROLLER2. * * For more information on the effect of NXAC2PT_PAUSE, see the large comment * on NXT_PACKET_IN2 in nicira-ext.h */ enum nx_action_controller2_prop_type { NXAC2PT_MAX_LEN, /* ovs_be16 max bytes to send (default all). */ NXAC2PT_CONTROLLER_ID, /* ovs_be16 dest controller ID (default 0). */ NXAC2PT_REASON, /* uint8_t reason (OFPR_*), default 0. */ NXAC2PT_USERDATA, /* Data to copy into NXPINT_USERDATA. */ NXAC2PT_PAUSE, /* Flag to pause pipeline to resume later. */ }; /* The action structure for NXAST_CONTROLLER2 is "struct ext_action_header", * followed by NXAC2PT_* properties. */ static enum ofperr decode_NXAST_RAW_CONTROLLER(const struct nx_action_controller *nac, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_controller *oc; oc = ofpact_put_CONTROLLER(out); oc->ofpact.raw = NXAST_RAW_CONTROLLER; oc->max_len = ntohs(nac->max_len); oc->controller_id = ntohs(nac->controller_id); oc->reason = nac->reason; ofpact_finish_CONTROLLER(out, &oc); return 0; } static enum ofperr decode_NXAST_RAW_CONTROLLER2(const struct ext_action_header *eah, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (!is_all_zeros(eah->pad, sizeof eah->pad)) { return OFPERR_NXBRC_MUST_BE_ZERO; } size_t start_ofs = out->size; struct ofpact_controller *oc = ofpact_put_CONTROLLER(out); oc->ofpact.raw = NXAST_RAW_CONTROLLER2; oc->max_len = UINT16_MAX; oc->reason = OFPR_ACTION; struct ofpbuf properties; ofpbuf_use_const(&properties, eah, ntohs(eah->len)); ofpbuf_pull(&properties, sizeof *eah); while (properties.size > 0) { struct ofpbuf payload; uint64_t type; enum ofperr error = ofpprop_pull(&properties, &payload, &type); if (error) { return error; } switch (type) { case NXAC2PT_MAX_LEN: error = ofpprop_parse_u16(&payload, &oc->max_len); break; case NXAC2PT_CONTROLLER_ID: error = ofpprop_parse_u16(&payload, &oc->controller_id); break; case NXAC2PT_REASON: { uint8_t u8; error = ofpprop_parse_u8(&payload, &u8); oc->reason = u8; break; } case NXAC2PT_USERDATA: out->size = start_ofs + OFPACT_CONTROLLER_SIZE; ofpbuf_put(out, payload.msg, ofpbuf_msgsize(&payload)); oc = ofpbuf_at_assert(out, start_ofs, sizeof *oc); oc->userdata_len = ofpbuf_msgsize(&payload); break; case NXAC2PT_PAUSE: oc->pause = true; break; default: error = OFPPROP_UNKNOWN(false, "NXAST_RAW_CONTROLLER2", type); break; } if (error) { return error; } } ofpact_finish_CONTROLLER(out, &oc); return 0; } static void encode_CONTROLLER(const struct ofpact_controller *controller, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (controller->userdata_len || controller->pause || controller->ofpact.raw == NXAST_RAW_CONTROLLER2) { size_t start_ofs = out->size; put_NXAST_CONTROLLER2(out); if (controller->max_len != UINT16_MAX) { ofpprop_put_u16(out, NXAC2PT_MAX_LEN, controller->max_len); } if (controller->controller_id != 0) { ofpprop_put_u16(out, NXAC2PT_CONTROLLER_ID, controller->controller_id); } if (controller->reason != OFPR_ACTION) { ofpprop_put_u8(out, NXAC2PT_REASON, controller->reason); } if (controller->userdata_len != 0) { ofpprop_put(out, NXAC2PT_USERDATA, controller->userdata, controller->userdata_len); } if (controller->pause) { ofpprop_put_flag(out, NXAC2PT_PAUSE); } pad_ofpat(out, start_ofs); } else { struct nx_action_controller *nac; nac = put_NXAST_CONTROLLER(out); nac->max_len = htons(controller->max_len); nac->controller_id = htons(controller->controller_id); nac->reason = controller->reason; } } static char * OVS_WARN_UNUSED_RESULT parse_CONTROLLER(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { enum ofp_packet_in_reason reason = OFPR_ACTION; uint16_t controller_id = 0; uint16_t max_len = UINT16_MAX; const char *userdata = NULL; bool pause = false; if (!arg[0]) { /* Use defaults. */ } else if (strspn(arg, "0123456789") == strlen(arg)) { char *error = str_to_u16(arg, "max_len", &max_len); if (error) { return error; } } else { char *name, *value; while (ofputil_parse_key_value(&arg, &name, &value)) { if (!strcmp(name, "reason")) { if (!ofputil_packet_in_reason_from_string(value, &reason)) { return xasprintf("unknown reason \"%s\"", value); } } else if (!strcmp(name, "max_len")) { char *error = str_to_u16(value, "max_len", &max_len); if (error) { return error; } } else if (!strcmp(name, "id")) { char *error = str_to_u16(value, "id", &controller_id); if (error) { return error; } } else if (!strcmp(name, "userdata")) { userdata = value; } else if (!strcmp(name, "pause")) { pause = true; } else { return xasprintf("unknown key \"%s\" parsing controller " "action", name); } } } if (reason == OFPR_ACTION && controller_id == 0 && !userdata && !pause) { struct ofpact_output *output; output = ofpact_put_OUTPUT(ofpacts); output->port = OFPP_CONTROLLER; output->max_len = max_len; } else { struct ofpact_controller *controller; controller = ofpact_put_CONTROLLER(ofpacts); controller->max_len = max_len; controller->reason = reason; controller->controller_id = controller_id; controller->pause = pause; if (userdata) { size_t start_ofs = ofpacts->size; const char *end = ofpbuf_put_hex(ofpacts, userdata, NULL); if (*end) { return xstrdup("bad hex digit in `controller' " "action `userdata'"); } size_t userdata_len = ofpacts->size - start_ofs; controller = ofpacts->header; controller->userdata_len = userdata_len; } ofpact_finish_CONTROLLER(ofpacts, &controller); } return NULL; } static void format_hex_arg(struct ds *s, const uint8_t *data, size_t len) { for (size_t i = 0; i < len; i++) { if (i) { ds_put_char(s, '.'); } ds_put_format(s, "%02"PRIx8, data[i]); } } static void format_CONTROLLER(const struct ofpact_controller *a, struct ds *s) { if (a->reason == OFPR_ACTION && !a->controller_id && !a->userdata_len && !a->pause) { ds_put_format(s, "%sCONTROLLER:%s%"PRIu16, colors.special, colors.end, a->max_len); } else { enum ofp_packet_in_reason reason = a->reason; ds_put_format(s, "%scontroller(%s", colors.paren, colors.end); if (reason != OFPR_ACTION) { char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE]; ds_put_format(s, "%sreason=%s%s,", colors.param, colors.end, ofputil_packet_in_reason_to_string( reason, reasonbuf, sizeof reasonbuf)); } if (a->max_len != UINT16_MAX) { ds_put_format(s, "%smax_len=%s%"PRIu16",", colors.param, colors.end, a->max_len); } if (a->controller_id != 0) { ds_put_format(s, "%sid=%s%"PRIu16",", colors.param, colors.end, a->controller_id); } if (a->userdata_len) { ds_put_format(s, "%suserdata=%s", colors.param, colors.end); format_hex_arg(s, a->userdata, a->userdata_len); ds_put_char(s, ','); } if (a->pause) { ds_put_format(s, "%spause%s,", colors.value, colors.end); } ds_chomp(s, ','); ds_put_format(s, "%s)%s", colors.paren, colors.end); } } /* Enqueue action. */ struct ofp10_action_enqueue { ovs_be16 type; /* OFPAT10_ENQUEUE. */ ovs_be16 len; /* Len is 16. */ ovs_be16 port; /* Port that queue belongs. Should refer to a valid physical port (i.e. < OFPP_MAX) or OFPP_IN_PORT. */ uint8_t pad[6]; /* Pad for 64-bit alignment. */ ovs_be32 queue_id; /* Where to enqueue the packets. */ }; OFP_ASSERT(sizeof(struct ofp10_action_enqueue) == 16); static enum ofperr decode_OFPAT_RAW10_ENQUEUE(const struct ofp10_action_enqueue *oae, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_enqueue *enqueue; enqueue = ofpact_put_ENQUEUE(out); enqueue->port = u16_to_ofp(ntohs(oae->port)); enqueue->queue = ntohl(oae->queue_id); if (ofp_to_u16(enqueue->port) >= ofp_to_u16(OFPP_MAX) && enqueue->port != OFPP_IN_PORT && enqueue->port != OFPP_LOCAL) { return OFPERR_OFPBAC_BAD_OUT_PORT; } return 0; } static void encode_ENQUEUE(const struct ofpact_enqueue *enqueue, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { struct ofp10_action_enqueue *oae; oae = put_OFPAT10_ENQUEUE(out); oae->port = htons(ofp_to_u16(enqueue->port)); oae->queue_id = htonl(enqueue->queue); } else { put_OFPAT_SET_QUEUE(out, ofp_version, enqueue->queue); struct ofp11_action_output *oao = put_OFPAT11_OUTPUT(out); oao->port = ofputil_port_to_ofp11(enqueue->port); oao->max_len = OVS_BE16_MAX; put_NXAST_POP_QUEUE(out); } } static char * OVS_WARN_UNUSED_RESULT parse_ENQUEUE(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { char *sp = NULL; char *port = strtok_r(arg, ":q,", &sp); char *queue = strtok_r(NULL, "", &sp); struct ofpact_enqueue *enqueue; if (port == NULL || queue == NULL) { return xstrdup("\"enqueue\" syntax is \"enqueue:PORT:QUEUE\" or " "\"enqueue(PORT,QUEUE)\""); } enqueue = ofpact_put_ENQUEUE(ofpacts); if (!ofputil_port_from_string(port, &enqueue->port)) { return xasprintf("%s: enqueue to unknown port", port); } return str_to_u32(queue, &enqueue->queue); } static void format_ENQUEUE(const struct ofpact_enqueue *a, struct ds *s) { ds_put_format(s, "%senqueue:%s", colors.param, colors.end); ofputil_format_port(a->port, s); ds_put_format(s, ":%"PRIu32, a->queue); } /* Action structure for NXAST_OUTPUT_REG. * * Outputs to the OpenFlow port number written to src[ofs:ofs+nbits]. * * The format and semantics of 'src' and 'ofs_nbits' are similar to those for * the NXAST_REG_LOAD action. * * The acceptable nxm_header values for 'src' are the same as the acceptable * nxm_header values for the 'src' field of NXAST_REG_MOVE. * * The 'max_len' field indicates the number of bytes to send when the chosen * port is OFPP_CONTROLLER. Its semantics are equivalent to the 'max_len' * field of OFPAT_OUTPUT. * * The 'zero' field is required to be zeroed for forward compatibility. */ struct nx_action_output_reg { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_OUTPUT_REG. */ ovs_be16 ofs_nbits; /* (ofs << 6) | (n_bits - 1). */ ovs_be32 src; /* Source. */ ovs_be16 max_len; /* Max length to send to controller. */ uint8_t zero[6]; /* Reserved, must be zero. */ }; OFP_ASSERT(sizeof(struct nx_action_output_reg) == 24); /* Action structure for NXAST_OUTPUT_REG2. * * Like the NXAST_OUTPUT_REG but organized so that there is room for a 64-bit * experimenter OXM as 'src'. */ struct nx_action_output_reg2 { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_OUTPUT_REG2. */ ovs_be16 ofs_nbits; /* (ofs << 6) | (n_bits - 1). */ ovs_be16 max_len; /* Max length to send to controller. */ /* Followed by: * - 'src', as an OXM/NXM header (either 4 or 8 bytes). * - Enough 0-bytes to pad the action out to 24 bytes. */ uint8_t pad[10]; }; OFP_ASSERT(sizeof(struct nx_action_output_reg2) == 24); static enum ofperr decode_NXAST_RAW_OUTPUT_REG(const struct nx_action_output_reg *naor, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { struct ofpact_output_reg *output_reg; enum ofperr error; if (!is_all_zeros(naor->zero, sizeof naor->zero)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } output_reg = ofpact_put_OUTPUT_REG(out); output_reg->ofpact.raw = NXAST_RAW_OUTPUT_REG; output_reg->src.ofs = nxm_decode_ofs(naor->ofs_nbits); output_reg->src.n_bits = nxm_decode_n_bits(naor->ofs_nbits); output_reg->max_len = ntohs(naor->max_len); error = mf_vl_mff_mf_from_nxm_header(ntohl(naor->src), vl_mff_map, &output_reg->src.field, tlv_bitmap); if (error) { return error; } return mf_check_src(&output_reg->src, NULL); } static enum ofperr decode_NXAST_RAW_OUTPUT_REG2(const struct nx_action_output_reg2 *naor, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { struct ofpact_output_reg *output_reg; enum ofperr error; output_reg = ofpact_put_OUTPUT_REG(out); output_reg->ofpact.raw = NXAST_RAW_OUTPUT_REG2; output_reg->src.ofs = nxm_decode_ofs(naor->ofs_nbits); output_reg->src.n_bits = nxm_decode_n_bits(naor->ofs_nbits); output_reg->max_len = ntohs(naor->max_len); struct ofpbuf b = ofpbuf_const_initializer(naor, ntohs(naor->len)); ofpbuf_pull(&b, OBJECT_OFFSETOF(naor, pad)); error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &output_reg->src.field, NULL, tlv_bitmap); if (error) { return error; } if (!is_all_zeros(b.data, b.size)) { return OFPERR_NXBRC_MUST_BE_ZERO; } return mf_check_src(&output_reg->src, NULL); } static void encode_OUTPUT_REG(const struct ofpact_output_reg *output_reg, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { /* If 'output_reg' came in as an NXAST_RAW_OUTPUT_REG2 action, or if it * cannot be encoded in the older form, encode it as * NXAST_RAW_OUTPUT_REG2. */ if (output_reg->ofpact.raw == NXAST_RAW_OUTPUT_REG2 || !mf_nxm_header(output_reg->src.field->id)) { struct nx_action_output_reg2 *naor = put_NXAST_OUTPUT_REG2(out); size_t size = out->size; naor->ofs_nbits = nxm_encode_ofs_nbits(output_reg->src.ofs, output_reg->src.n_bits); naor->max_len = htons(output_reg->max_len); out->size = size - sizeof naor->pad; nx_put_mff_header(out, output_reg->src.field, 0, false); out->size = size; } else { struct nx_action_output_reg *naor = put_NXAST_OUTPUT_REG(out); naor->ofs_nbits = nxm_encode_ofs_nbits(output_reg->src.ofs, output_reg->src.n_bits); naor->src = htonl(nxm_header_from_mff(output_reg->src.field)); naor->max_len = htons(output_reg->max_len); } } static char * OVS_WARN_UNUSED_RESULT parse_OUTPUT_REG(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return parse_OUTPUT(arg, ofpacts, usable_protocols); } static void format_OUTPUT_REG(const struct ofpact_output_reg *a, struct ds *s) { ds_put_format(s, "%soutput:%s", colors.special, colors.end); mf_format_subfield(&a->src, s); } /* Action structure for NXAST_BUNDLE and NXAST_BUNDLE_LOAD. * * The bundle actions choose a slave from a supplied list of options. * NXAST_BUNDLE outputs to its selection. NXAST_BUNDLE_LOAD writes its * selection to a register. * * The list of possible slaves follows the nx_action_bundle structure. The size * of each slave is governed by its type as indicated by the 'slave_type' * parameter. The list of slaves should be padded at its end with zeros to make * the total length of the action a multiple of 8. * * Switches infer from the 'slave_type' parameter the size of each slave. All * implementations must support the NXM_OF_IN_PORT 'slave_type' which indicates * that the slaves are OpenFlow port numbers with NXM_LENGTH(NXM_OF_IN_PORT) == * 2 byte width. Switches should reject actions which indicate unknown or * unsupported slave types. * * Switches use a strategy dictated by the 'algorithm' parameter to choose a * slave. If the switch does not support the specified 'algorithm' parameter, * it should reject the action. * * Several algorithms take into account liveness when selecting slaves. The * liveness of a slave is implementation defined (with one exception), but will * generally take into account things like its carrier status and the results * of any link monitoring protocols which happen to be running on it. In order * to give controllers a place-holder value, the OFPP_NONE port is always * considered live, that is, NXAST_BUNDLE_LOAD stores OFPP_NONE in the output * register if no slave is live. * * Some slave selection strategies require the use of a hash function, in which * case the 'fields' and 'basis' parameters should be populated. The 'fields' * parameter (one of NX_HASH_FIELDS_*) designates which parts of the flow to * hash. Refer to the definition of "enum nx_hash_fields" for details. The * 'basis' parameter is used as a universal hash parameter. Different values * of 'basis' yield different hash results. * * The 'zero' parameter at the end of the action structure is reserved for * future use. Switches are required to reject actions which have nonzero * bytes in the 'zero' field. * * NXAST_BUNDLE actions should have 'ofs_nbits' and 'dst' zeroed. Switches * should reject actions which have nonzero bytes in either of these fields. * * NXAST_BUNDLE_LOAD stores the OpenFlow port number of the selected slave in * dst[ofs:ofs+n_bits]. The format and semantics of 'dst' and 'ofs_nbits' are * similar to those for the NXAST_REG_LOAD action. */ struct nx_action_bundle { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length including slaves. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_BUNDLE or NXAST_BUNDLE_LOAD. */ /* Slave choice algorithm to apply to hash value. */ ovs_be16 algorithm; /* One of NX_BD_ALG_*. */ /* What fields to hash and how. */ ovs_be16 fields; /* One of NX_HASH_FIELDS_*. */ ovs_be16 basis; /* Universal hash parameter. */ ovs_be32 slave_type; /* NXM_OF_IN_PORT. */ ovs_be16 n_slaves; /* Number of slaves. */ ovs_be16 ofs_nbits; /* (ofs << 6) | (n_bits - 1). */ ovs_be32 dst; /* Destination. */ uint8_t zero[4]; /* Reserved. Must be zero. */ }; OFP_ASSERT(sizeof(struct nx_action_bundle) == 32); static enum ofperr decode_bundle(bool load, const struct nx_action_bundle *nab, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5); struct ofpact_bundle *bundle; uint32_t slave_type; size_t slaves_size, i; enum ofperr error; bundle = ofpact_put_BUNDLE(ofpacts); bundle->n_slaves = ntohs(nab->n_slaves); bundle->basis = ntohs(nab->basis); bundle->fields = ntohs(nab->fields); bundle->algorithm = ntohs(nab->algorithm); slave_type = ntohl(nab->slave_type); slaves_size = ntohs(nab->len) - sizeof *nab; error = OFPERR_OFPBAC_BAD_ARGUMENT; if (!flow_hash_fields_valid(bundle->fields)) { VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields); } else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) { VLOG_WARN_RL(&rl, "too many slaves"); } else if (bundle->algorithm != NX_BD_ALG_HRW && bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) { VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm); } else if (slave_type != mf_nxm_header(MFF_IN_PORT)) { VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type); } else { error = 0; } if (!is_all_zeros(nab->zero, sizeof nab->zero)) { VLOG_WARN_RL(&rl, "reserved field is nonzero"); error = OFPERR_OFPBAC_BAD_ARGUMENT; } if (load) { bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits); bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits); error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map, &bundle->dst.field, tlv_bitmap); if (error) { return error; } if (bundle->dst.n_bits < 16) { VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit " "destination."); error = OFPERR_OFPBAC_BAD_ARGUMENT; } } else { if (nab->ofs_nbits || nab->dst) { VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields"); error = OFPERR_OFPBAC_BAD_ARGUMENT; } } if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) { VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes " "allocated for slaves. %"PRIuSIZE" bytes are required " "for %"PRIu16" slaves.", load ? "bundle_load" : "bundle", slaves_size, bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves); error = OFPERR_OFPBAC_BAD_LEN; } for (i = 0; i < bundle->n_slaves; i++) { ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i])); ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port); bundle = ofpacts->header; } ofpact_finish_BUNDLE(ofpacts, &bundle); if (!error) { error = bundle_check(bundle, OFPP_MAX, NULL); } return error; } static enum ofperr decode_NXAST_RAW_BUNDLE(const struct nx_action_bundle *nab, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_bundle(false, nab, NULL, NULL, out); } static enum ofperr decode_NXAST_RAW_BUNDLE_LOAD(const struct nx_action_bundle *nab, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { return decode_bundle(true, nab, vl_mff_map, tlv_bitmap, out); } static void encode_BUNDLE(const struct ofpact_bundle *bundle, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { int slaves_len = ROUND_UP(2 * bundle->n_slaves, OFP_ACTION_ALIGN); struct nx_action_bundle *nab; ovs_be16 *slaves; size_t i; nab = (bundle->dst.field ? put_NXAST_BUNDLE_LOAD(out) : put_NXAST_BUNDLE(out)); nab->len = htons(ntohs(nab->len) + slaves_len); nab->algorithm = htons(bundle->algorithm); nab->fields = htons(bundle->fields); nab->basis = htons(bundle->basis); nab->slave_type = htonl(mf_nxm_header(MFF_IN_PORT)); nab->n_slaves = htons(bundle->n_slaves); if (bundle->dst.field) { nab->ofs_nbits = nxm_encode_ofs_nbits(bundle->dst.ofs, bundle->dst.n_bits); nab->dst = htonl(nxm_header_from_mff(bundle->dst.field)); } slaves = ofpbuf_put_zeros(out, slaves_len); for (i = 0; i < bundle->n_slaves; i++) { slaves[i] = htons(ofp_to_u16(bundle->slaves[i])); } } static char * OVS_WARN_UNUSED_RESULT parse_BUNDLE(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return bundle_parse(arg, ofpacts); } static char * OVS_WARN_UNUSED_RESULT parse_bundle_load(const char *arg, struct ofpbuf *ofpacts) { return bundle_parse_load(arg, ofpacts); } static void format_BUNDLE(const struct ofpact_bundle *a, struct ds *s) { bundle_format(a, s); } /* Set VLAN actions. */ static enum ofperr decode_set_vlan_vid(uint16_t vid, bool push_vlan_if_needed, struct ofpbuf *out) { if (vid & ~0xfff) { return OFPERR_OFPBAC_BAD_ARGUMENT; } else { struct ofpact_vlan_vid *vlan_vid = ofpact_put_SET_VLAN_VID(out); vlan_vid->vlan_vid = vid; vlan_vid->push_vlan_if_needed = push_vlan_if_needed; return 0; } } static enum ofperr decode_OFPAT_RAW10_SET_VLAN_VID(uint16_t vid, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_set_vlan_vid(vid, true, out); } static enum ofperr decode_OFPAT_RAW11_SET_VLAN_VID(uint16_t vid, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_set_vlan_vid(vid, false, out); } static void encode_SET_VLAN_VID(const struct ofpact_vlan_vid *vlan_vid, enum ofp_version ofp_version, struct ofpbuf *out) { uint16_t vid = vlan_vid->vlan_vid; /* Push a VLAN tag, if none is present and this form of the action calls * for such a feature. */ if (ofp_version > OFP10_VERSION && vlan_vid->push_vlan_if_needed && !vlan_vid->flow_has_vlan) { put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q)); } if (ofp_version == OFP10_VERSION) { put_OFPAT10_SET_VLAN_VID(out, vid); } else if (ofp_version == OFP11_VERSION) { put_OFPAT11_SET_VLAN_VID(out, vid); } else { put_set_field(out, ofp_version, MFF_VLAN_VID, vid | OFPVID12_PRESENT); } } static char * OVS_WARN_UNUSED_RESULT parse_set_vlan_vid(char *arg, struct ofpbuf *ofpacts, bool push_vlan_if_needed) { struct ofpact_vlan_vid *vlan_vid; uint16_t vid; char *error; error = str_to_u16(arg, "VLAN VID", &vid); if (error) { return error; } if (vid & ~VLAN_VID_MASK) { return xasprintf("%s: not a valid VLAN VID", arg); } vlan_vid = ofpact_put_SET_VLAN_VID(ofpacts); vlan_vid->vlan_vid = vid; vlan_vid->push_vlan_if_needed = push_vlan_if_needed; return NULL; } static char * OVS_WARN_UNUSED_RESULT parse_SET_VLAN_VID(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return parse_set_vlan_vid(arg, ofpacts, false); } static void format_SET_VLAN_VID(const struct ofpact_vlan_vid *a, struct ds *s) { ds_put_format(s, "%s%s:%s%"PRIu16, colors.param, a->push_vlan_if_needed ? "mod_vlan_vid" : "set_vlan_vid", colors.end, a->vlan_vid); } /* Set PCP actions. */ static enum ofperr decode_set_vlan_pcp(uint8_t pcp, bool push_vlan_if_needed, struct ofpbuf *out) { if (pcp & ~7) { return OFPERR_OFPBAC_BAD_ARGUMENT; } else { struct ofpact_vlan_pcp *vlan_pcp = ofpact_put_SET_VLAN_PCP(out); vlan_pcp->vlan_pcp = pcp; vlan_pcp->push_vlan_if_needed = push_vlan_if_needed; return 0; } } static enum ofperr decode_OFPAT_RAW10_SET_VLAN_PCP(uint8_t pcp, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_set_vlan_pcp(pcp, true, out); } static enum ofperr decode_OFPAT_RAW11_SET_VLAN_PCP(uint8_t pcp, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_set_vlan_pcp(pcp, false, out); } static void encode_SET_VLAN_PCP(const struct ofpact_vlan_pcp *vlan_pcp, enum ofp_version ofp_version, struct ofpbuf *out) { uint8_t pcp = vlan_pcp->vlan_pcp; /* Push a VLAN tag, if none is present and this form of the action calls * for such a feature. */ if (ofp_version > OFP10_VERSION && vlan_pcp->push_vlan_if_needed && !vlan_pcp->flow_has_vlan) { put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q)); } if (ofp_version == OFP10_VERSION) { put_OFPAT10_SET_VLAN_PCP(out, pcp); } else if (ofp_version == OFP11_VERSION) { put_OFPAT11_SET_VLAN_PCP(out, pcp); } else { put_set_field(out, ofp_version, MFF_VLAN_PCP, pcp); } } static char * OVS_WARN_UNUSED_RESULT parse_set_vlan_pcp(char *arg, struct ofpbuf *ofpacts, bool push_vlan_if_needed) { struct ofpact_vlan_pcp *vlan_pcp; uint8_t pcp; char *error; error = str_to_u8(arg, "VLAN PCP", &pcp); if (error) { return error; } if (pcp & ~7) { return xasprintf("%s: not a valid VLAN PCP", arg); } vlan_pcp = ofpact_put_SET_VLAN_PCP(ofpacts); vlan_pcp->vlan_pcp = pcp; vlan_pcp->push_vlan_if_needed = push_vlan_if_needed; return NULL; } static char * OVS_WARN_UNUSED_RESULT parse_SET_VLAN_PCP(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return parse_set_vlan_pcp(arg, ofpacts, false); } static void format_SET_VLAN_PCP(const struct ofpact_vlan_pcp *a, struct ds *s) { ds_put_format(s, "%s%s:%s%"PRIu8, colors.param, a->push_vlan_if_needed ? "mod_vlan_pcp" : "set_vlan_pcp", colors.end, a->vlan_pcp); } /* Strip VLAN actions. */ static enum ofperr decode_OFPAT_RAW10_STRIP_VLAN(struct ofpbuf *out) { ofpact_put_STRIP_VLAN(out)->ofpact.raw = OFPAT_RAW10_STRIP_VLAN; return 0; } static enum ofperr decode_OFPAT_RAW11_POP_VLAN(struct ofpbuf *out) { ofpact_put_STRIP_VLAN(out)->ofpact.raw = OFPAT_RAW11_POP_VLAN; return 0; } static void encode_STRIP_VLAN(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { put_OFPAT10_STRIP_VLAN(out); } else { put_OFPAT11_POP_VLAN(out); } } static char * OVS_WARN_UNUSED_RESULT parse_STRIP_VLAN(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_STRIP_VLAN(ofpacts)->ofpact.raw = OFPAT_RAW10_STRIP_VLAN; return NULL; } static char * OVS_WARN_UNUSED_RESULT parse_pop_vlan(struct ofpbuf *ofpacts) { ofpact_put_STRIP_VLAN(ofpacts)->ofpact.raw = OFPAT_RAW11_POP_VLAN; return NULL; } static void format_STRIP_VLAN(const struct ofpact_null *a, struct ds *s) { ds_put_format(s, (a->ofpact.raw == OFPAT_RAW11_POP_VLAN ? "%spop_vlan%s" : "%sstrip_vlan%s"), colors.value, colors.end); } /* Push VLAN action. */ static enum ofperr decode_OFPAT_RAW11_PUSH_VLAN(ovs_be16 eth_type, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (eth_type != htons(ETH_TYPE_VLAN_8021Q)) { /* XXX 802.1AD(QinQ) isn't supported at the moment */ return OFPERR_OFPBAC_BAD_ARGUMENT; } ofpact_put_PUSH_VLAN(out); return 0; } static void encode_PUSH_VLAN(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { /* PUSH is a side effect of a SET_VLAN_VID/PCP, which should * follow this action. */ } else { /* XXX ETH_TYPE_VLAN_8021AD case */ put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q)); } } static char * OVS_WARN_UNUSED_RESULT parse_PUSH_VLAN(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint16_t ethertype; char *error; *usable_protocols &= OFPUTIL_P_OF11_UP; error = str_to_u16(arg, "ethertype", &ethertype); if (error) { return error; } if (ethertype != ETH_TYPE_VLAN_8021Q) { /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */ return xasprintf("%s: not a valid VLAN ethertype", arg); } ofpact_put_PUSH_VLAN(ofpacts); return NULL; } static void format_PUSH_VLAN(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { /* XXX 802.1AD case*/ ds_put_format(s, "%spush_vlan:%s%#"PRIx16, colors.param, colors.end, ETH_TYPE_VLAN_8021Q); } /* Action structure for OFPAT10_SET_DL_SRC/DST and OFPAT11_SET_DL_SRC/DST. */ struct ofp_action_dl_addr { ovs_be16 type; /* Type. */ ovs_be16 len; /* Length is 16. */ struct eth_addr dl_addr; /* Ethernet address. */ uint8_t pad[6]; }; OFP_ASSERT(sizeof(struct ofp_action_dl_addr) == 16); static enum ofperr decode_OFPAT_RAW_SET_DL_SRC(const struct ofp_action_dl_addr *a, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_ETH_SRC(out)->mac = a->dl_addr; return 0; } static enum ofperr decode_OFPAT_RAW_SET_DL_DST(const struct ofp_action_dl_addr *a, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_ETH_DST(out)->mac = a->dl_addr; return 0; } static void encode_SET_ETH_addr(const struct ofpact_mac *mac, enum ofp_version ofp_version, enum ofp_raw_action_type raw, enum mf_field_id field, struct ofpbuf *out) { if (ofp_version < OFP12_VERSION) { struct ofp_action_dl_addr *oada; oada = ofpact_put_raw(out, ofp_version, raw, 0); oada->dl_addr = mac->mac; } else { put_set_field(out, ofp_version, field, eth_addr_to_uint64(mac->mac)); } } static void encode_SET_ETH_SRC(const struct ofpact_mac *mac, enum ofp_version ofp_version, struct ofpbuf *out) { encode_SET_ETH_addr(mac, ofp_version, OFPAT_RAW_SET_DL_SRC, MFF_ETH_SRC, out); } static void encode_SET_ETH_DST(const struct ofpact_mac *mac, enum ofp_version ofp_version, struct ofpbuf *out) { encode_SET_ETH_addr(mac, ofp_version, OFPAT_RAW_SET_DL_DST, MFF_ETH_DST, out); } static char * OVS_WARN_UNUSED_RESULT parse_SET_ETH_SRC(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_mac(arg, &ofpact_put_SET_ETH_SRC(ofpacts)->mac); } static char * OVS_WARN_UNUSED_RESULT parse_SET_ETH_DST(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_mac(arg, &ofpact_put_SET_ETH_DST(ofpacts)->mac); } static void format_SET_ETH_SRC(const struct ofpact_mac *a, struct ds *s) { ds_put_format(s, "%smod_dl_src:%s"ETH_ADDR_FMT, colors.param, colors.end, ETH_ADDR_ARGS(a->mac)); } static void format_SET_ETH_DST(const struct ofpact_mac *a, struct ds *s) { ds_put_format(s, "%smod_dl_dst:%s"ETH_ADDR_FMT, colors.param, colors.end, ETH_ADDR_ARGS(a->mac)); } /* Set IPv4 address actions. */ static enum ofperr decode_OFPAT_RAW_SET_NW_SRC(ovs_be32 ipv4, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_IPV4_SRC(out)->ipv4 = ipv4; return 0; } static enum ofperr decode_OFPAT_RAW_SET_NW_DST(ovs_be32 ipv4, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_IPV4_DST(out)->ipv4 = ipv4; return 0; } static void encode_SET_IPV4_addr(const struct ofpact_ipv4 *ipv4, enum ofp_version ofp_version, enum ofp_raw_action_type raw, enum mf_field_id field, struct ofpbuf *out) { ovs_be32 addr = ipv4->ipv4; if (ofp_version < OFP12_VERSION) { ofpact_put_raw(out, ofp_version, raw, ntohl(addr)); } else { put_set_field(out, ofp_version, field, ntohl(addr)); } } static void encode_SET_IPV4_SRC(const struct ofpact_ipv4 *ipv4, enum ofp_version ofp_version, struct ofpbuf *out) { encode_SET_IPV4_addr(ipv4, ofp_version, OFPAT_RAW_SET_NW_SRC, MFF_IPV4_SRC, out); } static void encode_SET_IPV4_DST(const struct ofpact_ipv4 *ipv4, enum ofp_version ofp_version, struct ofpbuf *out) { encode_SET_IPV4_addr(ipv4, ofp_version, OFPAT_RAW_SET_NW_DST, MFF_IPV4_DST, out); } static char * OVS_WARN_UNUSED_RESULT parse_SET_IPV4_SRC(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_ip(arg, &ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4); } static char * OVS_WARN_UNUSED_RESULT parse_SET_IPV4_DST(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_ip(arg, &ofpact_put_SET_IPV4_DST(ofpacts)->ipv4); } static void format_SET_IPV4_SRC(const struct ofpact_ipv4 *a, struct ds *s) { ds_put_format(s, "%smod_nw_src:%s"IP_FMT, colors.param, colors.end, IP_ARGS(a->ipv4)); } static void format_SET_IPV4_DST(const struct ofpact_ipv4 *a, struct ds *s) { ds_put_format(s, "%smod_nw_dst:%s"IP_FMT, colors.param, colors.end, IP_ARGS(a->ipv4)); } /* Set IPv4/v6 TOS actions. */ static enum ofperr decode_OFPAT_RAW_SET_NW_TOS(uint8_t dscp, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (dscp & ~IP_DSCP_MASK) { return OFPERR_OFPBAC_BAD_ARGUMENT; } else { ofpact_put_SET_IP_DSCP(out)->dscp = dscp; return 0; } } static void encode_SET_IP_DSCP(const struct ofpact_dscp *dscp, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version < OFP12_VERSION) { put_OFPAT_SET_NW_TOS(out, ofp_version, dscp->dscp); } else { put_set_field(out, ofp_version, MFF_IP_DSCP_SHIFTED, dscp->dscp >> 2); } } static char * OVS_WARN_UNUSED_RESULT parse_SET_IP_DSCP(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint8_t tos; char *error; error = str_to_u8(arg, "TOS", &tos); if (error) { return error; } if (tos & ~IP_DSCP_MASK) { return xasprintf("%s: not a valid TOS", arg); } ofpact_put_SET_IP_DSCP(ofpacts)->dscp = tos; return NULL; } static void format_SET_IP_DSCP(const struct ofpact_dscp *a, struct ds *s) { ds_put_format(s, "%smod_nw_tos:%s%d", colors.param, colors.end, a->dscp); } /* Set IPv4/v6 ECN actions. */ static enum ofperr decode_OFPAT_RAW11_SET_NW_ECN(uint8_t ecn, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (ecn & ~IP_ECN_MASK) { return OFPERR_OFPBAC_BAD_ARGUMENT; } else { ofpact_put_SET_IP_ECN(out)->ecn = ecn; return 0; } } static void encode_SET_IP_ECN(const struct ofpact_ecn *ip_ecn, enum ofp_version ofp_version, struct ofpbuf *out) { uint8_t ecn = ip_ecn->ecn; if (ofp_version == OFP10_VERSION) { struct mf_subfield dst = { .field = mf_from_id(MFF_IP_ECN), .ofs = 0, .n_bits = 2 }; put_reg_load(out, &dst, ecn); } else if (ofp_version == OFP11_VERSION) { put_OFPAT11_SET_NW_ECN(out, ecn); } else { put_set_field(out, ofp_version, MFF_IP_ECN, ecn); } } static char * OVS_WARN_UNUSED_RESULT parse_SET_IP_ECN(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint8_t ecn; char *error; error = str_to_u8(arg, "ECN", &ecn); if (error) { return error; } if (ecn & ~IP_ECN_MASK) { return xasprintf("%s: not a valid ECN", arg); } ofpact_put_SET_IP_ECN(ofpacts)->ecn = ecn; return NULL; } static void format_SET_IP_ECN(const struct ofpact_ecn *a, struct ds *s) { ds_put_format(s, "%smod_nw_ecn:%s%d", colors.param, colors.end, a->ecn); } /* Set IPv4/v6 TTL actions. */ static enum ofperr decode_OFPAT_RAW11_SET_NW_TTL(uint8_t ttl, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_IP_TTL(out)->ttl = ttl; return 0; } static void encode_SET_IP_TTL(const struct ofpact_ip_ttl *ttl, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version >= OFP11_VERSION) { put_OFPAT11_SET_NW_TTL(out, ttl->ttl); } else { struct mf_subfield dst = { .field = mf_from_id(MFF_IP_TTL), .ofs = 0, .n_bits = 8 }; put_reg_load(out, &dst, ttl->ttl); } } static char * OVS_WARN_UNUSED_RESULT parse_SET_IP_TTL(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint8_t ttl; char *error; error = str_to_u8(arg, "TTL", &ttl); if (error) { return error; } ofpact_put_SET_IP_TTL(ofpacts)->ttl = ttl; return NULL; } static void format_SET_IP_TTL(const struct ofpact_ip_ttl *a, struct ds *s) { ds_put_format(s, "%smod_nw_ttl:%s%d", colors.param, colors.end, a->ttl); } /* Set TCP/UDP/SCTP port actions. */ static enum ofperr decode_OFPAT_RAW_SET_TP_SRC(ovs_be16 port, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_L4_SRC_PORT(out)->port = ntohs(port); return 0; } static enum ofperr decode_OFPAT_RAW_SET_TP_DST(ovs_be16 port, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_L4_DST_PORT(out)->port = ntohs(port); return 0; } static void encode_SET_L4_port(const struct ofpact_l4_port *l4_port, enum ofp_version ofp_version, enum ofp_raw_action_type raw, enum mf_field_id field, struct ofpbuf *out) { uint16_t port = l4_port->port; if (ofp_version >= OFP12_VERSION && field != MFF_N_IDS) { put_set_field(out, ofp_version, field, port); } else { ofpact_put_raw(out, ofp_version, raw, port); } } static void encode_SET_L4_SRC_PORT(const struct ofpact_l4_port *l4_port, enum ofp_version ofp_version, struct ofpbuf *out) { uint8_t proto = l4_port->flow_ip_proto; enum mf_field_id field = (proto == IPPROTO_TCP ? MFF_TCP_SRC : proto == IPPROTO_UDP ? MFF_UDP_SRC : proto == IPPROTO_SCTP ? MFF_SCTP_SRC : MFF_N_IDS); encode_SET_L4_port(l4_port, ofp_version, OFPAT_RAW_SET_TP_SRC, field, out); } static void encode_SET_L4_DST_PORT(const struct ofpact_l4_port *l4_port, enum ofp_version ofp_version, struct ofpbuf *out) { uint8_t proto = l4_port->flow_ip_proto; enum mf_field_id field = (proto == IPPROTO_TCP ? MFF_TCP_DST : proto == IPPROTO_UDP ? MFF_UDP_DST : proto == IPPROTO_SCTP ? MFF_SCTP_DST : MFF_N_IDS); encode_SET_L4_port(l4_port, ofp_version, OFPAT_RAW_SET_TP_DST, field, out); } static char * OVS_WARN_UNUSED_RESULT parse_SET_L4_SRC_PORT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_u16(arg, "source port", &ofpact_put_SET_L4_SRC_PORT(ofpacts)->port); } static char * OVS_WARN_UNUSED_RESULT parse_SET_L4_DST_PORT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_u16(arg, "destination port", &ofpact_put_SET_L4_DST_PORT(ofpacts)->port); } static void format_SET_L4_SRC_PORT(const struct ofpact_l4_port *a, struct ds *s) { ds_put_format(s, "%smod_tp_src:%s%d", colors.param, colors.end, a->port); } static void format_SET_L4_DST_PORT(const struct ofpact_l4_port *a, struct ds *s) { ds_put_format(s, "%smod_tp_dst:%s%d", colors.param, colors.end, a->port); } /* Action structure for OFPAT_COPY_FIELD. */ struct ofp15_action_copy_field { ovs_be16 type; /* OFPAT_COPY_FIELD. */ ovs_be16 len; /* Length is padded to 64 bits. */ ovs_be16 n_bits; /* Number of bits to copy. */ ovs_be16 src_offset; /* Starting bit offset in source. */ ovs_be16 dst_offset; /* Starting bit offset in destination. */ uint8_t pad[2]; /* Followed by: * - OXM header for source field. * - OXM header for destination field. * - Padding with 0-bytes to a multiple of 8 bytes. * The "pad2" member is the beginning of the above. */ uint8_t pad2[4]; }; OFP_ASSERT(sizeof(struct ofp15_action_copy_field) == 16); /* Action structure for OpenFlow 1.3 extension copy-field action.. */ struct onf_action_copy_field { ovs_be16 type; /* OFPAT_EXPERIMENTER. */ ovs_be16 len; /* Length is padded to 64 bits. */ ovs_be32 experimenter; /* ONF_VENDOR_ID. */ ovs_be16 exp_type; /* 3200. */ uint8_t pad[2]; /* Not used. */ ovs_be16 n_bits; /* Number of bits to copy. */ ovs_be16 src_offset; /* Starting bit offset in source. */ ovs_be16 dst_offset; /* Starting bit offset in destination. */ uint8_t pad2[2]; /* Not used. */ /* Followed by: * - OXM header for source field. * - OXM header for destination field. * - Padding with 0-bytes (either 0 or 4 of them) to a multiple of 8 bytes. * The "pad3" member is the beginning of the above. */ uint8_t pad3[4]; /* Not used. */ }; OFP_ASSERT(sizeof(struct onf_action_copy_field) == 24); /* Action structure for NXAST_REG_MOVE. * * Copies src[src_ofs:src_ofs+n_bits] to dst[dst_ofs:dst_ofs+n_bits], where * a[b:c] denotes the bits within 'a' numbered 'b' through 'c' (not including * bit 'c'). Bit numbering starts at 0 for the least-significant bit, 1 for * the next most significant bit, and so on. * * 'src' and 'dst' are nxm_header values with nxm_hasmask=0. (It doesn't make * sense to use nxm_hasmask=1 because the action does not do any kind of * matching; it uses the actual value of a field.) * * The following nxm_header values are potentially acceptable as 'src': * * - NXM_OF_IN_PORT * - NXM_OF_ETH_DST * - NXM_OF_ETH_SRC * - NXM_OF_ETH_TYPE * - NXM_OF_VLAN_TCI * - NXM_OF_IP_TOS * - NXM_OF_IP_PROTO * - NXM_OF_IP_SRC * - NXM_OF_IP_DST * - NXM_OF_TCP_SRC * - NXM_OF_TCP_DST * - NXM_OF_UDP_SRC * - NXM_OF_UDP_DST * - NXM_OF_ICMP_TYPE * - NXM_OF_ICMP_CODE * - NXM_OF_ARP_OP * - NXM_OF_ARP_SPA * - NXM_OF_ARP_TPA * - NXM_NX_TUN_ID * - NXM_NX_ARP_SHA * - NXM_NX_ARP_THA * - NXM_NX_ICMPV6_TYPE * - NXM_NX_ICMPV6_CODE * - NXM_NX_ND_SLL * - NXM_NX_ND_TLL * - NXM_NX_REG(idx) for idx in the switch's accepted range. * - NXM_NX_PKT_MARK * - NXM_NX_TUN_IPV4_SRC * - NXM_NX_TUN_IPV4_DST * * The following nxm_header values are potentially acceptable as 'dst': * * - NXM_OF_ETH_DST * - NXM_OF_ETH_SRC * - NXM_OF_IP_TOS * - NXM_OF_IP_SRC * - NXM_OF_IP_DST * - NXM_OF_TCP_SRC * - NXM_OF_TCP_DST * - NXM_OF_UDP_SRC * - NXM_OF_UDP_DST * - NXM_OF_ICMP_TYPE * - NXM_OF_ICMP_CODE * - NXM_NX_ICMPV6_TYPE * - NXM_NX_ICMPV6_CODE * - NXM_NX_ARP_SHA * - NXM_NX_ARP_THA * - NXM_OF_ARP_OP * - NXM_OF_ARP_SPA * - NXM_OF_ARP_TPA * Modifying any of the above fields changes the corresponding packet * header. * * - NXM_OF_IN_PORT * * - NXM_NX_REG(idx) for idx in the switch's accepted range. * * - NXM_NX_PKT_MARK * * - NXM_OF_VLAN_TCI. Modifying this field's value has side effects on the * packet's 802.1Q header. Setting a value with CFI=0 removes the 802.1Q * header (if any), ignoring the other bits. Setting a value with CFI=1 * adds or modifies the 802.1Q header appropriately, setting the TCI field * to the field's new value (with the CFI bit masked out). * * - NXM_NX_TUN_ID, NXM_NX_TUN_IPV4_SRC, NXM_NX_TUN_IPV4_DST. Modifying * any of these values modifies the corresponding tunnel header field used * for the packet's next tunnel encapsulation, if allowed by the * configuration of the output tunnel port. * * A given nxm_header value may be used as 'src' or 'dst' only on a flow whose * nx_match satisfies its prerequisites. For example, NXM_OF_IP_TOS may be * used only if the flow's nx_match includes an nxm_entry that specifies * nxm_type=NXM_OF_ETH_TYPE, nxm_hasmask=0, and nxm_value=0x0800. * * The switch will reject actions for which src_ofs+n_bits is greater than the * width of 'src' or dst_ofs+n_bits is greater than the width of 'dst' with * error type OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT. * * This action behaves properly when 'src' overlaps with 'dst', that is, it * behaves as if 'src' were copied out to a temporary buffer, then the * temporary buffer copied to 'dst'. */ struct nx_action_reg_move { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_REG_MOVE. */ ovs_be16 n_bits; /* Number of bits. */ ovs_be16 src_ofs; /* Starting bit offset in source. */ ovs_be16 dst_ofs; /* Starting bit offset in destination. */ /* Followed by: * - OXM/NXM header for source field (4 or 8 bytes). * - OXM/NXM header for destination field (4 or 8 bytes). * - Padding with 0-bytes to a multiple of 8 bytes, if necessary. */ }; OFP_ASSERT(sizeof(struct nx_action_reg_move) == 16); static enum ofperr decode_copy_field__(ovs_be16 src_offset, ovs_be16 dst_offset, ovs_be16 n_bits, const void *action, ovs_be16 action_len, size_t oxm_offset, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts); enum ofperr error; move->ofpact.raw = ONFACT_RAW13_COPY_FIELD; move->src.ofs = ntohs(src_offset); move->src.n_bits = ntohs(n_bits); move->dst.ofs = ntohs(dst_offset); move->dst.n_bits = ntohs(n_bits); struct ofpbuf b = ofpbuf_const_initializer(action, ntohs(action_len)); ofpbuf_pull(&b, oxm_offset); error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->src.field, NULL, tlv_bitmap); if (error) { return error; } error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->dst.field, NULL, tlv_bitmap); if (error) { return error; } if (!is_all_zeros(b.data, b.size)) { return OFPERR_NXBRC_MUST_BE_ZERO; } return nxm_reg_move_check(move, NULL); } static enum ofperr decode_OFPAT_RAW15_COPY_FIELD(const struct ofp15_action_copy_field *oacf, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { return decode_copy_field__(oacf->src_offset, oacf->dst_offset, oacf->n_bits, oacf, oacf->len, OBJECT_OFFSETOF(oacf, pad2), vl_mff_map, tlv_bitmap, ofpacts); } static enum ofperr decode_ONFACT_RAW13_COPY_FIELD(const struct onf_action_copy_field *oacf, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { return decode_copy_field__(oacf->src_offset, oacf->dst_offset, oacf->n_bits, oacf, oacf->len, OBJECT_OFFSETOF(oacf, pad3), vl_mff_map, tlv_bitmap, ofpacts); } static enum ofperr decode_NXAST_RAW_REG_MOVE(const struct nx_action_reg_move *narm, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts); enum ofperr error; move->ofpact.raw = NXAST_RAW_REG_MOVE; move->src.ofs = ntohs(narm->src_ofs); move->src.n_bits = ntohs(narm->n_bits); move->dst.ofs = ntohs(narm->dst_ofs); move->dst.n_bits = ntohs(narm->n_bits); struct ofpbuf b = ofpbuf_const_initializer(narm, ntohs(narm->len)); ofpbuf_pull(&b, sizeof *narm); error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->src.field, NULL, tlv_bitmap); if (error) { return error; } error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &move->dst.field, NULL, tlv_bitmap); if (error) { return error; } if (!is_all_zeros(b.data, b.size)) { return OFPERR_NXBRC_MUST_BE_ZERO; } return nxm_reg_move_check(move, NULL); } static void encode_REG_MOVE(const struct ofpact_reg_move *move, enum ofp_version ofp_version, struct ofpbuf *out) { /* For OpenFlow 1.3, the choice of ONFACT_RAW13_COPY_FIELD versus * NXAST_RAW_REG_MOVE is somewhat difficult. Neither one is guaranteed to * be supported by every OpenFlow 1.3 implementation. It would be ideal to * probe for support. Until we have that ability, we currently prefer * NXAST_RAW_REG_MOVE for backward compatibility with older Open vSwitch * versions. */ size_t start_ofs = out->size; if (ofp_version >= OFP15_VERSION) { struct ofp15_action_copy_field *copy = put_OFPAT15_COPY_FIELD(out); copy->n_bits = htons(move->dst.n_bits); copy->src_offset = htons(move->src.ofs); copy->dst_offset = htons(move->dst.ofs); out->size = out->size - sizeof copy->pad2; nx_put_mff_header(out, move->src.field, ofp_version, false); nx_put_mff_header(out, move->dst.field, ofp_version, false); } else if (ofp_version == OFP13_VERSION && move->ofpact.raw == ONFACT_RAW13_COPY_FIELD) { struct onf_action_copy_field *copy = put_ONFACT13_COPY_FIELD(out); copy->n_bits = htons(move->dst.n_bits); copy->src_offset = htons(move->src.ofs); copy->dst_offset = htons(move->dst.ofs); out->size = out->size - sizeof copy->pad3; nx_put_mff_header(out, move->src.field, ofp_version, false); nx_put_mff_header(out, move->dst.field, ofp_version, false); } else { struct nx_action_reg_move *narm = put_NXAST_REG_MOVE(out); narm->n_bits = htons(move->dst.n_bits); narm->src_ofs = htons(move->src.ofs); narm->dst_ofs = htons(move->dst.ofs); nx_put_mff_header(out, move->src.field, 0, false); nx_put_mff_header(out, move->dst.field, 0, false); } pad_ofpat(out, start_ofs); } static char * OVS_WARN_UNUSED_RESULT parse_REG_MOVE(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_reg_move *move = ofpact_put_REG_MOVE(ofpacts); return nxm_parse_reg_move(move, arg); } static void format_REG_MOVE(const struct ofpact_reg_move *a, struct ds *s) { nxm_format_reg_move(a, s); } /* Action structure for OFPAT12_SET_FIELD. */ struct ofp12_action_set_field { ovs_be16 type; /* OFPAT12_SET_FIELD. */ ovs_be16 len; /* Length is padded to 64 bits. */ /* Followed by: * - An OXM header, value, and (in OpenFlow 1.5+) optionally a mask. * - Enough 0-bytes to pad out to a multiple of 64 bits. * * The "pad" member is the beginning of the above. */ uint8_t pad[4]; }; OFP_ASSERT(sizeof(struct ofp12_action_set_field) == 8); /* Action structure for NXAST_REG_LOAD. * * Copies value[0:n_bits] to dst[ofs:ofs+n_bits], where a[b:c] denotes the bits * within 'a' numbered 'b' through 'c' (not including bit 'c'). Bit numbering * starts at 0 for the least-significant bit, 1 for the next most significant * bit, and so on. * * 'dst' is an nxm_header with nxm_hasmask=0. See the documentation for * NXAST_REG_MOVE, above, for the permitted fields and for the side effects of * loading them. * * The 'ofs' and 'n_bits' fields are combined into a single 'ofs_nbits' field * to avoid enlarging the structure by another 8 bytes. To allow 'n_bits' to * take a value between 1 and 64 (inclusive) while taking up only 6 bits, it is * also stored as one less than its true value: * * 15 6 5 0 * +------------------------------+------------------+ * | ofs | n_bits - 1 | * +------------------------------+------------------+ * * The switch will reject actions for which ofs+n_bits is greater than the * width of 'dst', or in which any bits in 'value' with value 2**n_bits or * greater are set to 1, with error type OFPET_BAD_ACTION, code * OFPBAC_BAD_ARGUMENT. */ struct nx_action_reg_load { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_REG_LOAD. */ ovs_be16 ofs_nbits; /* (ofs << 6) | (n_bits - 1). */ ovs_be32 dst; /* Destination register. */ ovs_be64 value; /* Immediate value. */ }; OFP_ASSERT(sizeof(struct nx_action_reg_load) == 24); /* The NXAST_REG_LOAD2 action structure is "struct ext_action_header", * followed by: * * - An NXM/OXM header, value, and optionally a mask. * - Enough 0-bytes to pad out to a multiple of 64 bits. * * The "pad" member is the beginning of the above. */ static enum ofperr decode_ofpat_set_field(const struct ofp12_action_set_field *oasf, bool may_mask, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpbuf b = ofpbuf_const_initializer(oasf, ntohs(oasf->len)); ofpbuf_pull(&b, OBJECT_OFFSETOF(oasf, pad)); union mf_value value, mask; const struct mf_field *field; enum ofperr error; error = mf_vl_mff_nx_pull_entry(&b, vl_mff_map, &field, &value, may_mask ? &mask : NULL, tlv_bitmap); if (error) { return (error == OFPERR_OFPBMC_BAD_MASK ? OFPERR_OFPBAC_BAD_SET_MASK : error); } if (!may_mask) { memset(&mask, 0xff, field->n_bytes); } if (!is_all_zeros(b.data, b.size)) { return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } /* OpenFlow says specifically that one may not set OXM_OF_IN_PORT via * Set-Field. */ if (field->id == MFF_IN_PORT_OXM) { return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } /* oxm_length is now validated to be compatible with mf_value. */ if (!field->writable) { VLOG_WARN_RL(&rl, "destination field %s is not writable", field->name); return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } /* The value must be valid for match. OpenFlow 1.5 also says, * "In an OXM_OF_VLAN_VID set-field action, the OFPVID_PRESENT bit must be * a 1-bit in oxm_value and in oxm_mask." */ if (!mf_is_value_valid(field, &value) || (field->id == MFF_VLAN_VID && (!(mask.be16 & htons(OFPVID12_PRESENT)) || !(value.be16 & htons(OFPVID12_PRESENT))))) { struct ds ds = DS_EMPTY_INITIALIZER; mf_format(field, &value, NULL, &ds); VLOG_WARN_RL(&rl, "Invalid value for set field %s: %s", field->name, ds_cstr(&ds)); ds_destroy(&ds); return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } ofpact_put_set_field(ofpacts, field, &value, &mask); return 0; } static enum ofperr decode_OFPAT_RAW12_SET_FIELD(const struct ofp12_action_set_field *oasf, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { return decode_ofpat_set_field(oasf, false, vl_mff_map, tlv_bitmap, ofpacts); } static enum ofperr decode_OFPAT_RAW15_SET_FIELD(const struct ofp12_action_set_field *oasf, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { return decode_ofpat_set_field(oasf, true, vl_mff_map, tlv_bitmap, ofpacts); } static enum ofperr decode_NXAST_RAW_REG_LOAD(const struct nx_action_reg_load *narl, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { struct mf_subfield dst; enum ofperr error; dst.ofs = nxm_decode_ofs(narl->ofs_nbits); dst.n_bits = nxm_decode_n_bits(narl->ofs_nbits); error = mf_vl_mff_mf_from_nxm_header(ntohl(narl->dst), vl_mff_map, &dst.field, tlv_bitmap); if (error) { return error; } error = mf_check_dst(&dst, NULL); if (error) { return error; } /* Reject 'narl' if a bit numbered 'n_bits' or higher is set to 1 in * narl->value. */ if (dst.n_bits < 64 && ntohll(narl->value) >> dst.n_bits) { return OFPERR_OFPBAC_BAD_ARGUMENT; } struct ofpact_set_field *sf = ofpact_put_reg_load(out, dst.field, NULL, NULL); bitwise_put(ntohll(narl->value), sf->value, dst.field->n_bytes, dst.ofs, dst.n_bits); bitwise_put(UINT64_MAX, ofpact_set_field_mask(sf), dst.field->n_bytes, dst.ofs, dst.n_bits); return 0; } static enum ofperr decode_NXAST_RAW_REG_LOAD2(const struct ext_action_header *eah, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { struct ofpbuf b = ofpbuf_const_initializer(eah, ntohs(eah->len)); ofpbuf_pull(&b, OBJECT_OFFSETOF(eah, pad)); union mf_value value, mask; const struct mf_field *field; enum ofperr error; error = mf_vl_mff_nx_pull_entry(&b, vl_mff_map, &field, &value, &mask, tlv_bitmap); if (error) { return error; } if (!is_all_zeros(b.data, b.size)) { return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } if (!field->writable) { VLOG_WARN_RL(&rl, "destination field %s is not writable", field->name); return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } /* Put value and mask. */ ofpact_put_reg_load2(out, field, &value, &mask); return 0; } static void put_set_field(struct ofpbuf *openflow, enum ofp_version ofp_version, enum mf_field_id field, uint64_t value_) { struct ofp12_action_set_field *oasf OVS_UNUSED; int n_bytes = mf_from_id(field)->n_bytes; size_t start_ofs = openflow->size; union mf_value value; value.be64 = htonll(value_ << (8 * (8 - n_bytes))); oasf = put_OFPAT12_SET_FIELD(openflow); openflow->size = openflow->size - sizeof oasf->pad; nx_put_entry(openflow, mf_from_id(field), ofp_version, &value, NULL); pad_ofpat(openflow, start_ofs); } static void put_reg_load(struct ofpbuf *openflow, const struct mf_subfield *dst, uint64_t value) { ovs_assert(dst->n_bits <= 64); struct nx_action_reg_load *narl = put_NXAST_REG_LOAD(openflow); narl->ofs_nbits = nxm_encode_ofs_nbits(dst->ofs, dst->n_bits); narl->dst = htonl(nxm_header_from_mff(dst->field)); narl->value = htonll(value); } static bool next_load_segment(const struct ofpact_set_field *sf, struct mf_subfield *dst, uint64_t *value) { int n_bits = sf->field->n_bits; int n_bytes = sf->field->n_bytes; int start = dst->ofs + dst->n_bits; if (start < n_bits) { dst->field = sf->field; dst->ofs = bitwise_scan(ofpact_set_field_mask(sf), n_bytes, 1, start, n_bits); if (dst->ofs < n_bits) { dst->n_bits = bitwise_scan(ofpact_set_field_mask(sf), n_bytes, 0, dst->ofs + 1, MIN(dst->ofs + 64, n_bits)) - dst->ofs; *value = bitwise_get(sf->value, n_bytes, dst->ofs, dst->n_bits); return true; } } return false; } /* Convert 'sf' to a series of REG_LOADs. */ static void set_field_to_nxast(const struct ofpact_set_field *sf, struct ofpbuf *openflow) { /* If 'sf' cannot be encoded as NXAST_REG_LOAD because it requires an * experimenter OXM or is variable length (or if it came in as * NXAST_REG_LOAD2), encode as NXAST_REG_LOAD2. Otherwise use * NXAST_REG_LOAD, which is backward compatible. */ if (sf->ofpact.raw == NXAST_RAW_REG_LOAD2 || !mf_nxm_header(sf->field->id) || sf->field->variable_len) { struct ext_action_header *eah OVS_UNUSED; size_t start_ofs = openflow->size; eah = put_NXAST_REG_LOAD2(openflow); openflow->size = openflow->size - sizeof eah->pad; nx_put_entry(openflow, sf->field, 0, sf->value, ofpact_set_field_mask(sf)); pad_ofpat(openflow, start_ofs); } else { struct mf_subfield dst; uint64_t value; dst.ofs = dst.n_bits = 0; while (next_load_segment(sf, &dst, &value)) { put_reg_load(openflow, &dst, value); } } } /* Convert 'sf', which must set an entire field, to standard OpenFlow 1.0/1.1 * actions, if we can, falling back to Nicira extensions if we must. * * We check only meta-flow types that can appear within set field actions and * that have a mapping to compatible action types. These struct mf_field * definitions have a defined OXM or NXM header value and specify the field as * writable. */ static void set_field_to_legacy_openflow(const struct ofpact_set_field *sf, enum ofp_version ofp_version, struct ofpbuf *out) { switch ((int) sf->field->id) { case MFF_VLAN_TCI: { ovs_be16 tci = sf->value->be16; bool cfi = (tci & htons(VLAN_CFI)) != 0; uint16_t vid = vlan_tci_to_vid(tci); uint8_t pcp = vlan_tci_to_pcp(tci); if (ofp_version < OFP11_VERSION) { /* NXM_OF_VLAN_TCI to OpenFlow 1.0 mapping: * * If CFI=1, Add or modify VLAN VID & PCP. * If CFI=0, strip VLAN header, if any. */ if (cfi) { put_OFPAT10_SET_VLAN_VID(out, vid); put_OFPAT10_SET_VLAN_PCP(out, pcp); } else { put_OFPAT10_STRIP_VLAN(out); } } else { /* NXM_OF_VLAN_TCI to OpenFlow 1.1 mapping: * * If CFI=1, Add or modify VLAN VID & PCP. * OpenFlow 1.1 set actions only apply if the packet * already has VLAN tags. To be sure that is the case * we have to push a VLAN header. As we do not support * multiple layers of VLANs, this is a no-op, if a VLAN * header already exists. This may backfire, however, * when we start supporting multiple layers of VLANs. * If CFI=0, strip VLAN header, if any. */ if (cfi) { /* Push a VLAN tag, if one was not seen at action validation * time. */ if (!sf->flow_has_vlan) { put_OFPAT11_PUSH_VLAN(out, htons(ETH_TYPE_VLAN_8021Q)); } put_OFPAT11_SET_VLAN_VID(out, vid); put_OFPAT11_SET_VLAN_PCP(out, pcp); } else { /* If the flow did not match on vlan, we have no way of * knowing if the vlan tag exists, so we must POP just to be * sure. */ put_OFPAT11_POP_VLAN(out); } } break; } case MFF_VLAN_VID: { uint16_t vid = ntohs(sf->value->be16) & VLAN_VID_MASK; if (ofp_version == OFP10_VERSION) { put_OFPAT10_SET_VLAN_VID(out, vid); } else { put_OFPAT11_SET_VLAN_VID(out, vid); } break; } case MFF_VLAN_PCP: if (ofp_version == OFP10_VERSION) { put_OFPAT10_SET_VLAN_PCP(out, sf->value->u8); } else { put_OFPAT11_SET_VLAN_PCP(out, sf->value->u8); } break; case MFF_ETH_SRC: put_OFPAT_SET_DL_SRC(out, ofp_version)->dl_addr = sf->value->mac; break; case MFF_ETH_DST: put_OFPAT_SET_DL_DST(out, ofp_version)->dl_addr = sf->value->mac; break; case MFF_IPV4_SRC: put_OFPAT_SET_NW_SRC(out, ofp_version, sf->value->be32); break; case MFF_IPV4_DST: put_OFPAT_SET_NW_DST(out, ofp_version, sf->value->be32); break; case MFF_IP_DSCP: put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value->u8); break; case MFF_IP_DSCP_SHIFTED: put_OFPAT_SET_NW_TOS(out, ofp_version, sf->value->u8 << 2); break; case MFF_IP_ECN: { struct ofpact_ecn ip_ecn = { .ecn = sf->value->u8 }; encode_SET_IP_ECN(&ip_ecn, ofp_version, out); break; } case MFF_TCP_SRC: case MFF_UDP_SRC: put_OFPAT_SET_TP_SRC(out, sf->value->be16); break; case MFF_TCP_DST: case MFF_UDP_DST: put_OFPAT_SET_TP_DST(out, sf->value->be16); break; default: set_field_to_nxast(sf, out); break; } } static void set_field_to_set_field(const struct ofpact_set_field *sf, enum ofp_version ofp_version, struct ofpbuf *out) { struct ofp12_action_set_field *oasf OVS_UNUSED; size_t start_ofs = out->size; oasf = put_OFPAT12_SET_FIELD(out); out->size = out->size - sizeof oasf->pad; nx_put_entry(out, sf->field, ofp_version, sf->value, ofpact_set_field_mask(sf)); pad_ofpat(out, start_ofs); } static void encode_SET_FIELD(const struct ofpact_set_field *sf, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version >= OFP15_VERSION) { /* OF1.5+ only has Set-Field (reg_load is redundant so we drop it * entirely). */ set_field_to_set_field(sf, ofp_version, out); } else if (sf->ofpact.raw == NXAST_RAW_REG_LOAD || sf->ofpact.raw == NXAST_RAW_REG_LOAD2) { /* It came in as reg_load, send it out the same way. */ set_field_to_nxast(sf, out); } else if (ofp_version < OFP12_VERSION) { /* OpenFlow 1.0 and 1.1 don't have Set-Field. */ set_field_to_legacy_openflow(sf, ofp_version, out); } else if (is_all_ones(ofpact_set_field_mask(sf), sf->field->n_bytes)) { /* We're encoding to OpenFlow 1.2, 1.3, or 1.4. The action sets an * entire field, so encode it as OFPAT_SET_FIELD. */ set_field_to_set_field(sf, ofp_version, out); } else { /* We're encoding to OpenFlow 1.2, 1.3, or 1.4. The action cannot be * encoded as OFPAT_SET_FIELD because it does not set an entire field, * so encode it as reg_load. */ set_field_to_nxast(sf, out); } } /* Parses the input argument 'arg' into the key, value, and delimiter * components that are common across the reg_load and set_field action format. * * With an argument like "1->metadata", sets the following pointers to * point within 'arg': * key: "metadata" * value: "1" * delim: "->" * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT set_field_split_str(char *arg, char **key, char **value, char **delim) { char *value_end; *value = arg; value_end = strstr(arg, "->"); *key = value_end + strlen("->"); if (delim) { *delim = value_end; } if (!value_end) { return xasprintf("%s: missing `->'", arg); } if (strlen(value_end) <= strlen("->")) { return xasprintf("%s: missing field name following `->'", arg); } return NULL; } /* Parses a "set_field" action with argument 'arg', appending the parsed * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT set_field_parse__(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { char *value; char *delim; char *key; const struct mf_field *mf; union mf_value sf_value, sf_mask; char *error; error = set_field_split_str(arg, &key, &value, &delim); if (error) { return error; } mf = mf_from_name(key); if (!mf) { return xasprintf("%s is not a valid OXM field name", key); } if (!mf->writable) { return xasprintf("%s is read-only", key); } delim[0] = '\0'; error = mf_parse(mf, value, &sf_value, &sf_mask); if (error) { return error; } if (!mf_is_value_valid(mf, &sf_value)) { return xasprintf("%s is not a valid value for field %s", value, key); } *usable_protocols &= mf->usable_protocols_exact; ofpact_put_set_field(ofpacts, mf, &sf_value, &sf_mask); return NULL; } /* Parses 'arg' as the argument to a "set_field" action, and appends such an * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT parse_SET_FIELD(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { char *copy = xstrdup(arg); char *error = set_field_parse__(copy, ofpacts, usable_protocols); free(copy); return error; } static char * OVS_WARN_UNUSED_RESULT parse_reg_load(char *arg, struct ofpbuf *ofpacts) { struct mf_subfield dst; char *key, *value_str; union mf_value value; char *error; error = set_field_split_str(arg, &key, &value_str, NULL); if (error) { return error; } error = mf_parse_subfield(&dst, key); if (error) { return error; } if (parse_int_string(value_str, (uint8_t *)&value, dst.field->n_bytes, &key)) { return xasprintf("%s: cannot parse integer value", arg); } if (!bitwise_is_all_zeros(&value, dst.field->n_bytes, dst.n_bits, dst.field->n_bytes * 8 - dst.n_bits)) { struct ds ds; ds_init(&ds); mf_format(dst.field, &value, NULL, &ds); error = xasprintf("%s: value %s does not fit into %d bits", arg, ds_cstr(&ds), dst.n_bits); ds_destroy(&ds); return error; } struct ofpact_set_field *sf = ofpact_put_reg_load(ofpacts, dst.field, NULL, NULL); bitwise_copy(&value, dst.field->n_bytes, 0, sf->value, dst.field->n_bytes, dst.ofs, dst.n_bits); bitwise_one(ofpact_set_field_mask(sf), dst.field->n_bytes, dst.ofs, dst.n_bits); return NULL; } static void format_SET_FIELD(const struct ofpact_set_field *a, struct ds *s) { if (a->ofpact.raw == NXAST_RAW_REG_LOAD) { struct mf_subfield dst; uint64_t value; dst.ofs = dst.n_bits = 0; while (next_load_segment(a, &dst, &value)) { ds_put_format(s, "%sload:%s%#"PRIx64"%s->%s", colors.special, colors.end, value, colors.special, colors.end); mf_format_subfield(&dst, s); ds_put_char(s, ','); } ds_chomp(s, ','); } else { ds_put_format(s, "%sset_field:%s", colors.special, colors.end); mf_format(a->field, a->value, ofpact_set_field_mask(a), s); ds_put_format(s, "%s->%s%s", colors.special, colors.end, a->field->name); } } /* Appends an OFPACT_SET_FIELD ofpact with enough space for the value and mask * for the 'field' to 'ofpacts' and returns it. Fills in the value from * 'value', if non-NULL, and mask from 'mask' if non-NULL. If 'value' is * non-NULL and 'mask' is NULL, an all-ones mask will be filled in. */ struct ofpact_set_field * ofpact_put_set_field(struct ofpbuf *ofpacts, const struct mf_field *field, const void *value, const void *mask) { struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts); sf->field = field; /* Fill in the value and mask if given, otherwise put zeroes so that the * caller may fill in the value and mask itself. */ if (value) { ofpbuf_put_uninit(ofpacts, 2 * field->n_bytes); sf = ofpacts->header; memcpy(sf->value, value, field->n_bytes); if (mask) { memcpy(ofpact_set_field_mask(sf), mask, field->n_bytes); } else { memset(ofpact_set_field_mask(sf), 0xff, field->n_bytes); } } else { ofpbuf_put_zeros(ofpacts, 2 * field->n_bytes); sf = ofpacts->header; } /* Update length. */ ofpact_finish_SET_FIELD(ofpacts, &sf); return sf; } /* Appends an OFPACT_SET_FIELD ofpact to 'ofpacts' and returns it. The ofpact * is marked such that, if possible, it will be translated to OpenFlow as * NXAST_REG_LOAD extension actions rather than OFPAT_SET_FIELD, either because * that was the way that the action was expressed when it came into OVS or for * backward compatibility. */ struct ofpact_set_field * ofpact_put_reg_load(struct ofpbuf *ofpacts, const struct mf_field *field, const void *value, const void *mask) { struct ofpact_set_field *sf = ofpact_put_set_field(ofpacts, field, value, mask); sf->ofpact.raw = NXAST_RAW_REG_LOAD; return sf; } struct ofpact_set_field * ofpact_put_reg_load2(struct ofpbuf *ofpacts, const struct mf_field *field, const void *value, const void *mask) { struct ofpact_set_field *sf = ofpact_put_set_field(ofpacts, field, value, mask); sf->ofpact.raw = NXAST_RAW_REG_LOAD2; return sf; } /* Action structure for NXAST_STACK_PUSH and NXAST_STACK_POP. * * Pushes (or pops) field[offset: offset + n_bits] to (or from) * top of the stack. */ struct nx_action_stack { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_STACK_PUSH or NXAST_STACK_POP. */ ovs_be16 offset; /* Bit offset into the field. */ /* Followed by: * - OXM/NXM header for field to push or pop (4 or 8 bytes). * - ovs_be16 'n_bits', the number of bits to extract from the field. * - Enough 0-bytes to pad out the action to 24 bytes. */ uint8_t pad[12]; /* See above. */ }; OFP_ASSERT(sizeof(struct nx_action_stack) == 24); static enum ofperr decode_stack_action(const struct nx_action_stack *nasp, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpact_stack *stack_action) { enum ofperr error; stack_action->subfield.ofs = ntohs(nasp->offset); struct ofpbuf b = ofpbuf_const_initializer(nasp, sizeof *nasp); ofpbuf_pull(&b, OBJECT_OFFSETOF(nasp, pad)); error = mf_vl_mff_nx_pull_header(&b, vl_mff_map, &stack_action->subfield.field, NULL, tlv_bitmap); if (error) { return error; } stack_action->subfield.n_bits = ntohs(*(const ovs_be16 *) b.data); ofpbuf_pull(&b, 2); if (!is_all_zeros(b.data, b.size)) { return OFPERR_NXBRC_MUST_BE_ZERO; } return 0; } static enum ofperr decode_NXAST_RAW_STACK_PUSH(const struct nx_action_stack *nasp, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpact_stack *push = ofpact_put_STACK_PUSH(ofpacts); enum ofperr error = decode_stack_action(nasp, vl_mff_map, tlv_bitmap, push); return error ? error : nxm_stack_push_check(push, NULL); } static enum ofperr decode_NXAST_RAW_STACK_POP(const struct nx_action_stack *nasp, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpact_stack *pop = ofpact_put_STACK_POP(ofpacts); enum ofperr error = decode_stack_action(nasp, vl_mff_map, tlv_bitmap, pop); return error ? error : nxm_stack_pop_check(pop, NULL); } static void encode_STACK_op(const struct ofpact_stack *stack_action, struct nx_action_stack *nasp) { struct ofpbuf b; ovs_be16 n_bits; nasp->offset = htons(stack_action->subfield.ofs); ofpbuf_use_stack(&b, nasp, ntohs(nasp->len)); ofpbuf_put_uninit(&b, OBJECT_OFFSETOF(nasp, pad)); nx_put_mff_header(&b, stack_action->subfield.field, 0, false); n_bits = htons(stack_action->subfield.n_bits); ofpbuf_put(&b, &n_bits, sizeof n_bits); } static void encode_STACK_PUSH(const struct ofpact_stack *stack, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { encode_STACK_op(stack, put_NXAST_STACK_PUSH(out)); } static void encode_STACK_POP(const struct ofpact_stack *stack, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { encode_STACK_op(stack, put_NXAST_STACK_POP(out)); } static char * OVS_WARN_UNUSED_RESULT parse_STACK_PUSH(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return nxm_parse_stack_action(ofpact_put_STACK_PUSH(ofpacts), arg); } static char * OVS_WARN_UNUSED_RESULT parse_STACK_POP(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return nxm_parse_stack_action(ofpact_put_STACK_POP(ofpacts), arg); } static void format_STACK_PUSH(const struct ofpact_stack *a, struct ds *s) { nxm_format_stack_push(a, s); } static void format_STACK_POP(const struct ofpact_stack *a, struct ds *s) { nxm_format_stack_pop(a, s); } /* Action structure for NXAST_DEC_TTL_CNT_IDS. * * If the packet is not IPv4 or IPv6, does nothing. For IPv4 or IPv6, if the * TTL or hop limit is at least 2, decrements it by 1. Otherwise, if TTL or * hop limit is 0 or 1, sends a packet-in to the controllers with each of the * 'n_controllers' controller IDs specified in 'cnt_ids'. * * (This differs from NXAST_DEC_TTL in that for NXAST_DEC_TTL the packet-in is * sent only to controllers with id 0.) */ struct nx_action_cnt_ids { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length including slaves. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_DEC_TTL_CNT_IDS. */ ovs_be16 n_controllers; /* Number of controllers. */ uint8_t zeros[4]; /* Must be zero. */ /* Followed by 1 or more controller ids. * * uint16_t cnt_ids[]; // Controller ids. * uint8_t pad[]; // Must be 0 to 8-byte align cnt_ids[]. */ }; OFP_ASSERT(sizeof(struct nx_action_cnt_ids) == 16); static enum ofperr decode_OFPAT_RAW_DEC_NW_TTL(struct ofpbuf *out) { uint16_t id = 0; struct ofpact_cnt_ids *ids; enum ofperr error = 0; ids = ofpact_put_DEC_TTL(out); ids->n_controllers = 1; ofpbuf_put(out, &id, sizeof id); ids = out->header; ofpact_finish_DEC_TTL(out, &ids); return error; } static enum ofperr decode_NXAST_RAW_DEC_TTL_CNT_IDS(const struct nx_action_cnt_ids *nac_ids, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_cnt_ids *ids; size_t ids_size; int i; ids = ofpact_put_DEC_TTL(out); ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS; ids->n_controllers = ntohs(nac_ids->n_controllers); ids_size = ntohs(nac_ids->len) - sizeof *nac_ids; if (!is_all_zeros(nac_ids->zeros, sizeof nac_ids->zeros)) { return OFPERR_NXBRC_MUST_BE_ZERO; } if (ids_size < ids->n_controllers * sizeof(ovs_be16)) { VLOG_WARN_RL(&rl, "Nicira action dec_ttl_cnt_ids only has %"PRIuSIZE" " "bytes allocated for controller ids. %"PRIuSIZE" bytes " "are required for %"PRIu16" controllers.", ids_size, ids->n_controllers * sizeof(ovs_be16), ids->n_controllers); return OFPERR_OFPBAC_BAD_LEN; } for (i = 0; i < ids->n_controllers; i++) { uint16_t id = ntohs(((ovs_be16 *)(nac_ids + 1))[i]); ofpbuf_put(out, &id, sizeof id); ids = out->header; } ofpact_finish_DEC_TTL(out, &ids); return 0; } static void encode_DEC_TTL(const struct ofpact_cnt_ids *dec_ttl, enum ofp_version ofp_version, struct ofpbuf *out) { if (dec_ttl->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS || dec_ttl->n_controllers != 1 || dec_ttl->cnt_ids[0] != 0) { struct nx_action_cnt_ids *nac_ids = put_NXAST_DEC_TTL_CNT_IDS(out); int ids_len = ROUND_UP(2 * dec_ttl->n_controllers, OFP_ACTION_ALIGN); ovs_be16 *ids; size_t i; nac_ids->len = htons(ntohs(nac_ids->len) + ids_len); nac_ids->n_controllers = htons(dec_ttl->n_controllers); ids = ofpbuf_put_zeros(out, ids_len); for (i = 0; i < dec_ttl->n_controllers; i++) { ids[i] = htons(dec_ttl->cnt_ids[i]); } } else { put_OFPAT_DEC_NW_TTL(out, ofp_version); } } static void parse_noargs_dec_ttl(struct ofpbuf *ofpacts) { struct ofpact_cnt_ids *ids; uint16_t id = 0; ofpact_put_DEC_TTL(ofpacts); ofpbuf_put(ofpacts, &id, sizeof id); ids = ofpacts->header; ids->n_controllers++; ofpact_finish_DEC_TTL(ofpacts, &ids); } static char * OVS_WARN_UNUSED_RESULT parse_DEC_TTL(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { if (*arg == '\0') { parse_noargs_dec_ttl(ofpacts); } else { struct ofpact_cnt_ids *ids; char *cntr; ids = ofpact_put_DEC_TTL(ofpacts); ids->ofpact.raw = NXAST_RAW_DEC_TTL_CNT_IDS; for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL; cntr = strtok_r(NULL, ", ", &arg)) { uint16_t id = atoi(cntr); ofpbuf_put(ofpacts, &id, sizeof id); ids = ofpacts->header; ids->n_controllers++; } if (!ids->n_controllers) { return xstrdup("dec_ttl_cnt_ids: expected at least one controller " "id."); } ofpact_finish_DEC_TTL(ofpacts, &ids); } return NULL; } static void format_DEC_TTL(const struct ofpact_cnt_ids *a, struct ds *s) { size_t i; ds_put_format(s, "%sdec_ttl%s", colors.paren, colors.end); if (a->ofpact.raw == NXAST_RAW_DEC_TTL_CNT_IDS) { ds_put_format(s, "%s(%s", colors.paren, colors.end); for (i = 0; i < a->n_controllers; i++) { if (i) { ds_put_cstr(s, ","); } ds_put_format(s, "%"PRIu16, a->cnt_ids[i]); } ds_put_format(s, "%s)%s", colors.paren, colors.end); } } /* Set MPLS label actions. */ static enum ofperr decode_OFPAT_RAW_SET_MPLS_LABEL(ovs_be32 label, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_MPLS_LABEL(out)->label = label; return 0; } static void encode_SET_MPLS_LABEL(const struct ofpact_mpls_label *label, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version < OFP12_VERSION) { put_OFPAT_SET_MPLS_LABEL(out, ofp_version, label->label); } else { put_set_field(out, ofp_version, MFF_MPLS_LABEL, ntohl(label->label)); } } static char * OVS_WARN_UNUSED_RESULT parse_SET_MPLS_LABEL(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_mpls_label *mpls_label = ofpact_put_SET_MPLS_LABEL(ofpacts); if (*arg == '\0') { return xstrdup("set_mpls_label: expected label."); } mpls_label->label = htonl(atoi(arg)); return NULL; } static void format_SET_MPLS_LABEL(const struct ofpact_mpls_label *a, struct ds *s) { ds_put_format(s, "%sset_mpls_label(%s%"PRIu32"%s)%s", colors.paren, colors.end, ntohl(a->label), colors.paren, colors.end); } /* Set MPLS TC actions. */ static enum ofperr decode_OFPAT_RAW_SET_MPLS_TC(uint8_t tc, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_MPLS_TC(out)->tc = tc; return 0; } static void encode_SET_MPLS_TC(const struct ofpact_mpls_tc *tc, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version < OFP12_VERSION) { put_OFPAT_SET_MPLS_TC(out, ofp_version, tc->tc); } else { put_set_field(out, ofp_version, MFF_MPLS_TC, tc->tc); } } static char * OVS_WARN_UNUSED_RESULT parse_SET_MPLS_TC(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_mpls_tc *mpls_tc = ofpact_put_SET_MPLS_TC(ofpacts); if (*arg == '\0') { return xstrdup("set_mpls_tc: expected tc."); } mpls_tc->tc = atoi(arg); return NULL; } static void format_SET_MPLS_TC(const struct ofpact_mpls_tc *a, struct ds *s) { ds_put_format(s, "%sset_mpls_ttl(%s%"PRIu8"%s)%s", colors.paren, colors.end, a->tc, colors.paren, colors.end); } /* Set MPLS TTL actions. */ static enum ofperr decode_OFPAT_RAW_SET_MPLS_TTL(uint8_t ttl, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_MPLS_TTL(out)->ttl = ttl; return 0; } static void encode_SET_MPLS_TTL(const struct ofpact_mpls_ttl *ttl, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_SET_MPLS_TTL(out, ofp_version, ttl->ttl); } /* Parses 'arg' as the argument to a "set_mpls_ttl" action, and appends such an * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT parse_SET_MPLS_TTL(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_mpls_ttl *mpls_ttl = ofpact_put_SET_MPLS_TTL(ofpacts); if (*arg == '\0') { return xstrdup("set_mpls_ttl: expected ttl."); } mpls_ttl->ttl = atoi(arg); return NULL; } static void format_SET_MPLS_TTL(const struct ofpact_mpls_ttl *a, struct ds *s) { ds_put_format(s, "%sset_mpls_ttl(%s%"PRIu8"%s)%s", colors.paren, colors.end, a->ttl, colors.paren, colors.end); } /* Decrement MPLS TTL actions. */ static enum ofperr decode_OFPAT_RAW_DEC_MPLS_TTL(struct ofpbuf *out) { ofpact_put_DEC_MPLS_TTL(out); return 0; } static void encode_DEC_MPLS_TTL(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_DEC_MPLS_TTL(out, ofp_version); } static char * OVS_WARN_UNUSED_RESULT parse_DEC_MPLS_TTL(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_DEC_MPLS_TTL(ofpacts); return NULL; } static void format_DEC_MPLS_TTL(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%sdec_mpls_ttl%s", colors.value, colors.end); } /* Push MPLS label action. */ static enum ofperr decode_OFPAT_RAW_PUSH_MPLS(ovs_be16 ethertype, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_push_mpls *oam; if (!eth_type_mpls(ethertype)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } oam = ofpact_put_PUSH_MPLS(out); oam->ethertype = ethertype; return 0; } static void encode_PUSH_MPLS(const struct ofpact_push_mpls *push_mpls, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_PUSH_MPLS(out, ofp_version, push_mpls->ethertype); } static char * OVS_WARN_UNUSED_RESULT parse_PUSH_MPLS(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint16_t ethertype; char *error; error = str_to_u16(arg, "push_mpls", &ethertype); if (!error) { ofpact_put_PUSH_MPLS(ofpacts)->ethertype = htons(ethertype); } return error; } static void format_PUSH_MPLS(const struct ofpact_push_mpls *a, struct ds *s) { ds_put_format(s, "%spush_mpls:%s0x%04"PRIx16, colors.param, colors.end, ntohs(a->ethertype)); } /* Pop MPLS label action. */ static enum ofperr decode_OFPAT_RAW_POP_MPLS(ovs_be16 ethertype, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_POP_MPLS(out)->ethertype = ethertype; return 0; } static void encode_POP_MPLS(const struct ofpact_pop_mpls *pop_mpls, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_POP_MPLS(out, ofp_version, pop_mpls->ethertype); } static char * OVS_WARN_UNUSED_RESULT parse_POP_MPLS(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint16_t ethertype; char *error; error = str_to_u16(arg, "pop_mpls", &ethertype); if (!error) { ofpact_put_POP_MPLS(ofpacts)->ethertype = htons(ethertype); } return error; } static void format_POP_MPLS(const struct ofpact_pop_mpls *a, struct ds *s) { ds_put_format(s, "%spop_mpls:%s0x%04"PRIx16, colors.param, colors.end, ntohs(a->ethertype)); } /* Set tunnel ID actions. */ static enum ofperr decode_NXAST_RAW_SET_TUNNEL(uint32_t tun_id, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out); tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL; tunnel->tun_id = tun_id; return 0; } static enum ofperr decode_NXAST_RAW_SET_TUNNEL64(uint64_t tun_id, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_tunnel *tunnel = ofpact_put_SET_TUNNEL(out); tunnel->ofpact.raw = NXAST_RAW_SET_TUNNEL64; tunnel->tun_id = tun_id; return 0; } static void encode_SET_TUNNEL(const struct ofpact_tunnel *tunnel, enum ofp_version ofp_version, struct ofpbuf *out) { uint64_t tun_id = tunnel->tun_id; if (ofp_version < OFP12_VERSION) { if (tun_id <= UINT32_MAX && tunnel->ofpact.raw != NXAST_RAW_SET_TUNNEL64) { put_NXAST_SET_TUNNEL(out, tun_id); } else { put_NXAST_SET_TUNNEL64(out, tun_id); } } else { put_set_field(out, ofp_version, MFF_TUN_ID, tun_id); } } static char * OVS_WARN_UNUSED_RESULT parse_set_tunnel(char *arg, struct ofpbuf *ofpacts, enum ofp_raw_action_type raw) { struct ofpact_tunnel *tunnel; tunnel = ofpact_put_SET_TUNNEL(ofpacts); tunnel->ofpact.raw = raw; return str_to_u64(arg, &tunnel->tun_id); } static char * OVS_WARN_UNUSED_RESULT parse_SET_TUNNEL(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return parse_set_tunnel(arg, ofpacts, NXAST_RAW_SET_TUNNEL); } static void format_SET_TUNNEL(const struct ofpact_tunnel *a, struct ds *s) { ds_put_format(s, "%sset_tunnel%s:%s%#"PRIx64, colors.param, (a->tun_id > UINT32_MAX || a->ofpact.raw == NXAST_RAW_SET_TUNNEL64 ? "64" : ""), colors.end, a->tun_id); } /* Set queue action. */ static enum ofperr decode_OFPAT_RAW_SET_QUEUE(uint32_t queue_id, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { ofpact_put_SET_QUEUE(out)->queue_id = queue_id; return 0; } static void encode_SET_QUEUE(const struct ofpact_queue *queue, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_SET_QUEUE(out, ofp_version, queue->queue_id); } static char * OVS_WARN_UNUSED_RESULT parse_SET_QUEUE(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id); } static void format_SET_QUEUE(const struct ofpact_queue *a, struct ds *s) { ds_put_format(s, "%sset_queue:%s%"PRIu32, colors.param, colors.end, a->queue_id); } /* Pop queue action. */ static enum ofperr decode_NXAST_RAW_POP_QUEUE(struct ofpbuf *out) { ofpact_put_POP_QUEUE(out); return 0; } static void encode_POP_QUEUE(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { put_NXAST_POP_QUEUE(out); } static char * OVS_WARN_UNUSED_RESULT parse_POP_QUEUE(const char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_POP_QUEUE(ofpacts); return NULL; } static void format_POP_QUEUE(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%spop_queue%s", colors.value, colors.end); } /* Action structure for NXAST_FIN_TIMEOUT. * * This action changes the idle timeout or hard timeout, or both, of this * OpenFlow rule when the rule matches a TCP packet with the FIN or RST flag. * When such a packet is observed, the action reduces the rule's idle timeout * to 'fin_idle_timeout' and its hard timeout to 'fin_hard_timeout'. This * action has no effect on an existing timeout that is already shorter than the * one that the action specifies. A 'fin_idle_timeout' or 'fin_hard_timeout' * of zero has no effect on the respective timeout. * * 'fin_idle_timeout' and 'fin_hard_timeout' are measured in seconds. * 'fin_hard_timeout' specifies time since the flow's creation, not since the * receipt of the FIN or RST. * * This is useful for quickly discarding learned TCP flows that otherwise will * take a long time to expire. * * This action is intended for use with an OpenFlow rule that matches only a * single TCP flow. If the rule matches multiple TCP flows (e.g. it wildcards * all TCP traffic, or all TCP traffic to a particular port), then any FIN or * RST in any of those flows will cause the entire OpenFlow rule to expire * early, which is not normally desirable. */ struct nx_action_fin_timeout { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_FIN_TIMEOUT. */ ovs_be16 fin_idle_timeout; /* New idle timeout, if nonzero. */ ovs_be16 fin_hard_timeout; /* New hard timeout, if nonzero. */ ovs_be16 pad; /* Must be zero. */ }; OFP_ASSERT(sizeof(struct nx_action_fin_timeout) == 16); static enum ofperr decode_NXAST_RAW_FIN_TIMEOUT(const struct nx_action_fin_timeout *naft, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_fin_timeout *oft; oft = ofpact_put_FIN_TIMEOUT(out); oft->fin_idle_timeout = ntohs(naft->fin_idle_timeout); oft->fin_hard_timeout = ntohs(naft->fin_hard_timeout); return 0; } static void encode_FIN_TIMEOUT(const struct ofpact_fin_timeout *fin_timeout, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct nx_action_fin_timeout *naft = put_NXAST_FIN_TIMEOUT(out); naft->fin_idle_timeout = htons(fin_timeout->fin_idle_timeout); naft->fin_hard_timeout = htons(fin_timeout->fin_hard_timeout); } static char * OVS_WARN_UNUSED_RESULT parse_FIN_TIMEOUT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(ofpacts); char *key, *value; while (ofputil_parse_key_value(&arg, &key, &value)) { char *error; if (!strcmp(key, "idle_timeout")) { error = str_to_u16(value, key, &oft->fin_idle_timeout); } else if (!strcmp(key, "hard_timeout")) { error = str_to_u16(value, key, &oft->fin_hard_timeout); } else { error = xasprintf("invalid key '%s' in 'fin_timeout' argument", key); } if (error) { return error; } } return NULL; } static void format_FIN_TIMEOUT(const struct ofpact_fin_timeout *a, struct ds *s) { ds_put_format(s, "%sfin_timeout(%s", colors.paren, colors.end); if (a->fin_idle_timeout) { ds_put_format(s, "%sidle_timeout=%s%"PRIu16",", colors.param, colors.end, a->fin_idle_timeout); } if (a->fin_hard_timeout) { ds_put_format(s, "%shard_timeout=%s%"PRIu16",", colors.param, colors.end, a->fin_hard_timeout); } ds_chomp(s, ','); ds_put_format(s, "%s)%s", colors.paren, colors.end); } /* Action structures for NXAST_RESUBMIT and NXAST_RESUBMIT_TABLE. * * These actions search one of the switch's flow tables: * * - For NXAST_RESUBMIT_TABLE only, if the 'table' member is not 255, then * it specifies the table to search. * * - Otherwise (for NXAST_RESUBMIT_TABLE with a 'table' of 255, or for * NXAST_RESUBMIT regardless of 'table'), it searches the current flow * table, that is, the OpenFlow flow table that contains the flow from * which this action was obtained. If this action did not come from a * flow table (e.g. it came from an OFPT_PACKET_OUT message), then table 0 * is the current table. * * The flow table lookup uses a flow that may be slightly modified from the * original lookup: * * - For NXAST_RESUBMIT, the 'in_port' member of struct nx_action_resubmit * is used as the flow's in_port. * * - For NXAST_RESUBMIT_TABLE, if the 'in_port' member is not OFPP_IN_PORT, * then its value is used as the flow's in_port. Otherwise, the original * in_port is used. * * - If actions that modify the flow (e.g. OFPAT_SET_VLAN_VID) precede the * resubmit action, then the flow is updated with the new values. * * Following the lookup, the original in_port is restored. * * If the modified flow matched in the flow table, then the corresponding * actions are executed. Afterward, actions following the resubmit in the * original set of actions, if any, are executed; any changes made to the * packet (e.g. changes to VLAN) by secondary actions persist when those * actions are executed, although the original in_port is restored. * * Resubmit actions may be used any number of times within a set of actions. * * Resubmit actions may nest. To prevent infinite loops and excessive resource * use, the implementation may limit nesting depth and the total number of * resubmits: * * - Open vSwitch 1.0.1 and earlier did not support recursion. * * - Open vSwitch 1.0.2 and 1.0.3 limited recursion to 8 levels. * * - Open vSwitch 1.1 and 1.2 limited recursion to 16 levels. * * - Open vSwitch 1.2 through 1.8 limited recursion to 32 levels. * * - Open vSwitch 1.9 through 2.0 limited recursion to 64 levels. * * - Open vSwitch 2.1 through 2.5 limited recursion to 64 levels and impose * a total limit of 4,096 resubmits per flow translation (earlier versions * did not impose any total limit). * * NXAST_RESUBMIT ignores 'table' and 'pad'. NXAST_RESUBMIT_TABLE requires * 'pad' to be all-bits-zero. * * Open vSwitch 1.0.1 and earlier did not support recursion. Open vSwitch * before 1.2.90 did not support NXAST_RESUBMIT_TABLE. */ struct nx_action_resubmit { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_RESUBMIT. */ ovs_be16 in_port; /* New in_port for checking flow table. */ uint8_t table; /* NXAST_RESUBMIT_TABLE: table to use. */ uint8_t pad[3]; }; OFP_ASSERT(sizeof(struct nx_action_resubmit) == 16); static enum ofperr decode_NXAST_RAW_RESUBMIT(uint16_t port, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_resubmit *resubmit; resubmit = ofpact_put_RESUBMIT(out); resubmit->ofpact.raw = NXAST_RAW_RESUBMIT; resubmit->in_port = u16_to_ofp(port); resubmit->table_id = 0xff; return 0; } static enum ofperr decode_NXAST_RAW_RESUBMIT_TABLE(const struct nx_action_resubmit *nar, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_resubmit *resubmit; if (nar->pad[0] || nar->pad[1] || nar->pad[2]) { return OFPERR_OFPBAC_BAD_ARGUMENT; } resubmit = ofpact_put_RESUBMIT(out); resubmit->ofpact.raw = NXAST_RAW_RESUBMIT_TABLE; resubmit->in_port = u16_to_ofp(ntohs(nar->in_port)); resubmit->table_id = nar->table; return 0; } static void encode_RESUBMIT(const struct ofpact_resubmit *resubmit, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { uint16_t in_port = ofp_to_u16(resubmit->in_port); if (resubmit->table_id == 0xff && resubmit->ofpact.raw != NXAST_RAW_RESUBMIT_TABLE) { put_NXAST_RESUBMIT(out, in_port); } else { struct nx_action_resubmit *nar = put_NXAST_RESUBMIT_TABLE(out); nar->table = resubmit->table_id; nar->in_port = htons(in_port); } } static char * OVS_WARN_UNUSED_RESULT parse_RESUBMIT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_resubmit *resubmit; char *in_port_s, *table_s; resubmit = ofpact_put_RESUBMIT(ofpacts); in_port_s = strsep(&arg, ","); if (in_port_s && in_port_s[0]) { if (!ofputil_port_from_string(in_port_s, &resubmit->in_port)) { return xasprintf("%s: resubmit to unknown port", in_port_s); } } else { resubmit->in_port = OFPP_IN_PORT; } table_s = strsep(&arg, ","); if (table_s && table_s[0]) { uint32_t table_id = 0; char *error; error = str_to_u32(table_s, &table_id); if (error) { return error; } resubmit->table_id = table_id; } else { resubmit->table_id = 255; } if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) { return xstrdup("at least one \"in_port\" or \"table\" must be " "specified on resubmit"); } return NULL; } static void format_RESUBMIT(const struct ofpact_resubmit *a, struct ds *s) { if (a->in_port != OFPP_IN_PORT && a->table_id == 255) { ds_put_format(s, "%sresubmit:%s", colors.special, colors.end); ofputil_format_port(a->in_port, s); } else { ds_put_format(s, "%sresubmit(%s", colors.paren, colors.end); if (a->in_port != OFPP_IN_PORT) { ofputil_format_port(a->in_port, s); } ds_put_char(s, ','); if (a->table_id != 255) { ds_put_format(s, "%"PRIu8, a->table_id); } ds_put_format(s, "%s)%s", colors.paren, colors.end); } } /* Action structure for NXAST_LEARN. * * This action adds or modifies a flow in an OpenFlow table, similar to * OFPT_FLOW_MOD with OFPFC_MODIFY_STRICT as 'command'. The new flow has the * specified idle timeout, hard timeout, priority, cookie, and flags. The new * flow's match criteria and actions are built by applying each of the series * of flow_mod_spec elements included as part of the action. * * A flow_mod_spec starts with a 16-bit header. A header that is all-bits-0 is * a no-op used for padding the action as a whole to a multiple of 8 bytes in * length. Otherwise, the flow_mod_spec can be thought of as copying 'n_bits' * bits from a source to a destination. In this case, the header contains * multiple fields: * * 15 14 13 12 11 10 0 * +------+---+------+---------------------------------+ * | 0 |src| dst | n_bits | * +------+---+------+---------------------------------+ * * The meaning and format of a flow_mod_spec depends on 'src' and 'dst'. The * following table summarizes the meaning of each possible combination. * Details follow the table: * * src dst meaning * --- --- ---------------------------------------------------------- * 0 0 Add match criteria based on value in a field. * 1 0 Add match criteria based on an immediate value. * 0 1 Add NXAST_REG_LOAD action to copy field into a different field. * 1 1 Add NXAST_REG_LOAD action to load immediate value into a field. * 0 2 Add OFPAT_OUTPUT action to output to port from specified field. * All other combinations are undefined and not allowed. * * The flow_mod_spec header is followed by a source specification and a * destination specification. The format and meaning of the source * specification depends on 'src': * * - If 'src' is 0, the source bits are taken from a field in the flow to * which this action is attached. (This should be a wildcarded field. If * its value is fully specified then the source bits being copied have * constant values.) * * The source specification is an ovs_be32 'field' and an ovs_be16 'ofs'. * 'field' is an nxm_header with nxm_hasmask=0, and 'ofs' the starting bit * offset within that field. The source bits are field[ofs:ofs+n_bits-1]. * 'field' and 'ofs' are subject to the same restrictions as the source * field in NXAST_REG_MOVE. * * - If 'src' is 1, the source bits are a constant value. The source * specification is (n_bits+15)/16*2 bytes long. Taking those bytes as a * number in network order, the source bits are the 'n_bits' * least-significant bits. The switch will report an error if other bits * in the constant are nonzero. * * The flow_mod_spec destination specification, for 'dst' of 0 or 1, is an * ovs_be32 'field' and an ovs_be16 'ofs'. 'field' is an nxm_header with * nxm_hasmask=0 and 'ofs' is a starting bit offset within that field. The * meaning of the flow_mod_spec depends on 'dst': * * - If 'dst' is 0, the flow_mod_spec specifies match criteria for the new * flow. The new flow matches only if bits field[ofs:ofs+n_bits-1] in a * packet equal the source bits. 'field' may be any nxm_header with * nxm_hasmask=0 that is allowed in NXT_FLOW_MOD. * * Order is significant. Earlier flow_mod_specs must satisfy any * prerequisites for matching fields specified later, by copying constant * values into prerequisite fields. * * The switch will reject flow_mod_specs that do not satisfy NXM masking * restrictions. * * - If 'dst' is 1, the flow_mod_spec specifies an NXAST_REG_LOAD action for * the new flow. The new flow copies the source bits into * field[ofs:ofs+n_bits-1]. Actions are executed in the same order as the * flow_mod_specs. * * A single NXAST_REG_LOAD action writes no more than 64 bits, so n_bits * greater than 64 yields multiple NXAST_REG_LOAD actions. * * The flow_mod_spec destination spec for 'dst' of 2 (when 'src' is 0) is * empty. It has the following meaning: * * - The flow_mod_spec specifies an OFPAT_OUTPUT action for the new flow. * The new flow outputs to the OpenFlow port specified by the source field. * Of the special output ports with value OFPP_MAX or larger, OFPP_IN_PORT, * OFPP_FLOOD, OFPP_LOCAL, and OFPP_ALL are supported. Other special ports * may not be used. * * Resource Management * ------------------- * * A switch has a finite amount of flow table space available for learning. * When this space is exhausted, no new learning table entries will be learned * until some existing flow table entries expire. The controller should be * prepared to handle this by flooding (which can be implemented as a * low-priority flow). * * If a learned flow matches a single TCP stream with a relatively long * timeout, one may make the best of resource constraints by setting * 'fin_idle_timeout' or 'fin_hard_timeout' (both measured in seconds), or * both, to shorter timeouts. When either of these is specified as a nonzero * value, OVS adds a NXAST_FIN_TIMEOUT action, with the specified timeouts, to * the learned flow. * * Examples * -------- * * The following examples give a prose description of the flow_mod_specs along * with informal notation for how those would be represented and a hex dump of * the bytes that would be required. * * These examples could work with various nx_action_learn parameters. Typical * values would be idle_timeout=OFP_FLOW_PERMANENT, hard_timeout=60, * priority=OFP_DEFAULT_PRIORITY, flags=0, table_id=10. * * 1. Learn input port based on the source MAC, with lookup into * NXM_NX_REG1[16:31] by resubmit to in_port=99: * * Match on in_port=99: * ovs_be16(src=1, dst=0, n_bits=16), 20 10 * ovs_be16(99), 00 63 * ovs_be32(NXM_OF_IN_PORT), ovs_be16(0) 00 00 00 02 00 00 * * Match Ethernet destination on Ethernet source from packet: * ovs_be16(src=0, dst=0, n_bits=48), 00 30 * ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0) 00 00 04 06 00 00 * ovs_be32(NXM_OF_ETH_DST), ovs_be16(0) 00 00 02 06 00 00 * * Set NXM_NX_REG1[16:31] to the packet's input port: * ovs_be16(src=0, dst=1, n_bits=16), 08 10 * ovs_be32(NXM_OF_IN_PORT), ovs_be16(0) 00 00 00 02 00 00 * ovs_be32(NXM_NX_REG1), ovs_be16(16) 00 01 02 04 00 10 * * Given a packet that arrived on port A with Ethernet source address B, * this would set up the flow "in_port=99, dl_dst=B, * actions=load:A->NXM_NX_REG1[16..31]". * * In syntax accepted by ovs-ofctl, this action is: learn(in_port=99, * NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[], * load:NXM_OF_IN_PORT[]->NXM_NX_REG1[16..31]) * * 2. Output to input port based on the source MAC and VLAN VID, with lookup * into NXM_NX_REG1[16:31]: * * Match on same VLAN ID as packet: * ovs_be16(src=0, dst=0, n_bits=12), 00 0c * ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0) 00 00 08 02 00 00 * ovs_be32(NXM_OF_VLAN_TCI), ovs_be16(0) 00 00 08 02 00 00 * * Match Ethernet destination on Ethernet source from packet: * ovs_be16(src=0, dst=0, n_bits=48), 00 30 * ovs_be32(NXM_OF_ETH_SRC), ovs_be16(0) 00 00 04 06 00 00 * ovs_be32(NXM_OF_ETH_DST), ovs_be16(0) 00 00 02 06 00 00 * * Output to the packet's input port: * ovs_be16(src=0, dst=2, n_bits=16), 10 10 * ovs_be32(NXM_OF_IN_PORT), ovs_be16(0) 00 00 00 02 00 00 * * Given a packet that arrived on port A with Ethernet source address B in * VLAN C, this would set up the flow "dl_dst=B, vlan_vid=C, * actions=output:A". * * In syntax accepted by ovs-ofctl, this action is: * learn(NXM_OF_VLAN_TCI[0..11], NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[], * output:NXM_OF_IN_PORT[]) * * 3. Here's a recipe for a very simple-minded MAC learning switch. It uses a * 10-second MAC expiration time to make it easier to see what's going on * * ovs-vsctl del-controller br0 * ovs-ofctl del-flows br0 * ovs-ofctl add-flow br0 "table=0 actions=learn(table=1, \ hard_timeout=10, NXM_OF_VLAN_TCI[0..11], \ NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[], \ output:NXM_OF_IN_PORT[]), resubmit(,1)" * ovs-ofctl add-flow br0 "table=1 priority=0 actions=flood" * * You can then dump the MAC learning table with: * * ovs-ofctl dump-flows br0 table=1 * * Usage Advice * ------------ * * For best performance, segregate learned flows into a table that is not used * for any other flows except possibly for a lowest-priority "catch-all" flow * (a flow with no match criteria). If different learning actions specify * different match criteria, use different tables for the learned flows. * * The meaning of 'hard_timeout' and 'idle_timeout' can be counterintuitive. * These timeouts apply to the flow that is added, which means that a flow with * an idle timeout will expire when no traffic has been sent *to* the learned * address. This is not usually the intent in MAC learning; instead, we want * the MAC learn entry to expire when no traffic has been sent *from* the * learned address. Use a hard timeout for that. * * * Visibility of Changes * --------------------- * * Prior to Open vSwitch 2.4, any changes made by a "learn" action in a given * flow translation are visible to flow table lookups made later in the flow * translation. This means that, in the example above, a MAC learned by the * learn action in table 0 would be found in table 1 (if the packet being * processed had the same source and destination MAC address). * * In Open vSwitch 2.4 and later, changes to a flow table (whether to add or * modify a flow) by a "learn" action are visible only for later flow * translations, not for later lookups within the same flow translation. In * the MAC learning example, a MAC learned by the learn action in table 0 would * not be found in table 1 if the flow translation would resubmit to table 1 * after the processing of the learn action, meaning that if this MAC had not * been learned before then the packet would be flooded. */ struct nx_action_learn { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_LEARN. */ ovs_be16 idle_timeout; /* Idle time before discarding (seconds). */ ovs_be16 hard_timeout; /* Max time before discarding (seconds). */ ovs_be16 priority; /* Priority level of flow entry. */ ovs_be64 cookie; /* Cookie for new flow. */ ovs_be16 flags; /* NX_LEARN_F_*. */ uint8_t table_id; /* Table to insert flow entry. */ uint8_t pad; /* Must be zero. */ ovs_be16 fin_idle_timeout; /* Idle timeout after FIN, if nonzero. */ ovs_be16 fin_hard_timeout; /* Hard timeout after FIN, if nonzero. */ /* Followed by a sequence of flow_mod_spec elements, as described above, * until the end of the action is reached. */ }; OFP_ASSERT(sizeof(struct nx_action_learn) == 32); static ovs_be16 get_be16(const void **pp) { const ovs_be16 *p = *pp; ovs_be16 value = *p; *pp = p + 1; return value; } static ovs_be32 get_be32(const void **pp) { const ovs_be32 *p = *pp; ovs_be32 value = get_unaligned_be32(p); *pp = p + 1; return value; } static enum ofperr get_subfield(int n_bits, const void **p, struct mf_subfield *sf, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap) { enum ofperr error; error = mf_vl_mff_mf_from_nxm_header(ntohl(get_be32(p)), vl_mff_map, &sf->field, tlv_bitmap); sf->ofs = ntohs(get_be16(p)); sf->n_bits = n_bits; return error; } static unsigned int learn_min_len(uint16_t header) { int n_bits = header & NX_LEARN_N_BITS_MASK; int src_type = header & NX_LEARN_SRC_MASK; int dst_type = header & NX_LEARN_DST_MASK; unsigned int min_len; min_len = 0; if (src_type == NX_LEARN_SRC_FIELD) { min_len += sizeof(ovs_be32); /* src_field */ min_len += sizeof(ovs_be16); /* src_ofs */ } else { min_len += DIV_ROUND_UP(n_bits, 16); } if (dst_type == NX_LEARN_DST_MATCH || dst_type == NX_LEARN_DST_LOAD) { min_len += sizeof(ovs_be32); /* dst_field */ min_len += sizeof(ovs_be16); /* dst_ofs */ } return min_len; } /* Converts 'nal' into a "struct ofpact_learn" and appends that struct to * 'ofpacts'. Returns 0 if successful, otherwise an OFPERR_*. */ static enum ofperr decode_NXAST_RAW_LEARN(const struct nx_action_learn *nal, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpact_learn *learn; const void *p, *end; if (nal->pad) { return OFPERR_OFPBAC_BAD_ARGUMENT; } learn = ofpact_put_LEARN(ofpacts); learn->idle_timeout = ntohs(nal->idle_timeout); learn->hard_timeout = ntohs(nal->hard_timeout); learn->priority = ntohs(nal->priority); learn->cookie = nal->cookie; learn->table_id = nal->table_id; learn->fin_idle_timeout = ntohs(nal->fin_idle_timeout); learn->fin_hard_timeout = ntohs(nal->fin_hard_timeout); learn->flags = ntohs(nal->flags); if (learn->flags & ~(NX_LEARN_F_SEND_FLOW_REM | NX_LEARN_F_DELETE_LEARNED)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (learn->table_id == 0xff) { return OFPERR_OFPBAC_BAD_ARGUMENT; } end = (char *) nal + ntohs(nal->len); for (p = nal + 1; p != end; ) { struct ofpact_learn_spec *spec; uint16_t header = ntohs(get_be16(&p)); if (!header) { break; } spec = ofpbuf_put_zeros(ofpacts, sizeof *spec); learn = ofpacts->header; spec->src_type = header & NX_LEARN_SRC_MASK; spec->dst_type = header & NX_LEARN_DST_MASK; spec->n_bits = header & NX_LEARN_N_BITS_MASK; /* Check for valid src and dst type combination. */ if (spec->dst_type == NX_LEARN_DST_MATCH || spec->dst_type == NX_LEARN_DST_LOAD || (spec->dst_type == NX_LEARN_DST_OUTPUT && spec->src_type == NX_LEARN_SRC_FIELD)) { /* OK. */ } else { return OFPERR_OFPBAC_BAD_ARGUMENT; } /* Check that the arguments don't overrun the end of the action. */ if ((char *) end - (char *) p < learn_min_len(header)) { return OFPERR_OFPBAC_BAD_LEN; } /* Get the source. */ const uint8_t *imm = NULL; unsigned int imm_bytes = 0; enum ofperr error; if (spec->src_type == NX_LEARN_SRC_FIELD) { error = get_subfield(spec->n_bits, &p, &spec->src, vl_mff_map, tlv_bitmap); if (error) { return error; } } else { int p_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16); p = (const uint8_t *) p + p_bytes; imm_bytes = DIV_ROUND_UP(spec->n_bits, 8); imm = (const uint8_t *) p - imm_bytes; } /* Get the destination. */ if (spec->dst_type == NX_LEARN_DST_MATCH || spec->dst_type == NX_LEARN_DST_LOAD) { error = get_subfield(spec->n_bits, &p, &spec->dst, vl_mff_map, tlv_bitmap); if (error) { return error; } } if (imm) { uint8_t *src_imm = ofpbuf_put_zeros(ofpacts, OFPACT_ALIGN(imm_bytes)); memcpy(src_imm, imm, imm_bytes); learn = ofpacts->header; } } ofpact_finish_LEARN(ofpacts, &learn); if (!is_all_zeros(p, (char *) end - (char *) p)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } return 0; } static void put_be16(struct ofpbuf *b, ovs_be16 x) { ofpbuf_put(b, &x, sizeof x); } static void put_be32(struct ofpbuf *b, ovs_be32 x) { ofpbuf_put(b, &x, sizeof x); } static void put_u16(struct ofpbuf *b, uint16_t x) { put_be16(b, htons(x)); } static void put_u32(struct ofpbuf *b, uint32_t x) { put_be32(b, htonl(x)); } static void encode_LEARN(const struct ofpact_learn *learn, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { const struct ofpact_learn_spec *spec; struct nx_action_learn *nal; size_t start_ofs; start_ofs = out->size; nal = put_NXAST_LEARN(out); nal->idle_timeout = htons(learn->idle_timeout); nal->hard_timeout = htons(learn->hard_timeout); nal->fin_idle_timeout = htons(learn->fin_idle_timeout); nal->fin_hard_timeout = htons(learn->fin_hard_timeout); nal->priority = htons(learn->priority); nal->cookie = learn->cookie; nal->flags = htons(learn->flags); nal->table_id = learn->table_id; OFPACT_LEARN_SPEC_FOR_EACH (spec, learn) { put_u16(out, spec->n_bits | spec->dst_type | spec->src_type); if (spec->src_type == NX_LEARN_SRC_FIELD) { put_u32(out, nxm_header_from_mff(spec->src.field)); put_u16(out, spec->src.ofs); } else { size_t n_dst_bytes = 2 * DIV_ROUND_UP(spec->n_bits, 16); uint8_t *bits = ofpbuf_put_zeros(out, n_dst_bytes); unsigned int n_bytes = DIV_ROUND_UP(spec->n_bits, 8); memcpy(bits + n_dst_bytes - n_bytes, ofpact_learn_spec_imm(spec), n_bytes); } if (spec->dst_type == NX_LEARN_DST_MATCH || spec->dst_type == NX_LEARN_DST_LOAD) { put_u32(out, nxm_header_from_mff(spec->dst.field)); put_u16(out, spec->dst.ofs); } } pad_ofpat(out, start_ofs); } static char * OVS_WARN_UNUSED_RESULT parse_LEARN(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return learn_parse(arg, ofpacts); } static void format_LEARN(const struct ofpact_learn *a, struct ds *s) { learn_format(a, s); } /* Action structure for NXAST_CONJUNCTION. */ struct nx_action_conjunction { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* See enum ofp_raw_action_type. */ uint8_t clause; uint8_t n_clauses; ovs_be32 id; }; OFP_ASSERT(sizeof(struct nx_action_conjunction) == 16); static void add_conjunction(struct ofpbuf *out, uint32_t id, uint8_t clause, uint8_t n_clauses) { struct ofpact_conjunction *oc; oc = ofpact_put_CONJUNCTION(out); oc->id = id; oc->clause = clause; oc->n_clauses = n_clauses; } static enum ofperr decode_NXAST_RAW_CONJUNCTION(const struct nx_action_conjunction *nac, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (nac->n_clauses < 2 || nac->n_clauses > 64 || nac->clause >= nac->n_clauses) { return OFPERR_NXBAC_BAD_CONJUNCTION; } else { add_conjunction(out, ntohl(nac->id), nac->clause, nac->n_clauses); return 0; } } static void encode_CONJUNCTION(const struct ofpact_conjunction *oc, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct nx_action_conjunction *nac = put_NXAST_CONJUNCTION(out); nac->clause = oc->clause; nac->n_clauses = oc->n_clauses; nac->id = htonl(oc->id); } static void format_CONJUNCTION(const struct ofpact_conjunction *oc, struct ds *s) { ds_put_format(s, "%sconjunction(%s%"PRIu32",%"PRIu8"/%"PRIu8"%s)%s", colors.paren, colors.end, oc->id, oc->clause + 1, oc->n_clauses, colors.paren, colors.end); } static char * OVS_WARN_UNUSED_RESULT parse_CONJUNCTION(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { uint8_t n_clauses; uint8_t clause; uint32_t id; int n; if (!ovs_scan(arg, "%"SCNi32" , %"SCNu8" / %"SCNu8" %n", &id, &clause, &n_clauses, &n) || n != strlen(arg)) { return xstrdup("\"conjunction\" syntax is \"conjunction(id,i/n)\""); } if (n_clauses < 2) { return xstrdup("conjunction must have at least 2 clauses"); } else if (n_clauses > 64) { return xstrdup("conjunction must have at most 64 clauses"); } else if (clause < 1) { return xstrdup("clause index must be positive"); } else if (clause > n_clauses) { return xstrdup("clause index must be less than or equal to " "number of clauses"); } add_conjunction(ofpacts, id, clause - 1, n_clauses); return NULL; } /* Action structure for NXAST_MULTIPATH. * * This action performs the following steps in sequence: * * 1. Hashes the fields designated by 'fields', one of NX_HASH_FIELDS_*. * Refer to the definition of "enum nx_mp_fields" for details. * * The 'basis' value is used as a universal hash parameter, that is, * different values of 'basis' yield different hash functions. The * particular universal hash function used is implementation-defined. * * The hashed fields' values are drawn from the current state of the * flow, including all modifications that have been made by actions up to * this point. * * 2. Applies the multipath link choice algorithm specified by 'algorithm', * one of NX_MP_ALG_*. Refer to the definition of "enum nx_mp_algorithm" * for details. * * The output of the algorithm is 'link', an unsigned integer less than * or equal to 'max_link'. * * Some algorithms use 'arg' as an additional argument. * * 3. Stores 'link' in dst[ofs:ofs+n_bits]. The format and semantics of * 'dst' and 'ofs_nbits' are similar to those for the NXAST_REG_LOAD * action. * * The switch will reject actions that have an unknown 'fields', or an unknown * 'algorithm', or in which ofs+n_bits is greater than the width of 'dst', or * in which 'max_link' is greater than or equal to 2**n_bits, with error type * OFPET_BAD_ACTION, code OFPBAC_BAD_ARGUMENT. */ struct nx_action_multipath { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 32. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_MULTIPATH. */ /* What fields to hash and how. */ ovs_be16 fields; /* One of NX_HASH_FIELDS_*. */ ovs_be16 basis; /* Universal hash parameter. */ ovs_be16 pad0; /* Multipath link choice algorithm to apply to hash value. */ ovs_be16 algorithm; /* One of NX_MP_ALG_*. */ ovs_be16 max_link; /* Number of output links, minus 1. */ ovs_be32 arg; /* Algorithm-specific argument. */ ovs_be16 pad1; /* Where to store the result. */ ovs_be16 ofs_nbits; /* (ofs << 6) | (n_bits - 1). */ ovs_be32 dst; /* Destination. */ }; OFP_ASSERT(sizeof(struct nx_action_multipath) == 32); static enum ofperr decode_NXAST_RAW_MULTIPATH(const struct nx_action_multipath *nam, enum ofp_version ofp_version OVS_UNUSED, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { uint32_t n_links = ntohs(nam->max_link) + 1; size_t min_n_bits = log_2_ceil(n_links); struct ofpact_multipath *mp; enum ofperr error; mp = ofpact_put_MULTIPATH(out); mp->fields = ntohs(nam->fields); mp->basis = ntohs(nam->basis); mp->algorithm = ntohs(nam->algorithm); mp->max_link = ntohs(nam->max_link); mp->arg = ntohl(nam->arg); mp->dst.ofs = nxm_decode_ofs(nam->ofs_nbits); mp->dst.n_bits = nxm_decode_n_bits(nam->ofs_nbits); error = mf_vl_mff_mf_from_nxm_header(ntohl(nam->dst), vl_mff_map, &mp->dst.field, tlv_bitmap); if (error) { return error; } if (!flow_hash_fields_valid(mp->fields)) { VLOG_WARN_RL(&rl, "unsupported fields %d", (int) mp->fields); return OFPERR_OFPBAC_BAD_ARGUMENT; } else if (mp->algorithm != NX_MP_ALG_MODULO_N && mp->algorithm != NX_MP_ALG_HASH_THRESHOLD && mp->algorithm != NX_MP_ALG_HRW && mp->algorithm != NX_MP_ALG_ITER_HASH) { VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) mp->algorithm); return OFPERR_OFPBAC_BAD_ARGUMENT; } else if (mp->dst.n_bits < min_n_bits) { VLOG_WARN_RL(&rl, "multipath action requires at least %"PRIuSIZE" bits for " "%"PRIu32" links", min_n_bits, n_links); return OFPERR_OFPBAC_BAD_ARGUMENT; } return multipath_check(mp, NULL); } static void encode_MULTIPATH(const struct ofpact_multipath *mp, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct nx_action_multipath *nam = put_NXAST_MULTIPATH(out); nam->fields = htons(mp->fields); nam->basis = htons(mp->basis); nam->algorithm = htons(mp->algorithm); nam->max_link = htons(mp->max_link); nam->arg = htonl(mp->arg); nam->ofs_nbits = nxm_encode_ofs_nbits(mp->dst.ofs, mp->dst.n_bits); nam->dst = htonl(nxm_header_from_mff(mp->dst.field)); } static char * OVS_WARN_UNUSED_RESULT parse_MULTIPATH(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { return multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg); } static void format_MULTIPATH(const struct ofpact_multipath *a, struct ds *s) { multipath_format(a, s); } /* Action structure for NXAST_NOTE. * * This action has no effect. It is variable length. The switch does not * attempt to interpret the user-defined 'note' data in any way. A controller * can use this action to attach arbitrary metadata to a flow. * * This action might go away in the future. */ struct nx_action_note { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* A multiple of 8, but at least 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_NOTE. */ uint8_t note[6]; /* Start of user-defined data. */ /* Possibly followed by additional user-defined data. */ }; OFP_ASSERT(sizeof(struct nx_action_note) == 16); static enum ofperr decode_NXAST_RAW_NOTE(const struct nx_action_note *nan, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_note *note; unsigned int length; length = ntohs(nan->len) - offsetof(struct nx_action_note, note); note = ofpact_put_NOTE(out); note->length = length; ofpbuf_put(out, nan->note, length); note = out->header; ofpact_finish_NOTE(out, &note); return 0; } static void encode_NOTE(const struct ofpact_note *note, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { size_t start_ofs = out->size; struct nx_action_note *nan; put_NXAST_NOTE(out); out->size = out->size - sizeof nan->note; ofpbuf_put(out, note->data, note->length); pad_ofpat(out, start_ofs); } static char * OVS_WARN_UNUSED_RESULT parse_NOTE(const char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { size_t start_ofs = ofpacts->size; ofpact_put_NOTE(ofpacts); arg = ofpbuf_put_hex(ofpacts, arg, NULL); if (arg[0]) { return xstrdup("bad hex digit in `note' argument"); } struct ofpact_note *note = ofpbuf_at_assert(ofpacts, start_ofs, sizeof *note); note->length = ofpacts->size - (start_ofs + sizeof *note); ofpact_finish_NOTE(ofpacts, &note); return NULL; } static void format_NOTE(const struct ofpact_note *a, struct ds *s) { ds_put_format(s, "%snote:%s", colors.param, colors.end); format_hex_arg(s, a->data, a->length); } /* Exit action. */ static enum ofperr decode_NXAST_RAW_EXIT(struct ofpbuf *out) { ofpact_put_EXIT(out); return 0; } static void encode_EXIT(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { put_NXAST_EXIT(out); } static char * OVS_WARN_UNUSED_RESULT parse_EXIT(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_EXIT(ofpacts); return NULL; } static void format_EXIT(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%sexit%s", colors.special, colors.end); } /* Unroll xlate action. */ static void encode_UNROLL_XLATE(const struct ofpact_unroll_xlate *unroll OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out OVS_UNUSED) { OVS_NOT_REACHED(); } static char * OVS_WARN_UNUSED_RESULT parse_UNROLL_XLATE(char *arg OVS_UNUSED, struct ofpbuf *ofpacts OVS_UNUSED, enum ofputil_protocol *usable_protocols OVS_UNUSED) { OVS_NOT_REACHED(); return NULL; } static void format_UNROLL_XLATE(const struct ofpact_unroll_xlate *a, struct ds *s) { ds_put_format(s, "%sunroll_xlate(%s%stable=%s%"PRIu8 ", %scookie=%s%"PRIu64"%s)%s", colors.paren, colors.end, colors.special, colors.end, a->rule_table_id, colors.param, colors.end, ntohll(a->rule_cookie), colors.paren, colors.end); } /* The NXAST_CLONE action is "struct ext_action_header", followed by zero or * more embedded OpenFlow actions. */ static enum ofperr decode_NXAST_RAW_CLONE(const struct ext_action_header *eah, enum ofp_version ofp_version, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { int error; struct ofpbuf openflow; const size_t clone_offset = ofpacts_pull(out); struct ofpact_nest *clone = ofpact_put_CLONE(out); /* decode action list */ ofpbuf_pull(out, sizeof(*clone)); openflow = ofpbuf_const_initializer( eah + 1, ntohs(eah->len) - sizeof *eah); error = ofpacts_pull_openflow_actions__(&openflow, openflow.size, ofp_version, 1u << OVSINST_OFPIT11_APPLY_ACTIONS, out, 0, vl_mff_map, tlv_bitmap); clone = ofpbuf_push_uninit(out, sizeof *clone); out->header = &clone->ofpact; ofpact_finish_CLONE(out, &clone); ofpbuf_push_uninit(out, clone_offset); return error; } static void encode_CLONE(const struct ofpact_nest *clone, enum ofp_version ofp_version, struct ofpbuf *out) { size_t len; const size_t ofs = out->size; struct ext_action_header *eah; eah = put_NXAST_CLONE(out); len = ofpacts_put_openflow_actions(clone->actions, ofpact_nest_get_action_len(clone), out, ofp_version); len += sizeof *eah; eah = ofpbuf_at(out, ofs, sizeof *eah); eah->len = htons(len); } static char * OVS_WARN_UNUSED_RESULT parse_CLONE(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { const size_t clone_offset = ofpacts_pull(ofpacts); struct ofpact_nest *clone = ofpact_put_CLONE(ofpacts); char *error; ofpbuf_pull(ofpacts, sizeof *clone); error = ofpacts_parse_copy(arg, ofpacts, usable_protocols, false, 0); /* header points to the action list */ ofpacts->header = ofpbuf_push_uninit(ofpacts, sizeof *clone); clone = ofpacts->header; ofpact_finish_CLONE(ofpacts, &clone); ofpbuf_push_uninit(ofpacts, clone_offset); return error; } static void format_CLONE(const struct ofpact_nest *a, struct ds *s) { ds_put_format(s, "%sclone(%s", colors.paren, colors.end); ofpacts_format(a->actions, ofpact_nest_get_action_len(a), s); ds_put_format(s, "%s)%s", colors.paren, colors.end); } /* Action structure for NXAST_SAMPLE. * * Samples matching packets with the given probability and sends them * each to the set of collectors identified with the given ID. The * probability is expressed as a number of packets to be sampled out * of USHRT_MAX packets, and must be >0. * * When sending packet samples to IPFIX collectors, the IPFIX flow * record sent for each sampled packet is associated with the given * observation domain ID and observation point ID. Each IPFIX flow * record contain the sampled packet's headers when executing this * rule. If a sampled packet's headers are modified by previous * actions in the flow, those modified headers are sent. */ struct nx_action_sample { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_SAMPLE. */ ovs_be16 probability; /* Fraction of packets to sample. */ ovs_be32 collector_set_id; /* ID of collector set in OVSDB. */ ovs_be32 obs_domain_id; /* ID of sampling observation domain. */ ovs_be32 obs_point_id; /* ID of sampling observation point. */ }; OFP_ASSERT(sizeof(struct nx_action_sample) == 24); /* Action structure for NXAST_SAMPLE2 and NXAST_SAMPLE3. * * NXAST_SAMPLE2 was added in Open vSwitch 2.5.90. Compared to NXAST_SAMPLE, * it adds support for exporting egress tunnel information. * * NXAST_SAMPLE3 was added in Open vSwitch 2.6.90. Compared to NXAST_SAMPLE2, * it adds support for the 'direction' field. */ struct nx_action_sample2 { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 32. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_SAMPLE. */ ovs_be16 probability; /* Fraction of packets to sample. */ ovs_be32 collector_set_id; /* ID of collector set in OVSDB. */ ovs_be32 obs_domain_id; /* ID of sampling observation domain. */ ovs_be32 obs_point_id; /* ID of sampling observation point. */ ovs_be16 sampling_port; /* Sampling port. */ uint8_t direction; /* NXAST_SAMPLE3 only. */ uint8_t zeros[5]; /* Pad to a multiple of 8 bytes */ }; OFP_ASSERT(sizeof(struct nx_action_sample2) == 32); static enum ofperr decode_NXAST_RAW_SAMPLE(const struct nx_action_sample *nas, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_sample *sample; sample = ofpact_put_SAMPLE(out); sample->ofpact.raw = NXAST_RAW_SAMPLE; sample->probability = ntohs(nas->probability); sample->collector_set_id = ntohl(nas->collector_set_id); sample->obs_domain_id = ntohl(nas->obs_domain_id); sample->obs_point_id = ntohl(nas->obs_point_id); sample->sampling_port = OFPP_NONE; sample->direction = NX_ACTION_SAMPLE_DEFAULT; if (sample->probability == 0) { return OFPERR_OFPBAC_BAD_ARGUMENT; } return 0; } static enum ofperr decode_SAMPLE2(const struct nx_action_sample2 *nas, enum ofp_raw_action_type raw, enum nx_action_sample_direction direction, struct ofpact_sample *sample) { sample->ofpact.raw = raw; sample->probability = ntohs(nas->probability); sample->collector_set_id = ntohl(nas->collector_set_id); sample->obs_domain_id = ntohl(nas->obs_domain_id); sample->obs_point_id = ntohl(nas->obs_point_id); sample->sampling_port = u16_to_ofp(ntohs(nas->sampling_port)); sample->direction = direction; if (sample->probability == 0) { return OFPERR_OFPBAC_BAD_ARGUMENT; } return 0; } static enum ofperr decode_NXAST_RAW_SAMPLE2(const struct nx_action_sample2 *nas, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_SAMPLE2(nas, NXAST_RAW_SAMPLE2, NX_ACTION_SAMPLE_DEFAULT, ofpact_put_SAMPLE(out)); } static enum ofperr decode_NXAST_RAW_SAMPLE3(const struct nx_action_sample2 *nas, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_sample *sample = ofpact_put_SAMPLE(out); if (!is_all_zeros(nas->zeros, sizeof nas->zeros)) { return OFPERR_NXBRC_MUST_BE_ZERO; } if (nas->direction != NX_ACTION_SAMPLE_DEFAULT && nas->direction != NX_ACTION_SAMPLE_INGRESS && nas->direction != NX_ACTION_SAMPLE_EGRESS) { VLOG_WARN_RL(&rl, "invalid sample direction %"PRIu8, nas->direction); return OFPERR_OFPBAC_BAD_ARGUMENT; } return decode_SAMPLE2(nas, NXAST_RAW_SAMPLE3, nas->direction, sample); } static void encode_SAMPLE2(const struct ofpact_sample *sample, struct nx_action_sample2 *nas) { nas->probability = htons(sample->probability); nas->collector_set_id = htonl(sample->collector_set_id); nas->obs_domain_id = htonl(sample->obs_domain_id); nas->obs_point_id = htonl(sample->obs_point_id); nas->sampling_port = htons(ofp_to_u16(sample->sampling_port)); nas->direction = sample->direction; } static void encode_SAMPLE(const struct ofpact_sample *sample, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { if (sample->ofpact.raw == NXAST_RAW_SAMPLE3 || sample->direction != NX_ACTION_SAMPLE_DEFAULT) { encode_SAMPLE2(sample, put_NXAST_SAMPLE3(out)); } else if (sample->ofpact.raw == NXAST_RAW_SAMPLE2 || sample->sampling_port != OFPP_NONE) { encode_SAMPLE2(sample, put_NXAST_SAMPLE2(out)); } else { struct nx_action_sample *nas = put_NXAST_SAMPLE(out); nas->probability = htons(sample->probability); nas->collector_set_id = htonl(sample->collector_set_id); nas->obs_domain_id = htonl(sample->obs_domain_id); nas->obs_point_id = htonl(sample->obs_point_id); } } /* Parses 'arg' as the argument to a "sample" action, and appends such an * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT parse_SAMPLE(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_sample *os = ofpact_put_SAMPLE(ofpacts); os->sampling_port = OFPP_NONE; os->direction = NX_ACTION_SAMPLE_DEFAULT; char *key, *value; while (ofputil_parse_key_value(&arg, &key, &value)) { char *error = NULL; if (!strcmp(key, "probability")) { error = str_to_u16(value, "probability", &os->probability); if (!error && os->probability == 0) { error = xasprintf("invalid probability value \"%s\"", value); } } else if (!strcmp(key, "collector_set_id")) { error = str_to_u32(value, &os->collector_set_id); } else if (!strcmp(key, "obs_domain_id")) { error = str_to_u32(value, &os->obs_domain_id); } else if (!strcmp(key, "obs_point_id")) { error = str_to_u32(value, &os->obs_point_id); } else if (!strcmp(key, "sampling_port")) { if (!ofputil_port_from_string(value, &os->sampling_port)) { error = xasprintf("%s: unknown port", value); } } else if (!strcmp(key, "ingress")) { os->direction = NX_ACTION_SAMPLE_INGRESS; } else if (!strcmp(key, "egress")) { os->direction = NX_ACTION_SAMPLE_EGRESS; } else { error = xasprintf("invalid key \"%s\" in \"sample\" argument", key); } if (error) { return error; } } if (os->probability == 0) { return xstrdup("non-zero \"probability\" must be specified on sample"); } return NULL; } static void format_SAMPLE(const struct ofpact_sample *a, struct ds *s) { ds_put_format(s, "%ssample(%s%sprobability=%s%"PRIu16 ",%scollector_set_id=%s%"PRIu32 ",%sobs_domain_id=%s%"PRIu32 ",%sobs_point_id=%s%"PRIu32, colors.paren, colors.end, colors.param, colors.end, a->probability, colors.param, colors.end, a->collector_set_id, colors.param, colors.end, a->obs_domain_id, colors.param, colors.end, a->obs_point_id); if (a->sampling_port != OFPP_NONE) { ds_put_format(s, ",%ssampling_port=%s%"PRIu32, colors.param, colors.end, a->sampling_port); } if (a->direction == NX_ACTION_SAMPLE_INGRESS) { ds_put_format(s, ",%singress%s", colors.param, colors.end); } else if (a->direction == NX_ACTION_SAMPLE_EGRESS) { ds_put_format(s, ",%segress%s", colors.param, colors.end); } ds_put_format(s, "%s)%s", colors.paren, colors.end); } /* debug_recirc instruction. */ static bool enable_debug; void ofpact_dummy_enable(void) { enable_debug = true; } static enum ofperr decode_NXAST_RAW_DEBUG_RECIRC(struct ofpbuf *out) { if (!enable_debug) { return OFPERR_OFPBAC_BAD_VENDOR_TYPE; } ofpact_put_DEBUG_RECIRC(out); return 0; } static void encode_DEBUG_RECIRC(const struct ofpact_null *n OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { put_NXAST_DEBUG_RECIRC(out); } static char * OVS_WARN_UNUSED_RESULT parse_DEBUG_RECIRC(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_DEBUG_RECIRC(ofpacts); return NULL; } static void format_DEBUG_RECIRC(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%sdebug_recirc%s", colors.value, colors.end); } /* Action structure for NXAST_CT. * * Pass traffic to the connection tracker. * * There are two important concepts to understanding the connection tracking * interface: Packet state and Connection state. Packets may be "Untracked" or * "Tracked". Connections may be "Uncommitted" or "Committed". * * - Packet State: * * Untracked packets have not yet passed through the connection tracker, * and the connection state for such packets is unknown. In most cases, * packets entering the OpenFlow pipeline will initially be in the * untracked state. Untracked packets may become tracked by executing * NXAST_CT with a "recirc_table" specified. This makes various aspects * about the connection available, in particular the connection state. * * Tracked packets have previously passed through the connection tracker. * These packets will remain tracked through until the end of the OpenFlow * pipeline. Tracked packets which have NXAST_CT executed with a * "recirc_table" specified will return to the tracked state. * * The packet state is only significant for the duration of packet * processing within the OpenFlow pipeline. * * - Connection State: * * Multiple packets may be associated with a single connection. Initially, * all connections are uncommitted. The connection state corresponding to * a packet is available in the NXM_NX_CT_STATE field for tracked packets. * * Uncommitted connections have no state stored about them. Uncommitted * connections may transition into the committed state by executing * NXAST_CT with the NX_CT_F_COMMIT flag. * * Once a connection becomes committed, information may be gathered about * the connection by passing subsequent packets through the connection * tracker, and the state of the connection will be stored beyond the * lifetime of packet processing. * * Connections may transition back into the uncommitted state due to * external timers, or due to the contents of packets that are sent to the * connection tracker. This behaviour is outside of the scope of the * OpenFlow interface. * * The "zone" specifies a context within which the tracking is done: * * The connection tracking zone is a 16-bit number. Each zone is an * independent connection tracking context. The connection state for each * connection is completely separate for each zone, so if a connection * is committed to zone A, then it will remain uncommitted in zone B. * If NXAST_CT is executed with the same zone multiple times, later * executions have no effect. * * If 'zone_src' is nonzero, this specifies that the zone should be * sourced from a field zone_src[ofs:ofs+nbits]. The format and semantics * of 'zone_src' and 'zone_ofs_nbits' are similar to those for the * NXAST_REG_LOAD action. The acceptable nxm_header values for 'zone_src' * are the same as the acceptable nxm_header values for the 'src' field of * NXAST_REG_MOVE. * * If 'zone_src' is zero, then the value of 'zone_imm' will be used as the * connection tracking zone. * * The "recirc_table" allows NXM_NX_CT_* fields to become available: * * If "recirc_table" has a value other than NX_CT_RECIRC_NONE, then the * packet will be logically cloned prior to executing this action. One * copy will be sent to the connection tracker, then will be re-injected * into the OpenFlow pipeline beginning at the OpenFlow table specified in * this field. When the packet re-enters the pipeline, the NXM_NX_CT_* * fields will be populated. The original instance of the packet will * continue the current actions list. This can be thought of as similar to * the effect of the "output" action: One copy is sent out (in this case, * to the connection tracker), but the current copy continues processing. * * It is strongly recommended that this table is later than the current * table, to prevent loops. * * The "alg" attaches protocol-specific behaviour to this action: * * The ALG is a 16-bit number which specifies that additional * processing should be applied to this traffic. * * Protocol | Value | Meaning * -------------------------------------------------------------------- * None | 0 | No protocol-specific behaviour. * FTP | 21 | Parse FTP control connections and observe the * | | negotiation of related data connections. * Other | Other | Unsupported protocols. * * By way of example, if FTP control connections have this action applied * with the ALG set to FTP (21), then the connection tracker will observe * the negotiation of data connections. This allows the connection * tracker to identify subsequent data connections as "related" to this * existing connection. The "related" flag will be populated in the * NXM_NX_CT_STATE field for such connections if the 'recirc_table' is * specified. * * Zero or more actions may immediately follow this action. These actions will * be executed within the context of the connection tracker, and they require * the NX_CT_F_COMMIT flag to be set. */ struct nx_action_conntrack { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 24. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_CT. */ ovs_be16 flags; /* Zero or more NX_CT_F_* flags. * Unspecified flag bits must be zero. */ ovs_be32 zone_src; /* Connection tracking context. */ union { ovs_be16 zone_ofs_nbits;/* Range to use from source field. */ ovs_be16 zone_imm; /* Immediate value for zone. */ }; uint8_t recirc_table; /* Recirculate to a specific table, or NX_CT_RECIRC_NONE for no recirculation. */ uint8_t pad[3]; /* Zeroes */ ovs_be16 alg; /* Well-known port number for the protocol. * 0 indicates no ALG is required. */ /* Followed by a sequence of zero or more OpenFlow actions. The length of * these is included in 'len'. */ }; OFP_ASSERT(sizeof(struct nx_action_conntrack) == 24); static enum ofperr decode_ct_zone(const struct nx_action_conntrack *nac, struct ofpact_conntrack *out, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap) { if (nac->zone_src) { enum ofperr error; out->zone_src.ofs = nxm_decode_ofs(nac->zone_ofs_nbits); out->zone_src.n_bits = nxm_decode_n_bits(nac->zone_ofs_nbits); error = mf_vl_mff_mf_from_nxm_header(ntohl(nac->zone_src), vl_mff_map, &out->zone_src.field, tlv_bitmap); if (error) { return error; } error = mf_check_src(&out->zone_src, NULL); if (error) { return error; } if (out->zone_src.n_bits != 16) { VLOG_WARN_RL(&rl, "zone n_bits %d not within valid range [16..16]", out->zone_src.n_bits); return OFPERR_OFPBAC_BAD_SET_LEN; } } else { out->zone_src.field = NULL; out->zone_imm = ntohs(nac->zone_imm); } return 0; } static enum ofperr decode_NXAST_RAW_CT(const struct nx_action_conntrack *nac, enum ofp_version ofp_version, const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap, struct ofpbuf *out) { const size_t ct_offset = ofpacts_pull(out); struct ofpact_conntrack *conntrack = ofpact_put_CT(out); conntrack->flags = ntohs(nac->flags); int error = decode_ct_zone(nac, conntrack, vl_mff_map, tlv_bitmap); if (error) { goto out; } conntrack->recirc_table = nac->recirc_table; conntrack->alg = ntohs(nac->alg); ofpbuf_pull(out, sizeof(*conntrack)); struct ofpbuf openflow = ofpbuf_const_initializer( nac + 1, ntohs(nac->len) - sizeof(*nac)); error = ofpacts_pull_openflow_actions__(&openflow, openflow.size, ofp_version, 1u << OVSINST_OFPIT11_APPLY_ACTIONS, out, OFPACT_CT, vl_mff_map, tlv_bitmap); if (error) { goto out; } conntrack = ofpbuf_push_uninit(out, sizeof(*conntrack)); out->header = &conntrack->ofpact; ofpact_finish_CT(out, &conntrack); if (conntrack->ofpact.len > sizeof(*conntrack) && !(conntrack->flags & NX_CT_F_COMMIT)) { const struct ofpact *a; size_t ofpacts_len = conntrack->ofpact.len - sizeof(*conntrack); OFPACT_FOR_EACH (a, conntrack->actions, ofpacts_len) { if (a->type != OFPACT_NAT || ofpact_get_NAT(a)->flags || ofpact_get_NAT(a)->range_af != AF_UNSPEC) { VLOG_WARN_RL(&rl, "CT action requires commit flag if actions " "other than NAT without arguments are specified."); error = OFPERR_OFPBAC_BAD_ARGUMENT; goto out; } } } out: ofpbuf_push_uninit(out, ct_offset); return error; } static void encode_CT(const struct ofpact_conntrack *conntrack, enum ofp_version ofp_version, struct ofpbuf *out) { struct nx_action_conntrack *nac; const size_t ofs = out->size; size_t len; nac = put_NXAST_CT(out); nac->flags = htons(conntrack->flags); if (conntrack->zone_src.field) { nac->zone_src = htonl(nxm_header_from_mff(conntrack->zone_src.field)); nac->zone_ofs_nbits = nxm_encode_ofs_nbits(conntrack->zone_src.ofs, conntrack->zone_src.n_bits); } else { nac->zone_src = htonl(0); nac->zone_imm = htons(conntrack->zone_imm); } nac->recirc_table = conntrack->recirc_table; nac->alg = htons(conntrack->alg); len = ofpacts_put_openflow_actions(conntrack->actions, ofpact_ct_get_action_len(conntrack), out, ofp_version); len += sizeof(*nac); nac = ofpbuf_at(out, ofs, sizeof(*nac)); nac->len = htons(len); } static char * OVS_WARN_UNUSED_RESULT parse_NAT(char *arg, struct ofpbuf *, enum ofputil_protocol * OVS_UNUSED); /* Parses 'arg' as the argument to a "ct" action, and appends such an * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT parse_CT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { const size_t ct_offset = ofpacts_pull(ofpacts); struct ofpact_conntrack *oc; char *error = NULL; char *key, *value; oc = ofpact_put_CT(ofpacts); oc->flags = 0; oc->recirc_table = NX_CT_RECIRC_NONE; while (ofputil_parse_key_value(&arg, &key, &value)) { if (!strcmp(key, "commit")) { oc->flags |= NX_CT_F_COMMIT; } else if (!strcmp(key, "table")) { error = str_to_u8(value, "recirc_table", &oc->recirc_table); if (!error && oc->recirc_table == NX_CT_RECIRC_NONE) { error = xasprintf("invalid table %#"PRIx16, oc->recirc_table); } } else if (!strcmp(key, "zone")) { error = str_to_u16(value, "zone", &oc->zone_imm); if (error) { free(error); error = mf_parse_subfield(&oc->zone_src, value); if (error) { return error; } } } else if (!strcmp(key, "alg")) { error = str_to_connhelper(value, &oc->alg); } else if (!strcmp(key, "nat")) { const size_t nat_offset = ofpacts_pull(ofpacts); error = parse_NAT(value, ofpacts, usable_protocols); /* Update CT action pointer and length. */ ofpacts->header = ofpbuf_push_uninit(ofpacts, nat_offset); oc = ofpacts->header; } else if (!strcmp(key, "exec")) { /* Hide existing actions from ofpacts_parse_copy(), so the * nesting can be handled transparently. */ enum ofputil_protocol usable_protocols2; const size_t exec_offset = ofpacts_pull(ofpacts); /* Initializes 'usable_protocol2', fold it back to * '*usable_protocols' afterwards, so that we do not lose * restrictions already in there. */ error = ofpacts_parse_copy(value, ofpacts, &usable_protocols2, false, OFPACT_CT); *usable_protocols &= usable_protocols2; ofpacts->header = ofpbuf_push_uninit(ofpacts, exec_offset); oc = ofpacts->header; } else { error = xasprintf("invalid argument to \"ct\" action: `%s'", key); } if (error) { break; } } ofpact_finish_CT(ofpacts, &oc); ofpbuf_push_uninit(ofpacts, ct_offset); return error; } static void format_alg(int port, struct ds *s) { switch(port) { case IPPORT_FTP: ds_put_format(s, "%salg=%sftp,", colors.param, colors.end); break; case IPPORT_TFTP: ds_put_format(s, "%salg=%stftp,", colors.param, colors.end); break; case 0: /* Don't print. */ break; default: ds_put_format(s, "%salg=%s%d,", colors.param, colors.end, port); break; } } static void format_NAT(const struct ofpact_nat *a, struct ds *ds); static void format_CT(const struct ofpact_conntrack *a, struct ds *s) { ds_put_format(s, "%sct(%s", colors.paren, colors.end); if (a->flags & NX_CT_F_COMMIT) { ds_put_format(s, "%scommit%s,", colors.value, colors.end); } if (a->recirc_table != NX_CT_RECIRC_NONE) { ds_put_format(s, "%stable=%s%"PRIu8",", colors.special, colors.end, a->recirc_table); } if (a->zone_src.field) { ds_put_format(s, "%szone=%s", colors.param, colors.end); mf_format_subfield(&a->zone_src, s); ds_put_char(s, ','); } else if (a->zone_imm) { ds_put_format(s, "%szone=%s%"PRIu16",", colors.param, colors.end, a->zone_imm); } /* If the first action is a NAT action, format it outside of the 'exec' * envelope. */ const struct ofpact *action = a->actions; size_t actions_len = ofpact_ct_get_action_len(a); if (actions_len && action->type == OFPACT_NAT) { format_NAT(ofpact_get_NAT(action), s); ds_put_char(s, ','); actions_len -= OFPACT_ALIGN(action->len); action = ofpact_next(action); } if (actions_len) { ds_put_format(s, "%sexec(%s", colors.paren, colors.end); ofpacts_format(action, actions_len, s); ds_put_format(s, "%s),%s", colors.paren, colors.end); } format_alg(a->alg, s); ds_chomp(s, ','); ds_put_format(s, "%s)%s", colors.paren, colors.end); } /* ct_clear action. */ static enum ofperr decode_NXAST_RAW_CT_CLEAR(struct ofpbuf *out) { ofpact_put_CT_CLEAR(out); return 0; } static void encode_CT_CLEAR(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { put_NXAST_CT_CLEAR(out); } static char * OVS_WARN_UNUSED_RESULT parse_CT_CLEAR(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_CT_CLEAR(ofpacts); return NULL; } static void format_CT_CLEAR(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%sct_clear%s", colors.value, colors.end); } /* NAT action. */ /* Which optional fields are present? */ enum nx_nat_range { NX_NAT_RANGE_IPV4_MIN = 1 << 0, /* ovs_be32 */ NX_NAT_RANGE_IPV4_MAX = 1 << 1, /* ovs_be32 */ NX_NAT_RANGE_IPV6_MIN = 1 << 2, /* struct in6_addr */ NX_NAT_RANGE_IPV6_MAX = 1 << 3, /* struct in6_addr */ NX_NAT_RANGE_PROTO_MIN = 1 << 4, /* ovs_be16 */ NX_NAT_RANGE_PROTO_MAX = 1 << 5, /* ovs_be16 */ }; /* Action structure for NXAST_NAT. */ struct nx_action_nat { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_NAT. */ uint8_t pad[2]; /* Must be zero. */ ovs_be16 flags; /* Zero or more NX_NAT_F_* flags. * Unspecified flag bits must be zero. */ ovs_be16 range_present; /* NX_NAT_RANGE_* */ /* Followed by optional parameters as specified by 'range_present' */ }; OFP_ASSERT(sizeof(struct nx_action_nat) == 16); static void encode_NAT(const struct ofpact_nat *nat, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct nx_action_nat *nan; const size_t ofs = out->size; uint16_t range_present = 0; nan = put_NXAST_NAT(out); nan->flags = htons(nat->flags); if (nat->range_af == AF_INET) { if (nat->range.addr.ipv4.min) { ovs_be32 *min = ofpbuf_put_uninit(out, sizeof *min); *min = nat->range.addr.ipv4.min; range_present |= NX_NAT_RANGE_IPV4_MIN; } if (nat->range.addr.ipv4.max) { ovs_be32 *max = ofpbuf_put_uninit(out, sizeof *max); *max = nat->range.addr.ipv4.max; range_present |= NX_NAT_RANGE_IPV4_MAX; } } else if (nat->range_af == AF_INET6) { if (!ipv6_mask_is_any(&nat->range.addr.ipv6.min)) { struct in6_addr *min = ofpbuf_put_uninit(out, sizeof *min); *min = nat->range.addr.ipv6.min; range_present |= NX_NAT_RANGE_IPV6_MIN; } if (!ipv6_mask_is_any(&nat->range.addr.ipv6.max)) { struct in6_addr *max = ofpbuf_put_uninit(out, sizeof *max); *max = nat->range.addr.ipv6.max; range_present |= NX_NAT_RANGE_IPV6_MAX; } } if (nat->range_af != AF_UNSPEC) { if (nat->range.proto.min) { ovs_be16 *min = ofpbuf_put_uninit(out, sizeof *min); *min = htons(nat->range.proto.min); range_present |= NX_NAT_RANGE_PROTO_MIN; } if (nat->range.proto.max) { ovs_be16 *max = ofpbuf_put_uninit(out, sizeof *max); *max = htons(nat->range.proto.max); range_present |= NX_NAT_RANGE_PROTO_MAX; } } pad_ofpat(out, ofs); nan = ofpbuf_at(out, ofs, sizeof *nan); nan->range_present = htons(range_present); } static enum ofperr decode_NXAST_RAW_NAT(const struct nx_action_nat *nan, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_nat *nat; uint16_t range_present = ntohs(nan->range_present); const char *opts = (char *)(nan + 1); uint16_t len = ntohs(nan->len) - sizeof *nan; nat = ofpact_put_NAT(out); nat->flags = ntohs(nan->flags); /* Check for unknown or mutually exclusive flags. */ if ((nat->flags & ~NX_NAT_F_MASK) || (nat->flags & NX_NAT_F_SRC && nat->flags & NX_NAT_F_DST) || (nat->flags & NX_NAT_F_PROTO_HASH && nat->flags & NX_NAT_F_PROTO_RANDOM)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } #define NX_NAT_GET_OPT(DST, SRC, LEN, TYPE) \ (LEN >= sizeof(TYPE) \ ? (memcpy(DST, SRC, sizeof(TYPE)), LEN -= sizeof(TYPE), \ SRC += sizeof(TYPE)) \ : NULL) nat->range_af = AF_UNSPEC; if (range_present & NX_NAT_RANGE_IPV4_MIN) { if (range_present & (NX_NAT_RANGE_IPV6_MIN | NX_NAT_RANGE_IPV6_MAX)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (!NX_NAT_GET_OPT(&nat->range.addr.ipv4.min, opts, len, ovs_be32) || !nat->range.addr.ipv4.min) { return OFPERR_OFPBAC_BAD_ARGUMENT; } nat->range_af = AF_INET; if (range_present & NX_NAT_RANGE_IPV4_MAX) { if (!NX_NAT_GET_OPT(&nat->range.addr.ipv4.max, opts, len, ovs_be32)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (ntohl(nat->range.addr.ipv4.max) < ntohl(nat->range.addr.ipv4.min)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } } } else if (range_present & NX_NAT_RANGE_IPV4_MAX) { return OFPERR_OFPBAC_BAD_ARGUMENT; } else if (range_present & NX_NAT_RANGE_IPV6_MIN) { if (!NX_NAT_GET_OPT(&nat->range.addr.ipv6.min, opts, len, struct in6_addr) || ipv6_mask_is_any(&nat->range.addr.ipv6.min)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } nat->range_af = AF_INET6; if (range_present & NX_NAT_RANGE_IPV6_MAX) { if (!NX_NAT_GET_OPT(&nat->range.addr.ipv6.max, opts, len, struct in6_addr)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (memcmp(&nat->range.addr.ipv6.max, &nat->range.addr.ipv6.min, sizeof(struct in6_addr)) < 0) { return OFPERR_OFPBAC_BAD_ARGUMENT; } } } else if (range_present & NX_NAT_RANGE_IPV6_MAX) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (range_present & NX_NAT_RANGE_PROTO_MIN) { ovs_be16 proto; if (nat->range_af == AF_UNSPEC) { return OFPERR_OFPBAC_BAD_ARGUMENT; } if (!NX_NAT_GET_OPT(&proto, opts, len, ovs_be16) || proto == 0) { return OFPERR_OFPBAC_BAD_ARGUMENT; } nat->range.proto.min = ntohs(proto); if (range_present & NX_NAT_RANGE_PROTO_MAX) { if (!NX_NAT_GET_OPT(&proto, opts, len, ovs_be16)) { return OFPERR_OFPBAC_BAD_ARGUMENT; } nat->range.proto.max = ntohs(proto); if (nat->range.proto.max < nat->range.proto.min) { return OFPERR_OFPBAC_BAD_ARGUMENT; } } } else if (range_present & NX_NAT_RANGE_PROTO_MAX) { return OFPERR_OFPBAC_BAD_ARGUMENT; } return 0; } static void format_NAT(const struct ofpact_nat *a, struct ds *ds) { ds_put_format(ds, "%snat%s", colors.paren, colors.end); if (a->flags & (NX_NAT_F_SRC | NX_NAT_F_DST)) { ds_put_format(ds, "%s(%s", colors.paren, colors.end); ds_put_format(ds, a->flags & NX_NAT_F_SRC ? "%ssrc%s" : "%sdst%s", colors.param, colors.end); if (a->range_af != AF_UNSPEC) { ds_put_format(ds, "%s=%s", colors.param, colors.end); if (a->range_af == AF_INET) { ds_put_format(ds, IP_FMT, IP_ARGS(a->range.addr.ipv4.min)); if (a->range.addr.ipv4.max && a->range.addr.ipv4.max != a->range.addr.ipv4.min) { ds_put_format(ds, "-"IP_FMT, IP_ARGS(a->range.addr.ipv4.max)); } } else if (a->range_af == AF_INET6) { ipv6_format_addr_bracket(&a->range.addr.ipv6.min, ds, a->range.proto.min); if (!ipv6_mask_is_any(&a->range.addr.ipv6.max) && memcmp(&a->range.addr.ipv6.max, &a->range.addr.ipv6.min, sizeof(struct in6_addr)) != 0) { ds_put_char(ds, '-'); ipv6_format_addr_bracket(&a->range.addr.ipv6.max, ds, a->range.proto.min); } } if (a->range.proto.min) { ds_put_char(ds, ':'); ds_put_format(ds, "%"PRIu16, a->range.proto.min); if (a->range.proto.max && a->range.proto.max != a->range.proto.min) { ds_put_format(ds, "-%"PRIu16, a->range.proto.max); } } ds_put_char(ds, ','); if (a->flags & NX_NAT_F_PERSISTENT) { ds_put_format(ds, "%spersistent%s,", colors.value, colors.end); } if (a->flags & NX_NAT_F_PROTO_HASH) { ds_put_format(ds, "%shash%s,", colors.value, colors.end); } if (a->flags & NX_NAT_F_PROTO_RANDOM) { ds_put_format(ds, "%srandom%s,", colors.value, colors.end); } } ds_chomp(ds, ','); ds_put_format(ds, "%s)%s", colors.paren, colors.end); } } static char * OVS_WARN_UNUSED_RESULT str_to_nat_range(const char *s, struct ofpact_nat *on) { char ipv6_s[IPV6_SCAN_LEN + 1]; int n = 0; on->range_af = AF_UNSPEC; if (ovs_scan_len(s, &n, IP_SCAN_FMT, IP_SCAN_ARGS(&on->range.addr.ipv4.min))) { on->range_af = AF_INET; if (s[n] == '-') { n++; if (!ovs_scan_len(s, &n, IP_SCAN_FMT, IP_SCAN_ARGS(&on->range.addr.ipv4.max)) || (ntohl(on->range.addr.ipv4.max) < ntohl(on->range.addr.ipv4.min))) { goto error; } } } else if ((ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s) || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s)) && inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.min) == 1) { on->range_af = AF_INET6; if (s[n] == '-') { n++; if (!(ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s) || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s)) || inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.max) != 1 || memcmp(&on->range.addr.ipv6.max, &on->range.addr.ipv6.min, sizeof on->range.addr.ipv6.max) < 0) { goto error; } } } if (on->range_af != AF_UNSPEC && s[n] == ':') { n++; if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.min)) { goto error; } if (s[n] == '-') { n++; if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.max) || on->range.proto.max < on->range.proto.min) { goto error; } } } if (strlen(s) != n) { return xasprintf("garbage (%s) after nat range \"%s\" (pos: %d)", &s[n], s, n); } return NULL; error: return xasprintf("invalid nat range \"%s\"", s); } /* Parses 'arg' as the argument to a "nat" action, and appends such an * action to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ static char * OVS_WARN_UNUSED_RESULT parse_NAT(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_nat *on = ofpact_put_NAT(ofpacts); char *key, *value; on->flags = 0; on->range_af = AF_UNSPEC; while (ofputil_parse_key_value(&arg, &key, &value)) { char *error = NULL; if (!strcmp(key, "src")) { on->flags |= NX_NAT_F_SRC; error = str_to_nat_range(value, on); } else if (!strcmp(key, "dst")) { on->flags |= NX_NAT_F_DST; error = str_to_nat_range(value, on); } else if (!strcmp(key, "persistent")) { on->flags |= NX_NAT_F_PERSISTENT; } else if (!strcmp(key, "hash")) { on->flags |= NX_NAT_F_PROTO_HASH; } else if (!strcmp(key, "random")) { on->flags |= NX_NAT_F_PROTO_RANDOM; } else { error = xasprintf("invalid key \"%s\" in \"nat\" argument", key); } if (error) { return error; } } if (on->flags & NX_NAT_F_SRC && on->flags & NX_NAT_F_DST) { return xasprintf("May only specify one of \"src\" or \"dst\"."); } if (!(on->flags & NX_NAT_F_SRC || on->flags & NX_NAT_F_DST)) { if (on->flags) { return xasprintf("Flags allowed only with \"src\" or \"dst\"."); } if (on->range_af != AF_UNSPEC) { return xasprintf("Range allowed only with \"src\" or \"dst\"."); } } if (on->flags & NX_NAT_F_PROTO_HASH && on->flags & NX_NAT_F_PROTO_RANDOM) { return xasprintf("Both \"hash\" and \"random\" are not allowed."); } return NULL; } /* Truncate output action. */ struct nx_action_output_trunc { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* At least 16. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_OUTPUT_TRUNC. */ ovs_be16 port; /* Output port */ ovs_be32 max_len; /* Truncate packet to size bytes */ }; OFP_ASSERT(sizeof(struct nx_action_output_trunc) == 16); static enum ofperr decode_NXAST_RAW_OUTPUT_TRUNC(const struct nx_action_output_trunc *natrc, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_output_trunc *output_trunc; output_trunc = ofpact_put_OUTPUT_TRUNC(out); output_trunc->max_len = ntohl(natrc->max_len); output_trunc->port = u16_to_ofp(ntohs(natrc->port)); if (output_trunc->max_len < ETH_HEADER_LEN) { return OFPERR_OFPBAC_BAD_ARGUMENT; } return 0; } static void encode_OUTPUT_TRUNC(const struct ofpact_output_trunc *output_trunc, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct nx_action_output_trunc *natrc = put_NXAST_OUTPUT_TRUNC(out); natrc->max_len = htonl(output_trunc->max_len); natrc->port = htons(ofp_to_u16(output_trunc->port)); } static char * OVS_WARN_UNUSED_RESULT parse_OUTPUT_TRUNC(const char *arg, struct ofpbuf *ofpacts OVS_UNUSED, enum ofputil_protocol *usable_protocols OVS_UNUSED) { /* Disable output_trunc parsing. Expose as output(port=N,max_len=M) and * reuse parse_OUTPUT to parse output_trunc action. */ return xasprintf("unknown action %s", arg); } static void format_OUTPUT_TRUNC(const struct ofpact_output_trunc *a, struct ds *s) { ds_put_format(s, "%soutput%s(port=%"PRIu32",max_len=%"PRIu32")", colors.special, colors.end, a->port, a->max_len); } /* Meter instruction. */ static void encode_METER(const struct ofpact_meter *meter, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version >= OFP13_VERSION) { instruction_put_OFPIT13_METER(out)->meter_id = htonl(meter->meter_id); } } static char * OVS_WARN_UNUSED_RESULT parse_METER(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { *usable_protocols &= OFPUTIL_P_OF13_UP; return str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id); } static void format_METER(const struct ofpact_meter *a, struct ds *s) { ds_put_format(s, "%smeter:%s%"PRIu32, colors.param, colors.end, a->meter_id); } /* Clear-Actions instruction. */ static void encode_CLEAR_ACTIONS(const struct ofpact_null *null OVS_UNUSED, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out OVS_UNUSED) { if (ofp_version > OFP10_VERSION) { instruction_put_OFPIT11_CLEAR_ACTIONS(out); } } static char * OVS_WARN_UNUSED_RESULT parse_CLEAR_ACTIONS(char *arg OVS_UNUSED, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { ofpact_put_CLEAR_ACTIONS(ofpacts); return NULL; } static void format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED, struct ds *s) { ds_put_format(s, "%sclear_actions%s", colors.value, colors.end); } /* Write-Actions instruction. */ static void encode_WRITE_ACTIONS(const struct ofpact_nest *actions, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version > OFP10_VERSION) { const size_t ofs = out->size; instruction_put_OFPIT11_WRITE_ACTIONS(out); ofpacts_put_openflow_actions(actions->actions, ofpact_nest_get_action_len(actions), out, ofp_version); ofpacts_update_instruction_actions(out, ofs); } } static char * OVS_WARN_UNUSED_RESULT parse_WRITE_ACTIONS(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { size_t ofs = ofpacts_pull(ofpacts); struct ofpact_nest *on; char *error; /* Add a Write-Actions instruction and then pull it off. */ ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS, sizeof *on); ofpbuf_pull(ofpacts, sizeof *on); /* Parse nested actions. * * We pulled off "write-actions" and the previous actions because the * OFPACT_WRITE_ACTIONS is only partially constructed: its length is such * that it doesn't actually include the nested actions. That means that * ofpacts_parse() would reject them as being part of an Apply-Actions that * follows a Write-Actions, which is an invalid order. */ error = ofpacts_parse(arg, ofpacts, usable_protocols, false, OFPACT_WRITE_ACTIONS); /* Put the Write-Actions back on and update its length. */ on = ofpbuf_push_uninit(ofpacts, sizeof *on); on->ofpact.len = ofpacts->size; /* Put any previous actions or instructions back on. */ ofpbuf_push_uninit(ofpacts, ofs); return error; } static void format_WRITE_ACTIONS(const struct ofpact_nest *a, struct ds *s) { ds_put_format(s, "%swrite_actions(%s", colors.paren, colors.end); ofpacts_format(a->actions, ofpact_nest_get_action_len(a), s); ds_put_format(s, "%s)%s", colors.paren, colors.end); } /* Action structure for NXAST_WRITE_METADATA. * * Modifies the 'mask' bits of the metadata value. */ struct nx_action_write_metadata { ovs_be16 type; /* OFPAT_VENDOR. */ ovs_be16 len; /* Length is 32. */ ovs_be32 vendor; /* NX_VENDOR_ID. */ ovs_be16 subtype; /* NXAST_WRITE_METADATA. */ uint8_t zeros[6]; /* Must be zero. */ ovs_be64 metadata; /* Metadata register. */ ovs_be64 mask; /* Metadata mask. */ }; OFP_ASSERT(sizeof(struct nx_action_write_metadata) == 32); static enum ofperr decode_NXAST_RAW_WRITE_METADATA(const struct nx_action_write_metadata *nawm, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { struct ofpact_metadata *om; if (!is_all_zeros(nawm->zeros, sizeof nawm->zeros)) { return OFPERR_NXBRC_MUST_BE_ZERO; } om = ofpact_put_WRITE_METADATA(out); om->metadata = nawm->metadata; om->mask = nawm->mask; return 0; } static void encode_WRITE_METADATA(const struct ofpact_metadata *metadata, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { struct nx_action_write_metadata *nawm; nawm = put_NXAST_WRITE_METADATA(out); nawm->metadata = metadata->metadata; nawm->mask = metadata->mask; } else { struct ofp11_instruction_write_metadata *oiwm; oiwm = instruction_put_OFPIT11_WRITE_METADATA(out); oiwm->metadata = metadata->metadata; oiwm->metadata_mask = metadata->mask; } } static char * OVS_WARN_UNUSED_RESULT parse_WRITE_METADATA(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { struct ofpact_metadata *om; char *mask = strchr(arg, '/'); *usable_protocols &= OFPUTIL_P_NXM_OF11_UP; om = ofpact_put_WRITE_METADATA(ofpacts); if (mask) { char *error; *mask = '\0'; error = str_to_be64(mask + 1, &om->mask); if (error) { return error; } } else { om->mask = OVS_BE64_MAX; } return str_to_be64(arg, &om->metadata); } static void format_WRITE_METADATA(const struct ofpact_metadata *a, struct ds *s) { ds_put_format(s, "%swrite_metadata:%s%#"PRIx64, colors.param, colors.end, ntohll(a->metadata)); if (a->mask != OVS_BE64_MAX) { ds_put_format(s, "/%#"PRIx64, ntohll(a->mask)); } } /* Goto-Table instruction. */ static void encode_GOTO_TABLE(const struct ofpact_goto_table *goto_table, enum ofp_version ofp_version, struct ofpbuf *out) { if (ofp_version == OFP10_VERSION) { struct nx_action_resubmit *nar; nar = put_NXAST_RESUBMIT_TABLE(out); nar->table = goto_table->table_id; nar->in_port = htons(ofp_to_u16(OFPP_IN_PORT)); } else { struct ofp11_instruction_goto_table *oigt; oigt = instruction_put_OFPIT11_GOTO_TABLE(out); oigt->table_id = goto_table->table_id; memset(oigt->pad, 0, sizeof oigt->pad); } } static char * OVS_WARN_UNUSED_RESULT parse_GOTO_TABLE(char *arg, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols OVS_UNUSED) { struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts); char *table_s = strsep(&arg, ","); if (!table_s || !table_s[0]) { return xstrdup("instruction goto-table needs table id"); } return str_to_u8(table_s, "table", &ogt->table_id); } static void format_GOTO_TABLE(const struct ofpact_goto_table *a, struct ds *s) { ds_put_format(s, "%sgoto_table:%s%"PRIu8, colors.param, colors.end, a->table_id); } static void log_bad_action(const struct ofp_action_header *actions, size_t actions_len, const struct ofp_action_header *bad_action, enum ofperr error) { if (!VLOG_DROP_WARN(&rl)) { struct ds s; ds_init(&s); ds_put_hex_dump(&s, actions, actions_len, 0, false); VLOG_WARN("bad action at offset %#"PRIxPTR" (%s):\n%s", (char *)bad_action - (char *)actions, ofperr_get_name(error), ds_cstr(&s)); ds_destroy(&s); } } static enum ofperr ofpacts_decode(const void *actions, size_t actions_len, enum ofp_version ofp_version, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap, struct ofpbuf *ofpacts) { struct ofpbuf openflow = ofpbuf_const_initializer(actions, actions_len); while (openflow.size) { const struct ofp_action_header *action = openflow.data; enum ofp_raw_action_type raw; enum ofperr error; uint64_t arg; error = ofpact_pull_raw(&openflow, ofp_version, &raw, &arg); if (!error) { error = ofpact_decode(action, raw, ofp_version, arg, vl_mff_map, ofpacts_tlv_bitmap, ofpacts); } if (error) { log_bad_action(actions, actions_len, action, error); return error; } } return 0; } static enum ofperr ofpacts_pull_openflow_actions__(struct ofpbuf *openflow, unsigned int actions_len, enum ofp_version version, uint32_t allowed_ovsinsts, struct ofpbuf *ofpacts, enum ofpact_type outer_action, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap) { const struct ofp_action_header *actions; size_t orig_size = ofpacts->size; enum ofperr error; if (actions_len % OFP_ACTION_ALIGN != 0) { VLOG_WARN_RL(&rl, "OpenFlow message actions length %u is not a " "multiple of %d", actions_len, OFP_ACTION_ALIGN); return OFPERR_OFPBRC_BAD_LEN; } actions = ofpbuf_try_pull(openflow, actions_len); if (actions == NULL) { VLOG_WARN_RL(&rl, "OpenFlow message actions length %u exceeds " "remaining message length (%"PRIu32")", actions_len, openflow->size); return OFPERR_OFPBRC_BAD_LEN; } error = ofpacts_decode(actions, actions_len, version, vl_mff_map, ofpacts_tlv_bitmap, ofpacts); if (error) { ofpacts->size = orig_size; return error; } error = ofpacts_verify(ofpacts->data, ofpacts->size, allowed_ovsinsts, outer_action); if (error) { ofpacts->size = orig_size; } return error; } /* Attempts to convert 'actions_len' bytes of OpenFlow actions from the front * of 'openflow' into ofpacts. On success, appends the converted actions to * 'ofpacts'; on failure, 'ofpacts' is unchanged (but might be reallocated) . * Returns 0 if successful, otherwise an OpenFlow error. * * Actions are processed according to their OpenFlow version which * is provided in the 'version' parameter. * * In most places in OpenFlow, actions appear encapsulated in instructions, so * you should call ofpacts_pull_openflow_instructions() instead of this * function. * * 'vl_mff_map' and 'ofpacts_tlv_bitmap' are optional. If 'vl_mff_map' is * provided, it is used to get variable length mf_fields with configured * length in the actions. If an action uses a variable length mf_field, * 'ofpacts_tlv_bitmap' is updated accordingly for ref counting. If * 'vl_mff_map' is not provided, the default mf_fields with maximum length * will be used. * * The parsed actions are valid generically, but they may not be valid in a * specific context. For example, port numbers up to OFPP_MAX are valid * generically, but specific datapaths may only support port numbers in a * smaller range. Use ofpacts_check() to additional check whether actions are * valid in a specific context. */ enum ofperr ofpacts_pull_openflow_actions(struct ofpbuf *openflow, unsigned int actions_len, enum ofp_version version, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap, struct ofpbuf *ofpacts) { return ofpacts_pull_openflow_actions__(openflow, actions_len, version, 1u << OVSINST_OFPIT11_APPLY_ACTIONS, ofpacts, 0, vl_mff_map, ofpacts_tlv_bitmap); } /* OpenFlow 1.1 actions. */ /* True if an action sets the value of a field * in a way that is compatibile with the action set. * The field can be set via either a set or a move action. * False otherwise. */ static bool ofpact_is_set_or_move_action(const struct ofpact *a) { switch (a->type) { case OFPACT_SET_FIELD: case OFPACT_REG_MOVE: case OFPACT_SET_ETH_DST: case OFPACT_SET_ETH_SRC: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_L4_DST_PORT: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_SET_QUEUE: case OFPACT_SET_TUNNEL: case OFPACT_SET_VLAN_PCP: case OFPACT_SET_VLAN_VID: return true; case OFPACT_BUNDLE: case OFPACT_CLEAR_ACTIONS: case OFPACT_CT: case OFPACT_CT_CLEAR: case OFPACT_CLONE: case OFPACT_NAT: case OFPACT_CONTROLLER: case OFPACT_DEC_MPLS_TTL: case OFPACT_DEC_TTL: case OFPACT_ENQUEUE: case OFPACT_EXIT: case OFPACT_UNROLL_XLATE: case OFPACT_FIN_TIMEOUT: case OFPACT_GOTO_TABLE: case OFPACT_GROUP: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_METER: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_OUTPUT: case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_POP_MPLS: case OFPACT_POP_QUEUE: case OFPACT_PUSH_MPLS: case OFPACT_PUSH_VLAN: case OFPACT_RESUBMIT: case OFPACT_SAMPLE: case OFPACT_STACK_POP: case OFPACT_STACK_PUSH: case OFPACT_STRIP_VLAN: case OFPACT_WRITE_ACTIONS: case OFPACT_WRITE_METADATA: case OFPACT_DEBUG_RECIRC: return false; default: OVS_NOT_REACHED(); } } /* True if an action is allowed in the action set. * False otherwise. */ static bool ofpact_is_allowed_in_actions_set(const struct ofpact *a) { switch (a->type) { case OFPACT_DEC_MPLS_TTL: case OFPACT_DEC_TTL: case OFPACT_GROUP: case OFPACT_OUTPUT: case OFPACT_OUTPUT_TRUNC: case OFPACT_POP_MPLS: case OFPACT_PUSH_MPLS: case OFPACT_PUSH_VLAN: case OFPACT_REG_MOVE: case OFPACT_SET_FIELD: case OFPACT_SET_ETH_DST: case OFPACT_SET_ETH_SRC: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_L4_DST_PORT: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_SET_QUEUE: case OFPACT_SET_TUNNEL: case OFPACT_SET_VLAN_PCP: case OFPACT_SET_VLAN_VID: case OFPACT_STRIP_VLAN: return true; /* In general these actions are excluded because they are not part of * the OpenFlow specification nor map to actions that are defined in * the specification. Thus the order in which they should be applied * in the action set is undefined. */ case OFPACT_BUNDLE: case OFPACT_CLONE: case OFPACT_CONTROLLER: case OFPACT_CT: case OFPACT_CT_CLEAR: case OFPACT_NAT: case OFPACT_ENQUEUE: case OFPACT_EXIT: case OFPACT_UNROLL_XLATE: case OFPACT_FIN_TIMEOUT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_OUTPUT_REG: case OFPACT_POP_QUEUE: case OFPACT_RESUBMIT: case OFPACT_SAMPLE: case OFPACT_STACK_POP: case OFPACT_STACK_PUSH: case OFPACT_DEBUG_RECIRC: /* The action set may only include actions and thus * may not include any instructions */ case OFPACT_CLEAR_ACTIONS: case OFPACT_GOTO_TABLE: case OFPACT_METER: case OFPACT_WRITE_ACTIONS: case OFPACT_WRITE_METADATA: return false; default: OVS_NOT_REACHED(); } } /* Append ofpact 'a' onto the tail of 'out' */ static void ofpact_copy(struct ofpbuf *out, const struct ofpact *a) { ofpbuf_put(out, a, OFPACT_ALIGN(a->len)); } /* Copies the last ofpact whose type is 'filter' from 'in' to 'out'. */ static bool ofpacts_copy_last(struct ofpbuf *out, const struct ofpbuf *in, enum ofpact_type filter) { const struct ofpact *target; const struct ofpact *a; target = NULL; OFPACT_FOR_EACH (a, in->data, in->size) { if (a->type == filter) { target = a; } } if (target) { ofpact_copy(out, target); } return target != NULL; } /* Append all ofpacts, for which 'filter' returns true, from 'in' to 'out'. * The order of appended ofpacts is preserved between 'in' and 'out' */ static void ofpacts_copy_all(struct ofpbuf *out, const struct ofpbuf *in, bool (*filter)(const struct ofpact *)) { const struct ofpact *a; OFPACT_FOR_EACH (a, in->data, in->size) { if (filter(a)) { ofpact_copy(out, a); } } } /* Reads 'action_set', which contains ofpacts accumulated by * OFPACT_WRITE_ACTIONS instructions, and writes equivalent actions to be * executed directly into 'action_list'. (These names correspond to the * "Action Set" and "Action List" terms used in OpenFlow 1.1+.) * * In general this involves appending the last instance of each action that is * admissible in the action set in the order described in the OpenFlow * specification. * * Exceptions: * + output action is only appended if no group action was present in 'in'. * + As a simplification all set actions are copied in the order the are * provided in 'in' as many set actions applied to a field has the same * affect as only applying the last action that sets a field and * duplicates are removed by do_xlate_actions(). * This has an unwanted side-effect of compsoting multiple * LOAD_REG actions that touch different regions of the same field. */ void ofpacts_execute_action_set(struct ofpbuf *action_list, const struct ofpbuf *action_set) { /* The OpenFlow spec "Action Set" section specifies this order. */ ofpacts_copy_last(action_list, action_set, OFPACT_STRIP_VLAN); ofpacts_copy_last(action_list, action_set, OFPACT_POP_MPLS); ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_MPLS); ofpacts_copy_last(action_list, action_set, OFPACT_PUSH_VLAN); ofpacts_copy_last(action_list, action_set, OFPACT_DEC_TTL); ofpacts_copy_last(action_list, action_set, OFPACT_DEC_MPLS_TTL); ofpacts_copy_all(action_list, action_set, ofpact_is_set_or_move_action); ofpacts_copy_last(action_list, action_set, OFPACT_SET_QUEUE); /* If both OFPACT_GROUP and OFPACT_OUTPUT are present, OpenFlow says that * we should execute only OFPACT_GROUP. * * If neither OFPACT_GROUP nor OFPACT_OUTPUT is present, then we can drop * all the actions because there's no point in modifying a packet that will * not be sent anywhere. */ if (!ofpacts_copy_last(action_list, action_set, OFPACT_GROUP) && !ofpacts_copy_last(action_list, action_set, OFPACT_OUTPUT) && !ofpacts_copy_last(action_list, action_set, OFPACT_RESUBMIT) && !ofpacts_copy_last(action_list, action_set, OFPACT_CT)) { ofpbuf_clear(action_list); } } static enum ofperr ofpacts_decode_for_action_set(const struct ofp_action_header *in, size_t n_in, enum ofp_version version, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap, struct ofpbuf *out) { enum ofperr error; struct ofpact *a; size_t start = out->size; error = ofpacts_decode(in, n_in, version, vl_mff_map, ofpacts_tlv_bitmap, out); if (error) { return error; } OFPACT_FOR_EACH (a, ofpact_end(out->data, start), out->size - start) { if (!ofpact_is_allowed_in_actions_set(a)) { VLOG_WARN_RL(&rl, "disallowed action in action set"); return OFPERR_OFPBAC_BAD_TYPE; } } return 0; } /* OpenFlow 1.1 instructions. */ struct instruction_type_info { enum ovs_instruction_type type; const char *name; }; static const struct instruction_type_info inst_info[] = { #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) {OVSINST_##ENUM, NAME}, OVS_INSTRUCTIONS #undef DEFINE_INST }; const char * ovs_instruction_name_from_type(enum ovs_instruction_type type) { return type < ARRAY_SIZE(inst_info) ? inst_info[type].name : NULL; } int ovs_instruction_type_from_name(const char *name) { const struct instruction_type_info *p; for (p = inst_info; p < &inst_info[ARRAY_SIZE(inst_info)]; p++) { if (!strcasecmp(name, p->name)) { return p->type; } } return -1; } enum ovs_instruction_type ovs_instruction_type_from_ofpact_type(enum ofpact_type type) { switch (type) { case OFPACT_METER: return OVSINST_OFPIT13_METER; case OFPACT_CLEAR_ACTIONS: return OVSINST_OFPIT11_CLEAR_ACTIONS; case OFPACT_WRITE_ACTIONS: return OVSINST_OFPIT11_WRITE_ACTIONS; case OFPACT_WRITE_METADATA: return OVSINST_OFPIT11_WRITE_METADATA; case OFPACT_GOTO_TABLE: return OVSINST_OFPIT11_GOTO_TABLE; case OFPACT_OUTPUT: case OFPACT_GROUP: case OFPACT_CLONE: case OFPACT_CONTROLLER: case OFPACT_ENQUEUE: case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_BUNDLE: case OFPACT_SET_VLAN_VID: case OFPACT_SET_VLAN_PCP: case OFPACT_STRIP_VLAN: case OFPACT_PUSH_VLAN: case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: case OFPACT_REG_MOVE: case OFPACT_SET_FIELD: case OFPACT_STACK_PUSH: case OFPACT_STACK_POP: case OFPACT_DEC_TTL: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: case OFPACT_PUSH_MPLS: case OFPACT_POP_MPLS: case OFPACT_SET_TUNNEL: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_FIN_TIMEOUT: case OFPACT_RESUBMIT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_EXIT: case OFPACT_UNROLL_XLATE: case OFPACT_SAMPLE: case OFPACT_DEBUG_RECIRC: case OFPACT_CT: case OFPACT_CT_CLEAR: case OFPACT_NAT: default: return OVSINST_OFPIT11_APPLY_ACTIONS; } } enum ofperr ovs_instruction_type_from_inst_type(enum ovs_instruction_type *instruction_type, const uint16_t inst_type) { switch (inst_type) { #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \ case ENUM: \ *instruction_type = OVSINST_##ENUM; \ return 0; OVS_INSTRUCTIONS #undef DEFINE_INST default: return OFPERR_OFPBIC_UNKNOWN_INST; } } /* Two-way translation between OVS's internal "OVSINST_*" representation of * instructions and the "OFPIT_*" representation used in OpenFlow. */ struct ovsinst_map { enum ovs_instruction_type ovsinst; /* Internal name for instruction. */ int ofpit; /* OFPIT_* number from OpenFlow spec. */ }; static const struct ovsinst_map * get_ovsinst_map(enum ofp_version version) { /* OpenFlow 1.1 and 1.2 instructions. */ static const struct ovsinst_map of11[] = { { OVSINST_OFPIT11_GOTO_TABLE, 1 }, { OVSINST_OFPIT11_WRITE_METADATA, 2 }, { OVSINST_OFPIT11_WRITE_ACTIONS, 3 }, { OVSINST_OFPIT11_APPLY_ACTIONS, 4 }, { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 }, { 0, -1 }, }; /* OpenFlow 1.3+ instructions. */ static const struct ovsinst_map of13[] = { { OVSINST_OFPIT11_GOTO_TABLE, 1 }, { OVSINST_OFPIT11_WRITE_METADATA, 2 }, { OVSINST_OFPIT11_WRITE_ACTIONS, 3 }, { OVSINST_OFPIT11_APPLY_ACTIONS, 4 }, { OVSINST_OFPIT11_CLEAR_ACTIONS, 5 }, { OVSINST_OFPIT13_METER, 6 }, { 0, -1 }, }; return version < OFP13_VERSION ? of11 : of13; } /* Converts 'ovsinst_bitmap', a bitmap whose bits correspond to OVSINST_* * values, into a bitmap of instructions suitable for OpenFlow 'version' * (OFP11_VERSION or later), and returns the result. */ ovs_be32 ovsinst_bitmap_to_openflow(uint32_t ovsinst_bitmap, enum ofp_version version) { uint32_t ofpit_bitmap = 0; const struct ovsinst_map *x; for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) { if (ovsinst_bitmap & (1u << x->ovsinst)) { ofpit_bitmap |= 1u << x->ofpit; } } return htonl(ofpit_bitmap); } /* Converts 'ofpit_bitmap', a bitmap of instructions from an OpenFlow message * with the given 'version' (OFP11_VERSION or later) into a bitmap whose bits * correspond to OVSINST_* values, and returns the result. */ uint32_t ovsinst_bitmap_from_openflow(ovs_be32 ofpit_bitmap, enum ofp_version version) { uint32_t ovsinst_bitmap = 0; const struct ovsinst_map *x; for (x = get_ovsinst_map(version); x->ofpit >= 0; x++) { if (ofpit_bitmap & htonl(1u << x->ofpit)) { ovsinst_bitmap |= 1u << x->ovsinst; } } return ovsinst_bitmap; } static inline struct ofp11_instruction * instruction_next(const struct ofp11_instruction *inst) { return ((struct ofp11_instruction *) (void *) ((uint8_t *) inst + ntohs(inst->len))); } static inline bool instruction_is_valid(const struct ofp11_instruction *inst, size_t n_instructions) { uint16_t len = ntohs(inst->len); return (!(len % OFP11_INSTRUCTION_ALIGN) && len >= sizeof *inst && len / sizeof *inst <= n_instructions); } /* This macro is careful to check for instructions with bad lengths. */ #define INSTRUCTION_FOR_EACH(ITER, LEFT, INSTRUCTIONS, N_INSTRUCTIONS) \ for ((ITER) = (INSTRUCTIONS), (LEFT) = (N_INSTRUCTIONS); \ (LEFT) > 0 && instruction_is_valid(ITER, LEFT); \ ((LEFT) -= (ntohs((ITER)->len) \ / sizeof(struct ofp11_instruction)), \ (ITER) = instruction_next(ITER))) static enum ofperr decode_openflow11_instruction(const struct ofp11_instruction *inst, enum ovs_instruction_type *type) { uint16_t len = ntohs(inst->len); switch (inst->type) { case CONSTANT_HTONS(OFPIT11_EXPERIMENTER): return OFPERR_OFPBIC_BAD_EXPERIMENTER; #define DEFINE_INST(ENUM, STRUCT, EXTENSIBLE, NAME) \ case CONSTANT_HTONS(ENUM): \ if (EXTENSIBLE \ ? len >= sizeof(struct STRUCT) \ : len == sizeof(struct STRUCT)) { \ *type = OVSINST_##ENUM; \ return 0; \ } else { \ return OFPERR_OFPBIC_BAD_LEN; \ } OVS_INSTRUCTIONS #undef DEFINE_INST default: return OFPERR_OFPBIC_UNKNOWN_INST; } } static enum ofperr decode_openflow11_instructions(const struct ofp11_instruction insts[], size_t n_insts, const struct ofp11_instruction *out[]) { const struct ofp11_instruction *inst; size_t left; memset(out, 0, N_OVS_INSTRUCTIONS * sizeof *out); INSTRUCTION_FOR_EACH (inst, left, insts, n_insts) { enum ovs_instruction_type type; enum ofperr error; error = decode_openflow11_instruction(inst, &type); if (error) { return error; } if (out[type]) { return OFPERR_OFPBIC_DUP_INST; } out[type] = inst; } if (left) { VLOG_WARN_RL(&rl, "bad instruction format at offset %"PRIuSIZE, (n_insts - left) * sizeof *inst); return OFPERR_OFPBIC_BAD_LEN; } return 0; } static void get_actions_from_instruction(const struct ofp11_instruction *inst, const struct ofp_action_header **actions, size_t *actions_len) { *actions = ALIGNED_CAST(const struct ofp_action_header *, inst + 1); *actions_len = ntohs(inst->len) - sizeof *inst; } enum ofperr ofpacts_pull_openflow_instructions(struct ofpbuf *openflow, unsigned int instructions_len, enum ofp_version version, const struct vl_mff_map *vl_mff_map, uint64_t *ofpacts_tlv_bitmap, struct ofpbuf *ofpacts) { const struct ofp11_instruction *instructions; const struct ofp11_instruction *insts[N_OVS_INSTRUCTIONS]; enum ofperr error; ofpbuf_clear(ofpacts); if (version == OFP10_VERSION) { return ofpacts_pull_openflow_actions__(openflow, instructions_len, version, (1u << N_OVS_INSTRUCTIONS) - 1, ofpacts, 0, vl_mff_map, ofpacts_tlv_bitmap); } if (instructions_len % OFP11_INSTRUCTION_ALIGN != 0) { VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u is not a " "multiple of %d", instructions_len, OFP11_INSTRUCTION_ALIGN); error = OFPERR_OFPBIC_BAD_LEN; goto exit; } instructions = ofpbuf_try_pull(openflow, instructions_len); if (instructions == NULL) { VLOG_WARN_RL(&rl, "OpenFlow message instructions length %u exceeds " "remaining message length (%"PRIu32")", instructions_len, openflow->size); error = OFPERR_OFPBIC_BAD_LEN; goto exit; } error = decode_openflow11_instructions( instructions, instructions_len / OFP11_INSTRUCTION_ALIGN, insts); if (error) { goto exit; } if (insts[OVSINST_OFPIT13_METER]) { const struct ofp13_instruction_meter *oim; struct ofpact_meter *om; oim = ALIGNED_CAST(const struct ofp13_instruction_meter *, insts[OVSINST_OFPIT13_METER]); om = ofpact_put_METER(ofpacts); om->meter_id = ntohl(oim->meter_id); } if (insts[OVSINST_OFPIT11_APPLY_ACTIONS]) { const struct ofp_action_header *actions; size_t actions_len; get_actions_from_instruction(insts[OVSINST_OFPIT11_APPLY_ACTIONS], &actions, &actions_len); error = ofpacts_decode(actions, actions_len, version, vl_mff_map, ofpacts_tlv_bitmap, ofpacts); if (error) { goto exit; } } if (insts[OVSINST_OFPIT11_CLEAR_ACTIONS]) { instruction_get_OFPIT11_CLEAR_ACTIONS( insts[OVSINST_OFPIT11_CLEAR_ACTIONS]); ofpact_put_CLEAR_ACTIONS(ofpacts); } if (insts[OVSINST_OFPIT11_WRITE_ACTIONS]) { struct ofpact_nest *on; const struct ofp_action_header *actions; size_t actions_len; size_t start = ofpacts->size; ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS, offsetof(struct ofpact_nest, actions)); get_actions_from_instruction(insts[OVSINST_OFPIT11_WRITE_ACTIONS], &actions, &actions_len); error = ofpacts_decode_for_action_set(actions, actions_len, version, vl_mff_map, ofpacts_tlv_bitmap, ofpacts); if (error) { goto exit; } on = ofpbuf_at_assert(ofpacts, start, sizeof *on); on->ofpact.len = ofpacts->size - start; } if (insts[OVSINST_OFPIT11_WRITE_METADATA]) { const struct ofp11_instruction_write_metadata *oiwm; struct ofpact_metadata *om; oiwm = ALIGNED_CAST(const struct ofp11_instruction_write_metadata *, insts[OVSINST_OFPIT11_WRITE_METADATA]); om = ofpact_put_WRITE_METADATA(ofpacts); om->metadata = oiwm->metadata; om->mask = oiwm->metadata_mask; } if (insts[OVSINST_OFPIT11_GOTO_TABLE]) { const struct ofp11_instruction_goto_table *oigt; struct ofpact_goto_table *ogt; oigt = instruction_get_OFPIT11_GOTO_TABLE( insts[OVSINST_OFPIT11_GOTO_TABLE]); ogt = ofpact_put_GOTO_TABLE(ofpacts); ogt->table_id = oigt->table_id; } error = ofpacts_verify(ofpacts->data, ofpacts->size, (1u << N_OVS_INSTRUCTIONS) - 1, 0); exit: if (error) { ofpbuf_clear(ofpacts); } return error; } /* Update the length of the instruction that begins at offset 'ofs' within * 'openflow' and contains nested actions that extend to the end of 'openflow'. * If the instruction contains no nested actions, deletes it entirely. */ static void ofpacts_update_instruction_actions(struct ofpbuf *openflow, size_t ofs) { struct ofp11_instruction_actions *oia; oia = ofpbuf_at_assert(openflow, ofs, sizeof *oia); if (openflow->size > ofs + sizeof *oia) { oia->len = htons(openflow->size - ofs); } else { openflow->size = ofs; } } /* Checks that 'port' is a valid output port for OFPACT_OUTPUT, given that the * switch will never have more than 'max_ports' ports. Returns 0 if 'port' is * valid, otherwise an OpenFlow error code. */ enum ofperr ofpact_check_output_port(ofp_port_t port, ofp_port_t max_ports) { switch (port) { case OFPP_IN_PORT: case OFPP_TABLE: case OFPP_NORMAL: case OFPP_FLOOD: case OFPP_ALL: case OFPP_CONTROLLER: case OFPP_LOCAL: return 0; case OFPP_NONE: return OFPERR_OFPBAC_BAD_OUT_PORT; default: if (ofp_to_u16(port) < ofp_to_u16(max_ports)) { return 0; } return OFPERR_OFPBAC_BAD_OUT_PORT; } } /* Removes the protocols that require consistency between match and actions * (that's everything but OpenFlow 1.0) from '*usable_protocols'. * * (An example of an inconsistency between match and actions is a flow that * does not match on an MPLS Ethertype but has an action that pops an MPLS * label.) */ static void inconsistent_match(enum ofputil_protocol *usable_protocols) { *usable_protocols &= OFPUTIL_P_OF10_ANY; } /* May modify flow->dl_type, flow->nw_proto and flow->vlan_tci, * caller must restore them. * * Modifies some actions, filling in fields that could not be properly set * without context. */ static enum ofperr ofpact_check__(enum ofputil_protocol *usable_protocols, struct ofpact *a, struct flow *flow, ofp_port_t max_ports, uint8_t table_id, uint8_t n_tables) { const struct ofpact_enqueue *enqueue; const struct mf_field *mf; switch (a->type) { case OFPACT_OUTPUT: return ofpact_check_output_port(ofpact_get_OUTPUT(a)->port, max_ports); case OFPACT_CONTROLLER: return 0; case OFPACT_ENQUEUE: enqueue = ofpact_get_ENQUEUE(a); if (ofp_to_u16(enqueue->port) >= ofp_to_u16(max_ports) && enqueue->port != OFPP_IN_PORT && enqueue->port != OFPP_LOCAL) { return OFPERR_OFPBAC_BAD_OUT_PORT; } return 0; case OFPACT_OUTPUT_REG: return mf_check_src(&ofpact_get_OUTPUT_REG(a)->src, flow); case OFPACT_OUTPUT_TRUNC: return ofpact_check_output_port(ofpact_get_OUTPUT_TRUNC(a)->port, max_ports); case OFPACT_BUNDLE: return bundle_check(ofpact_get_BUNDLE(a), max_ports, flow); case OFPACT_SET_VLAN_VID: /* Remember if we saw a vlan tag in the flow to aid translating to * OpenFlow 1.1+ if need be. */ ofpact_get_SET_VLAN_VID(a)->flow_has_vlan = (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI); if (!(flow->vlan_tci & htons(VLAN_CFI)) && !ofpact_get_SET_VLAN_VID(a)->push_vlan_if_needed) { inconsistent_match(usable_protocols); } /* Temporary mark that we have a vlan tag. */ flow->vlan_tci |= htons(VLAN_CFI); return 0; case OFPACT_SET_VLAN_PCP: /* Remember if we saw a vlan tag in the flow to aid translating to * OpenFlow 1.1+ if need be. */ ofpact_get_SET_VLAN_PCP(a)->flow_has_vlan = (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI); if (!(flow->vlan_tci & htons(VLAN_CFI)) && !ofpact_get_SET_VLAN_PCP(a)->push_vlan_if_needed) { inconsistent_match(usable_protocols); } /* Temporary mark that we have a vlan tag. */ flow->vlan_tci |= htons(VLAN_CFI); return 0; case OFPACT_STRIP_VLAN: if (!(flow->vlan_tci & htons(VLAN_CFI))) { inconsistent_match(usable_protocols); } /* Temporary mark that we have no vlan tag. */ flow->vlan_tci = htons(0); return 0; case OFPACT_PUSH_VLAN: if (flow->vlan_tci & htons(VLAN_CFI)) { /* Multiple VLAN headers not supported. */ return OFPERR_OFPBAC_BAD_TAG; } /* Temporary mark that we have a vlan tag. */ flow->vlan_tci |= htons(VLAN_CFI); return 0; case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: return 0; case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: if (flow->dl_type != htons(ETH_TYPE_IP)) { inconsistent_match(usable_protocols); } return 0; case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_DEC_TTL: if (!is_ip_any(flow)) { inconsistent_match(usable_protocols); } return 0; case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: if (!is_ip_any(flow) || (flow->nw_frag & FLOW_NW_FRAG_LATER) || (flow->nw_proto != IPPROTO_TCP && flow->nw_proto != IPPROTO_UDP && flow->nw_proto != IPPROTO_SCTP)) { inconsistent_match(usable_protocols); } /* Note on which transport protocol the port numbers are set. * This allows this set action to be converted to an OF1.2 set field * action. */ if (a->type == OFPACT_SET_L4_SRC_PORT) { ofpact_get_SET_L4_SRC_PORT(a)->flow_ip_proto = flow->nw_proto; } else { ofpact_get_SET_L4_DST_PORT(a)->flow_ip_proto = flow->nw_proto; } return 0; case OFPACT_REG_MOVE: return nxm_reg_move_check(ofpact_get_REG_MOVE(a), flow); case OFPACT_SET_FIELD: mf = ofpact_get_SET_FIELD(a)->field; /* Require OXM_OF_VLAN_VID to have an existing VLAN header. */ if (!mf_are_prereqs_ok(mf, flow, NULL) || (mf->id == MFF_VLAN_VID && !(flow->vlan_tci & htons(VLAN_CFI)))) { VLOG_WARN_RL(&rl, "set_field %s lacks correct prerequisities", mf->name); return OFPERR_OFPBAC_MATCH_INCONSISTENT; } /* Remember if we saw a vlan tag in the flow to aid translating to * OpenFlow 1.1 if need be. */ ofpact_get_SET_FIELD(a)->flow_has_vlan = (flow->vlan_tci & htons(VLAN_CFI)) == htons(VLAN_CFI); if (mf->id == MFF_VLAN_TCI) { /* The set field may add or remove the vlan tag, * Mark the status temporarily. */ flow->vlan_tci = ofpact_get_SET_FIELD(a)->value->be16; } return 0; case OFPACT_STACK_PUSH: return nxm_stack_push_check(ofpact_get_STACK_PUSH(a), flow); case OFPACT_STACK_POP: return nxm_stack_pop_check(ofpact_get_STACK_POP(a), flow); case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: if (!eth_type_mpls(flow->dl_type)) { inconsistent_match(usable_protocols); } return 0; case OFPACT_SET_TUNNEL: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_RESUBMIT: return 0; case OFPACT_FIN_TIMEOUT: if (flow->nw_proto != IPPROTO_TCP) { inconsistent_match(usable_protocols); } return 0; case OFPACT_LEARN: return learn_check(ofpact_get_LEARN(a), flow); case OFPACT_CONJUNCTION: return 0; case OFPACT_MULTIPATH: return multipath_check(ofpact_get_MULTIPATH(a), flow); case OFPACT_NOTE: case OFPACT_EXIT: return 0; case OFPACT_PUSH_MPLS: flow->dl_type = ofpact_get_PUSH_MPLS(a)->ethertype; /* The packet is now MPLS and the MPLS payload is opaque. * Thus nothing can be assumed about the network protocol. * Temporarily mark that we have no nw_proto. */ flow->nw_proto = 0; return 0; case OFPACT_POP_MPLS: if (!eth_type_mpls(flow->dl_type)) { inconsistent_match(usable_protocols); } flow->dl_type = ofpact_get_POP_MPLS(a)->ethertype; return 0; case OFPACT_SAMPLE: return 0; case OFPACT_CLONE: { struct ofpact_nest *on = ofpact_get_CLONE(a); return ofpacts_check(on->actions, ofpact_nest_get_action_len(on), flow, max_ports, table_id, n_tables, usable_protocols); } case OFPACT_CT: { struct ofpact_conntrack *oc = ofpact_get_CT(a); if (!dl_type_is_ip_any(flow->dl_type) || (flow->ct_state & CS_INVALID && oc->flags & NX_CT_F_COMMIT) || (oc->alg == IPPORT_FTP && flow->nw_proto != IPPROTO_TCP) || (oc->alg == IPPORT_TFTP && flow->nw_proto != IPPROTO_UDP)) { /* We can't downgrade to OF1.0 and expect inconsistent CT actions * be silently discarded. Instead, datapath flow install fails, so * it is better to flag inconsistent CT actions as hard errors. */ return OFPERR_OFPBAC_MATCH_INCONSISTENT; } if (oc->zone_src.field) { return mf_check_src(&oc->zone_src, flow); } return ofpacts_check(oc->actions, ofpact_ct_get_action_len(oc), flow, max_ports, table_id, n_tables, usable_protocols); } case OFPACT_CT_CLEAR: return 0; case OFPACT_NAT: { struct ofpact_nat *on = ofpact_get_NAT(a); if (!dl_type_is_ip_any(flow->dl_type) || (on->range_af == AF_INET && flow->dl_type != htons(ETH_TYPE_IP)) || (on->range_af == AF_INET6 && flow->dl_type != htons(ETH_TYPE_IPV6))) { return OFPERR_OFPBAC_MATCH_INCONSISTENT; } return 0; } case OFPACT_CLEAR_ACTIONS: return 0; case OFPACT_WRITE_ACTIONS: { /* Use a temporary copy of 'usable_protocols' because we can't check * consistency of an action set. */ struct ofpact_nest *on = ofpact_get_WRITE_ACTIONS(a); enum ofputil_protocol p = *usable_protocols; return ofpacts_check(on->actions, ofpact_nest_get_action_len(on), flow, max_ports, table_id, n_tables, &p); } case OFPACT_WRITE_METADATA: return 0; case OFPACT_METER: { uint32_t mid = ofpact_get_METER(a)->meter_id; if (mid == 0 || mid > OFPM13_MAX) { return OFPERR_OFPMMFC_INVALID_METER; } return 0; } case OFPACT_GOTO_TABLE: { uint8_t goto_table = ofpact_get_GOTO_TABLE(a)->table_id; if ((table_id != 255 && goto_table <= table_id) || (n_tables != 255 && goto_table >= n_tables)) { return OFPERR_OFPBIC_BAD_TABLE_ID; } return 0; } case OFPACT_GROUP: return 0; case OFPACT_UNROLL_XLATE: /* UNROLL is an internal action that should never be seen via * OpenFlow. */ return OFPERR_OFPBAC_BAD_TYPE; case OFPACT_DEBUG_RECIRC: return 0; default: OVS_NOT_REACHED(); } } /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are * appropriate for a packet with the prerequisites satisfied by 'flow' in a * switch with no more than 'max_ports' ports. * * If 'ofpacts' and 'flow' are inconsistent with one another, un-sets in * '*usable_protocols' the protocols that forbid the inconsistency. (An * example of an inconsistency between match and actions is a flow that does * not match on an MPLS Ethertype but has an action that pops an MPLS label.) * * May annotate ofpacts with information gathered from the 'flow'. * * May temporarily modify 'flow', but restores the changes before returning. */ enum ofperr ofpacts_check(struct ofpact ofpacts[], size_t ofpacts_len, struct flow *flow, ofp_port_t max_ports, uint8_t table_id, uint8_t n_tables, enum ofputil_protocol *usable_protocols) { struct ofpact *a; ovs_be16 dl_type = flow->dl_type; ovs_be16 vlan_tci = flow->vlan_tci; uint8_t nw_proto = flow->nw_proto; enum ofperr error = 0; OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { error = ofpact_check__(usable_protocols, a, flow, max_ports, table_id, n_tables); if (error) { break; } } /* Restore fields that may have been modified. */ flow->dl_type = dl_type; flow->vlan_tci = vlan_tci; flow->nw_proto = nw_proto; return error; } /* Like ofpacts_check(), but reports inconsistencies as * OFPERR_OFPBAC_MATCH_INCONSISTENT rather than clearing bits. */ enum ofperr ofpacts_check_consistency(struct ofpact ofpacts[], size_t ofpacts_len, struct flow *flow, ofp_port_t max_ports, uint8_t table_id, uint8_t n_tables, enum ofputil_protocol usable_protocols) { enum ofputil_protocol p = usable_protocols; enum ofperr error; error = ofpacts_check(ofpacts, ofpacts_len, flow, max_ports, table_id, n_tables, &p); return (error ? error : p != usable_protocols ? OFPERR_OFPBAC_MATCH_INCONSISTENT : 0); } /* Returns the destination field that 'ofpact' would write to, or NULL * if the action would not write to an mf_field. */ const struct mf_field * ofpact_get_mf_dst(const struct ofpact *ofpact) { if (ofpact->type == OFPACT_SET_FIELD) { const struct ofpact_set_field *orl; orl = CONTAINER_OF(ofpact, struct ofpact_set_field, ofpact); return orl->field; } else if (ofpact->type == OFPACT_REG_MOVE) { const struct ofpact_reg_move *orm; orm = CONTAINER_OF(ofpact, struct ofpact_reg_move, ofpact); return orm->dst.field; } return NULL; } static enum ofperr unsupported_nesting(enum ofpact_type action, enum ofpact_type outer_action) { VLOG_WARN("%s action doesn't support nested action %s", ofpact_name(outer_action), ofpact_name(action)); return OFPERR_OFPBAC_BAD_ARGUMENT; } static bool field_requires_ct(enum mf_field_id field) { return field == MFF_CT_MARK || field == MFF_CT_LABEL; } /* Apply nesting constraints for actions */ static enum ofperr ofpacts_verify_nested(const struct ofpact *a, enum ofpact_type outer_action) { const struct mf_field *field = ofpact_get_mf_dst(a); if (field && field_requires_ct(field->id) && outer_action != OFPACT_CT) { VLOG_WARN("cannot set CT fields outside of ct action"); return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } if (a->type == OFPACT_NAT) { if (outer_action != OFPACT_CT) { VLOG_WARN("Cannot have NAT action outside of \"ct\" action"); return OFPERR_OFPBAC_BAD_SET_ARGUMENT; } return 0; } if (outer_action) { ovs_assert(outer_action == OFPACT_WRITE_ACTIONS || outer_action == OFPACT_CT); if (outer_action == OFPACT_CT) { if (!field) { return unsupported_nesting(a->type, outer_action); } else if (!field_requires_ct(field->id)) { VLOG_WARN("%s action doesn't support nested modification " "of %s", ofpact_name(outer_action), field->name); return OFPERR_OFPBAC_BAD_ARGUMENT; } } } return 0; } /* Verifies that the 'ofpacts_len' bytes of actions in 'ofpacts' are in the * appropriate order as defined by the OpenFlow spec and as required by Open * vSwitch. * * 'allowed_ovsinsts' is a bitmap of OVSINST_* values, in which 1-bits indicate * instructions that are allowed within 'ofpacts[]'. * * If 'outer_action' is not zero, it specifies that the actions are nested * within another action of type 'outer_action'. */ static enum ofperr ofpacts_verify(const struct ofpact ofpacts[], size_t ofpacts_len, uint32_t allowed_ovsinsts, enum ofpact_type outer_action) { const struct ofpact *a; enum ovs_instruction_type inst; inst = OVSINST_OFPIT13_METER; OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { enum ovs_instruction_type next; enum ofperr error; if (a->type == OFPACT_CONJUNCTION) { OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { if (a->type != OFPACT_CONJUNCTION && a->type != OFPACT_NOTE) { VLOG_WARN("\"conjunction\" actions may be used along with " "\"note\" but not any other kind of action " "(such as the \"%s\" action used here)", ofpact_name(a->type)); return OFPERR_NXBAC_BAD_CONJUNCTION; } } return 0; } error = ofpacts_verify_nested(a, outer_action); if (error) { return error; } next = ovs_instruction_type_from_ofpact_type(a->type); if (a > ofpacts && (inst == OVSINST_OFPIT11_APPLY_ACTIONS ? next < inst : next <= inst)) { const char *name = ovs_instruction_name_from_type(inst); const char *next_name = ovs_instruction_name_from_type(next); if (next == inst) { VLOG_WARN("duplicate %s instruction not allowed, for OpenFlow " "1.1+ compatibility", name); } else { VLOG_WARN("invalid instruction ordering: %s must appear " "before %s, for OpenFlow 1.1+ compatibility", next_name, name); } return OFPERR_OFPBAC_UNSUPPORTED_ORDER; } if (!((1u << next) & allowed_ovsinsts)) { const char *name = ovs_instruction_name_from_type(next); VLOG_WARN("%s instruction not allowed here", name); return OFPERR_OFPBIC_UNSUP_INST; } inst = next; } return 0; } /* Converting ofpacts to OpenFlow. */ static void encode_ofpact(const struct ofpact *a, enum ofp_version ofp_version, struct ofpbuf *out) { switch (a->type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) \ case OFPACT_##ENUM: \ encode_##ENUM(ofpact_get_##ENUM(a), ofp_version, out); \ return; OFPACTS #undef OFPACT default: OVS_NOT_REACHED(); } } /* Converts the 'ofpacts_len' bytes of ofpacts in 'ofpacts' into OpenFlow * actions in 'openflow', appending the actions to any existing data in * 'openflow'. */ size_t ofpacts_put_openflow_actions(const struct ofpact ofpacts[], size_t ofpacts_len, struct ofpbuf *openflow, enum ofp_version ofp_version) { const struct ofpact *a; size_t start_size = openflow->size; OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { encode_ofpact(a, ofp_version, openflow); } return openflow->size - start_size; } static enum ovs_instruction_type ofpact_is_apply_actions(const struct ofpact *a) { return (ovs_instruction_type_from_ofpact_type(a->type) == OVSINST_OFPIT11_APPLY_ACTIONS); } void ofpacts_put_openflow_instructions(const struct ofpact ofpacts[], size_t ofpacts_len, struct ofpbuf *openflow, enum ofp_version ofp_version) { const struct ofpact *end = ofpact_end(ofpacts, ofpacts_len); const struct ofpact *a; if (ofp_version == OFP10_VERSION) { ofpacts_put_openflow_actions(ofpacts, ofpacts_len, openflow, ofp_version); return; } a = ofpacts; while (a < end) { if (ofpact_is_apply_actions(a)) { size_t ofs = openflow->size; instruction_put_OFPIT11_APPLY_ACTIONS(openflow); do { encode_ofpact(a, ofp_version, openflow); a = ofpact_next(a); } while (a < end && ofpact_is_apply_actions(a)); ofpacts_update_instruction_actions(openflow, ofs); } else { encode_ofpact(a, ofp_version, openflow); a = ofpact_next(a); } } } /* Sets of supported actions. */ /* Two-way translation between OVS's internal "OFPACT_*" representation of * actions and the "OFPAT_*" representation used in some OpenFlow version. * (OFPAT_* numbering varies from one OpenFlow version to another, so a given * instance is specific to one OpenFlow version.) */ struct ofpact_map { enum ofpact_type ofpact; /* Internal name for action type. */ int ofpat; /* OFPAT_* number from OpenFlow spec. */ }; static const struct ofpact_map * get_ofpact_map(enum ofp_version version) { /* OpenFlow 1.0 actions. */ static const struct ofpact_map of10[] = { { OFPACT_OUTPUT, 0 }, { OFPACT_SET_VLAN_VID, 1 }, { OFPACT_SET_VLAN_PCP, 2 }, { OFPACT_STRIP_VLAN, 3 }, { OFPACT_SET_ETH_SRC, 4 }, { OFPACT_SET_ETH_DST, 5 }, { OFPACT_SET_IPV4_SRC, 6 }, { OFPACT_SET_IPV4_DST, 7 }, { OFPACT_SET_IP_DSCP, 8 }, { OFPACT_SET_L4_SRC_PORT, 9 }, { OFPACT_SET_L4_DST_PORT, 10 }, { OFPACT_ENQUEUE, 11 }, { 0, -1 }, }; /* OpenFlow 1.1 actions. */ static const struct ofpact_map of11[] = { { OFPACT_OUTPUT, 0 }, { OFPACT_SET_VLAN_VID, 1 }, { OFPACT_SET_VLAN_PCP, 2 }, { OFPACT_SET_ETH_SRC, 3 }, { OFPACT_SET_ETH_DST, 4 }, { OFPACT_SET_IPV4_SRC, 5 }, { OFPACT_SET_IPV4_DST, 6 }, { OFPACT_SET_IP_DSCP, 7 }, { OFPACT_SET_IP_ECN, 8 }, { OFPACT_SET_L4_SRC_PORT, 9 }, { OFPACT_SET_L4_DST_PORT, 10 }, /* OFPAT_COPY_TTL_OUT (11) not supported. */ /* OFPAT_COPY_TTL_IN (12) not supported. */ { OFPACT_SET_MPLS_LABEL, 13 }, { OFPACT_SET_MPLS_TC, 14 }, { OFPACT_SET_MPLS_TTL, 15 }, { OFPACT_DEC_MPLS_TTL, 16 }, { OFPACT_PUSH_VLAN, 17 }, { OFPACT_STRIP_VLAN, 18 }, { OFPACT_PUSH_MPLS, 19 }, { OFPACT_POP_MPLS, 20 }, { OFPACT_SET_QUEUE, 21 }, { OFPACT_GROUP, 22 }, { OFPACT_SET_IP_TTL, 23 }, { OFPACT_DEC_TTL, 24 }, { 0, -1 }, }; /* OpenFlow 1.2, 1.3, and 1.4 actions. */ static const struct ofpact_map of12[] = { { OFPACT_OUTPUT, 0 }, /* OFPAT_COPY_TTL_OUT (11) not supported. */ /* OFPAT_COPY_TTL_IN (12) not supported. */ { OFPACT_SET_MPLS_TTL, 15 }, { OFPACT_DEC_MPLS_TTL, 16 }, { OFPACT_PUSH_VLAN, 17 }, { OFPACT_STRIP_VLAN, 18 }, { OFPACT_PUSH_MPLS, 19 }, { OFPACT_POP_MPLS, 20 }, { OFPACT_SET_QUEUE, 21 }, { OFPACT_GROUP, 22 }, { OFPACT_SET_IP_TTL, 23 }, { OFPACT_DEC_TTL, 24 }, { OFPACT_SET_FIELD, 25 }, /* OF1.3+ OFPAT_PUSH_PBB (26) not supported. */ /* OF1.3+ OFPAT_POP_PBB (27) not supported. */ { 0, -1 }, }; switch (version) { case OFP10_VERSION: return of10; case OFP11_VERSION: return of11; case OFP12_VERSION: case OFP13_VERSION: case OFP14_VERSION: case OFP15_VERSION: case OFP16_VERSION: default: return of12; } } /* Converts 'ofpacts_bitmap', a bitmap whose bits correspond to OFPACT_* * values, into a bitmap of actions suitable for OpenFlow 'version', and * returns the result. */ ovs_be32 ofpact_bitmap_to_openflow(uint64_t ofpacts_bitmap, enum ofp_version version) { uint32_t openflow_bitmap = 0; const struct ofpact_map *x; for (x = get_ofpact_map(version); x->ofpat >= 0; x++) { if (ofpacts_bitmap & (UINT64_C(1) << x->ofpact)) { openflow_bitmap |= 1u << x->ofpat; } } return htonl(openflow_bitmap); } /* Converts 'ofpat_bitmap', a bitmap of actions from an OpenFlow message with * the given 'version' into a bitmap whose bits correspond to OFPACT_* values, * and returns the result. */ uint64_t ofpact_bitmap_from_openflow(ovs_be32 ofpat_bitmap, enum ofp_version version) { uint64_t ofpact_bitmap = 0; const struct ofpact_map *x; for (x = get_ofpact_map(version); x->ofpat >= 0; x++) { if (ofpat_bitmap & htonl(1u << x->ofpat)) { ofpact_bitmap |= UINT64_C(1) << x->ofpact; } } return ofpact_bitmap; } /* Appends to 's' a string representation of the set of OFPACT_* represented * by 'ofpacts_bitmap'. */ void ofpact_bitmap_format(uint64_t ofpacts_bitmap, struct ds *s) { if (!ofpacts_bitmap) { ds_put_cstr(s, "<none>"); } else { while (ofpacts_bitmap) { ds_put_format(s, "%s ", ofpact_name(rightmost_1bit_idx(ofpacts_bitmap))); ofpacts_bitmap = zero_rightmost_1bit(ofpacts_bitmap); } ds_chomp(s, ' '); } } /* Returns true if 'action' outputs to 'port', false otherwise. */ static bool ofpact_outputs_to_port(const struct ofpact *ofpact, ofp_port_t port) { switch (ofpact->type) { case OFPACT_OUTPUT: return ofpact_get_OUTPUT(ofpact)->port == port; case OFPACT_ENQUEUE: return ofpact_get_ENQUEUE(ofpact)->port == port; case OFPACT_CONTROLLER: return port == OFPP_CONTROLLER; case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_BUNDLE: case OFPACT_SET_VLAN_VID: case OFPACT_SET_VLAN_PCP: case OFPACT_STRIP_VLAN: case OFPACT_PUSH_VLAN: case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: case OFPACT_REG_MOVE: case OFPACT_SET_FIELD: case OFPACT_STACK_PUSH: case OFPACT_STACK_POP: case OFPACT_DEC_TTL: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: case OFPACT_SET_TUNNEL: case OFPACT_WRITE_METADATA: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_FIN_TIMEOUT: case OFPACT_RESUBMIT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_EXIT: case OFPACT_UNROLL_XLATE: case OFPACT_PUSH_MPLS: case OFPACT_POP_MPLS: case OFPACT_SAMPLE: case OFPACT_CLEAR_ACTIONS: case OFPACT_CLONE: case OFPACT_WRITE_ACTIONS: case OFPACT_GOTO_TABLE: case OFPACT_METER: case OFPACT_GROUP: case OFPACT_DEBUG_RECIRC: case OFPACT_CT: case OFPACT_CT_CLEAR: case OFPACT_NAT: default: return false; } } /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs * to 'port', false otherwise. */ bool ofpacts_output_to_port(const struct ofpact *ofpacts, size_t ofpacts_len, ofp_port_t port) { const struct ofpact *a; OFPACT_FOR_EACH_FLATTENED (a, ofpacts, ofpacts_len) { if (ofpact_outputs_to_port(a, port)) { return true; } } return false; } /* Returns true if any action in the 'ofpacts_len' bytes of 'ofpacts' outputs * to 'group', false otherwise. */ bool ofpacts_output_to_group(const struct ofpact *ofpacts, size_t ofpacts_len, uint32_t group_id) { const struct ofpact *a; OFPACT_FOR_EACH_FLATTENED (a, ofpacts, ofpacts_len) { if (a->type == OFPACT_GROUP && ofpact_get_GROUP(a)->group_id == group_id) { return true; } } return false; } bool ofpacts_equal(const struct ofpact *a, size_t a_len, const struct ofpact *b, size_t b_len) { return a_len == b_len && !memcmp(a, b, a_len); } /* Finds the OFPACT_METER action, if any, in the 'ofpacts_len' bytes of * 'ofpacts'. If found, returns its meter ID; if not, returns 0. * * This function relies on the order of 'ofpacts' being correct (as checked by * ofpacts_verify()). */ uint32_t ofpacts_get_meter(const struct ofpact ofpacts[], size_t ofpacts_len) { const struct ofpact *a; OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { enum ovs_instruction_type inst; inst = ovs_instruction_type_from_ofpact_type(a->type); if (a->type == OFPACT_METER) { return ofpact_get_METER(a)->meter_id; } else if (inst > OVSINST_OFPIT13_METER) { break; } } return 0; } /* Formatting ofpacts. */ static void ofpact_format(const struct ofpact *a, struct ds *s) { switch (a->type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) \ case OFPACT_##ENUM: \ format_##ENUM(ALIGNED_CAST(const struct STRUCT *, a), s); \ break; OFPACTS #undef OFPACT default: OVS_NOT_REACHED(); } } /* Appends a string representing the 'ofpacts_len' bytes of ofpacts in * 'ofpacts' to 'string'. */ void ofpacts_format(const struct ofpact *ofpacts, size_t ofpacts_len, struct ds *string) { if (!ofpacts_len) { ds_put_format(string, "%sdrop%s", colors.drop, colors.end); } else { const struct ofpact *a; OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) { if (a != ofpacts) { ds_put_char(string, ','); } ofpact_format(a, string); } } } /* Internal use by helpers. */ /* Implementation of ofpact_put_<ENUM>(). */ void * ofpact_put(struct ofpbuf *ofpacts, enum ofpact_type type, size_t len) { struct ofpact *ofpact; ofpacts->header = ofpbuf_put_uninit(ofpacts, len); ofpact = ofpacts->header; ofpact_init(ofpact, type, len); return ofpact; } /* Implementation of ofpact_init_<ENUM>(). */ void ofpact_init(struct ofpact *ofpact, enum ofpact_type type, size_t len) { memset(ofpact, 0, len); ofpact->type = type; ofpact->raw = -1; ofpact->len = len; } /* Implementation of ofpact_finish_<ENUM>(). * * Finishes composing a variable-length action (begun using * ofpact_put_<NAME>()), by padding the action to a multiple of OFPACT_ALIGNTO * bytes and updating its embedded length field. See the large comment near * the end of ofp-actions.h for more information. * * May reallocate 'ofpacts'. Callers should consider updating their 'ofpact' * pointer to the return value of this function. */ void * ofpact_finish(struct ofpbuf *ofpacts, struct ofpact *ofpact) { ptrdiff_t len; ovs_assert(ofpact == ofpacts->header); len = (char *) ofpbuf_tail(ofpacts) - (char *) ofpact; ovs_assert(len > 0 && len <= UINT16_MAX); ofpact->len = len; ofpbuf_padto(ofpacts, OFPACT_ALIGN(ofpacts->size)); return ofpacts->header; } static char * OVS_WARN_UNUSED_RESULT ofpact_parse(enum ofpact_type type, char *value, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { switch (type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) \ case OFPACT_##ENUM: \ return parse_##ENUM(value, ofpacts, usable_protocols); OFPACTS #undef OFPACT default: OVS_NOT_REACHED(); } } static bool ofpact_type_from_name(const char *name, enum ofpact_type *type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) \ if (!strcasecmp(name, NAME)) { \ *type = OFPACT_##ENUM; \ return true; \ } OFPACTS #undef OFPACT return false; } /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. * * If 'outer_action' is specified, indicates that the actions being parsed * are nested within another action of the type specified in 'outer_action'. */ static char * OVS_WARN_UNUSED_RESULT ofpacts_parse__(char *str, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols, bool allow_instructions, enum ofpact_type outer_action) { int prev_inst = -1; enum ofperr retval; char *key, *value; bool drop = false; char *pos; pos = str; while (ofputil_parse_key_value(&pos, &key, &value)) { enum ovs_instruction_type inst = OVSINST_OFPIT11_APPLY_ACTIONS; enum ofpact_type type; char *error = NULL; ofp_port_t port; if (ofpact_type_from_name(key, &type)) { error = ofpact_parse(type, value, ofpacts, usable_protocols); inst = ovs_instruction_type_from_ofpact_type(type); } else if (!strcasecmp(key, "mod_vlan_vid")) { error = parse_set_vlan_vid(value, ofpacts, true); } else if (!strcasecmp(key, "mod_vlan_pcp")) { error = parse_set_vlan_pcp(value, ofpacts, true); } else if (!strcasecmp(key, "set_nw_ttl")) { error = parse_SET_IP_TTL(value, ofpacts, usable_protocols); } else if (!strcasecmp(key, "pop_vlan")) { error = parse_pop_vlan(ofpacts); } else if (!strcasecmp(key, "set_tunnel64")) { error = parse_set_tunnel(value, ofpacts, NXAST_RAW_SET_TUNNEL64); } else if (!strcasecmp(key, "load")) { error = parse_reg_load(value, ofpacts); } else if (!strcasecmp(key, "bundle_load")) { error = parse_bundle_load(value, ofpacts); } else if (!strcasecmp(key, "drop")) { drop = true; } else if (!strcasecmp(key, "apply_actions")) { return xstrdup("apply_actions is the default instruction"); } else if (ofputil_port_from_string(key, &port)) { ofpact_put_OUTPUT(ofpacts)->port = port; } else { return xasprintf("unknown action %s", key); } if (error) { return error; } if (inst != OVSINST_OFPIT11_APPLY_ACTIONS) { if (!allow_instructions) { return xasprintf("only actions are allowed here (not " "instruction %s)", ovs_instruction_name_from_type(inst)); } if (inst == prev_inst) { return xasprintf("instruction %s may be specified only once", ovs_instruction_name_from_type(inst)); } } if (prev_inst != -1 && inst < prev_inst) { return xasprintf("instruction %s must be specified before %s", ovs_instruction_name_from_type(inst), ovs_instruction_name_from_type(prev_inst)); } prev_inst = inst; } if (drop && ofpacts->size) { return xstrdup("\"drop\" must not be accompanied by any other action " "or instruction"); } retval = ofpacts_verify(ofpacts->data, ofpacts->size, (allow_instructions ? (1u << N_OVS_INSTRUCTIONS) - 1 : 1u << OVSINST_OFPIT11_APPLY_ACTIONS), outer_action); if (retval) { return xstrdup("Incorrect instruction ordering"); } return NULL; } static char * OVS_WARN_UNUSED_RESULT ofpacts_parse(char *str, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols, bool allow_instructions, enum ofpact_type outer_action) { uint32_t orig_size = ofpacts->size; char *error = ofpacts_parse__(str, ofpacts, usable_protocols, allow_instructions, outer_action); if (error) { ofpacts->size = orig_size; } return error; } static char * OVS_WARN_UNUSED_RESULT ofpacts_parse_copy(const char *s_, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols, bool allow_instructions, enum ofpact_type outer_action) { char *error, *s; *usable_protocols = OFPUTIL_P_ANY; s = xstrdup(s_); error = ofpacts_parse(s, ofpacts, usable_protocols, allow_instructions, outer_action); free(s); return error; } /* Parses 's' as a set of OpenFlow actions and appends the actions to * 'ofpacts'. 'outer_action', if nonzero, specifies that 's' contains actions * that are nested within the action of type 'outer_action'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ char * OVS_WARN_UNUSED_RESULT ofpacts_parse_actions(const char *s, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { return ofpacts_parse_copy(s, ofpacts, usable_protocols, false, 0); } /* Parses 's' as a set of OpenFlow instructions and appends the instructions to * 'ofpacts'. * * Returns NULL if successful, otherwise a malloc()'d string describing the * error. The caller is responsible for freeing the returned string. */ char * OVS_WARN_UNUSED_RESULT ofpacts_parse_instructions(const char *s, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { return ofpacts_parse_copy(s, ofpacts, usable_protocols, true, 0); } const char * ofpact_name(enum ofpact_type type) { switch (type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) case OFPACT_##ENUM: return NAME; OFPACTS #undef OFPACT } return "<unknown>"; } /* Low-level action decoding and encoding functions. */ /* Everything needed to identify a particular OpenFlow action. */ struct ofpact_hdrs { uint32_t vendor; /* 0 if standard, otherwise a vendor code. */ uint16_t type; /* Type if standard, otherwise subtype. */ uint8_t ofp_version; /* From ofp_header. */ }; /* Information about a particular OpenFlow action. */ struct ofpact_raw_instance { /* The action's identity. */ struct ofpact_hdrs hdrs; enum ofp_raw_action_type raw; /* Looking up the action. */ struct hmap_node decode_node; /* Based on 'hdrs'. */ struct hmap_node encode_node; /* Based on 'raw' + 'hdrs.ofp_version'. */ /* The action's encoded size. * * If this action is fixed-length, 'min_length' == 'max_length'. * If it is variable length, then 'max_length' is ROUND_DOWN(UINT16_MAX, * OFP_ACTION_ALIGN) == 65528. */ unsigned short int min_length; unsigned short int max_length; /* For actions with a simple integer numeric argument, 'arg_ofs' is the * offset of that argument from the beginning of the action and 'arg_len' * its length, both in bytes. * * For actions that take other forms, these are both zero. */ unsigned short int arg_ofs; unsigned short int arg_len; /* The name of the action, e.g. "OFPAT_OUTPUT" or "NXAST_RESUBMIT". */ const char *name; /* If this action is deprecated, a human-readable string with a brief * explanation. */ const char *deprecation; }; /* Action header. */ struct ofp_action_header { /* The meaning of other values of 'type' generally depends on the OpenFlow * version (see enum ofp_raw_action_type). * * Across all OpenFlow versions, OFPAT_VENDOR indicates that 'vendor' * designates an OpenFlow vendor ID and that the remainder of the action * structure has a vendor-defined meaning. */ #define OFPAT_VENDOR 0xffff ovs_be16 type; /* Always a multiple of 8. */ ovs_be16 len; /* For type == OFPAT_VENDOR only, this is a vendor ID, e.g. NX_VENDOR_ID or * ONF_VENDOR_ID. Other 'type's use this space for some other purpose. */ ovs_be32 vendor; }; OFP_ASSERT(sizeof(struct ofp_action_header) == 8); static bool ofpact_hdrs_equal(const struct ofpact_hdrs *a, const struct ofpact_hdrs *b) { return (a->vendor == b->vendor && a->type == b->type && a->ofp_version == b->ofp_version); } static uint32_t ofpact_hdrs_hash(const struct ofpact_hdrs *hdrs) { return hash_2words(hdrs->vendor, (hdrs->type << 16) | hdrs->ofp_version); } #include "ofp-actions.inc2" static struct hmap * ofpact_decode_hmap(void) { static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER; static struct hmap hmap; if (ovsthread_once_start(&once)) { struct ofpact_raw_instance *inst; hmap_init(&hmap); for (inst = all_raw_instances; inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)]; inst++) { hmap_insert(&hmap, &inst->decode_node, ofpact_hdrs_hash(&inst->hdrs)); } ovsthread_once_done(&once); } return &hmap; } static struct hmap * ofpact_encode_hmap(void) { static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER; static struct hmap hmap; if (ovsthread_once_start(&once)) { struct ofpact_raw_instance *inst; hmap_init(&hmap); for (inst = all_raw_instances; inst < &all_raw_instances[ARRAY_SIZE(all_raw_instances)]; inst++) { hmap_insert(&hmap, &inst->encode_node, hash_2words(inst->raw, inst->hdrs.ofp_version)); } ovsthread_once_done(&once); } return &hmap; } static enum ofperr ofpact_decode_raw(enum ofp_version ofp_version, const struct ofp_action_header *oah, size_t length, const struct ofpact_raw_instance **instp) { const struct ofpact_raw_instance *inst; struct ofpact_hdrs hdrs; *instp = NULL; if (length < sizeof *oah) { return OFPERR_OFPBAC_BAD_LEN; } /* Get base action type. */ if (oah->type == htons(OFPAT_VENDOR)) { /* Get vendor. */ hdrs.vendor = ntohl(oah->vendor); if (hdrs.vendor == NX_VENDOR_ID || hdrs.vendor == ONF_VENDOR_ID) { /* Get extension subtype. */ const struct ext_action_header *nah; nah = ALIGNED_CAST(const struct ext_action_header *, oah); if (length < sizeof *nah) { return OFPERR_OFPBAC_BAD_LEN; } hdrs.type = ntohs(nah->subtype); } else { VLOG_WARN_RL(&rl, "OpenFlow action has unknown vendor %#"PRIx32, hdrs.vendor); return OFPERR_OFPBAC_BAD_VENDOR; } } else { hdrs.vendor = 0; hdrs.type = ntohs(oah->type); } hdrs.ofp_version = ofp_version; HMAP_FOR_EACH_WITH_HASH (inst, decode_node, ofpact_hdrs_hash(&hdrs), ofpact_decode_hmap()) { if (ofpact_hdrs_equal(&hdrs, &inst->hdrs)) { *instp = inst; return 0; } } return (hdrs.vendor ? OFPERR_OFPBAC_BAD_VENDOR_TYPE : OFPERR_OFPBAC_BAD_TYPE); } static enum ofperr ofpact_pull_raw(struct ofpbuf *buf, enum ofp_version ofp_version, enum ofp_raw_action_type *raw, uint64_t *arg) { const struct ofp_action_header *oah = buf->data; const struct ofpact_raw_instance *action; unsigned int length; enum ofperr error; *raw = *arg = 0; error = ofpact_decode_raw(ofp_version, oah, buf->size, &action); if (error) { return error; } if (action->deprecation) { VLOG_INFO_RL(&rl, "%s is deprecated in %s (%s)", action->name, ofputil_version_to_string(ofp_version), action->deprecation); } length = ntohs(oah->len); if (length > buf->size) { VLOG_WARN_RL(&rl, "OpenFlow action %s length %u exceeds action buffer " "length %"PRIu32, action->name, length, buf->size); return OFPERR_OFPBAC_BAD_LEN; } if (length < action->min_length || length > action->max_length) { VLOG_WARN_RL(&rl, "OpenFlow action %s length %u not in valid range " "[%hu,%hu]", action->name, length, action->min_length, action->max_length); return OFPERR_OFPBAC_BAD_LEN; } if (length % 8) { VLOG_WARN_RL(&rl, "OpenFlow action %s length %u is not a multiple " "of 8", action->name, length); return OFPERR_OFPBAC_BAD_LEN; } *raw = action->raw; *arg = 0; if (action->arg_len) { const uint8_t *p; int i; p = ofpbuf_at_assert(buf, action->arg_ofs, action->arg_len); for (i = 0; i < action->arg_len; i++) { *arg = (*arg << 8) | p[i]; } } ofpbuf_pull(buf, length); return 0; } static const struct ofpact_raw_instance * ofpact_raw_lookup(enum ofp_version ofp_version, enum ofp_raw_action_type raw) { const struct ofpact_raw_instance *inst; HMAP_FOR_EACH_WITH_HASH (inst, encode_node, hash_2words(raw, ofp_version), ofpact_encode_hmap()) { if (inst->raw == raw && inst->hdrs.ofp_version == ofp_version) { return inst; } } OVS_NOT_REACHED(); } static void * ofpact_put_raw(struct ofpbuf *buf, enum ofp_version ofp_version, enum ofp_raw_action_type raw, uint64_t arg) { const struct ofpact_raw_instance *inst; struct ofp_action_header *oah; const struct ofpact_hdrs *hdrs; inst = ofpact_raw_lookup(ofp_version, raw); hdrs = &inst->hdrs; oah = ofpbuf_put_zeros(buf, inst->min_length); oah->type = htons(hdrs->vendor ? OFPAT_VENDOR : hdrs->type); oah->len = htons(inst->min_length); oah->vendor = htonl(hdrs->vendor); switch (hdrs->vendor) { case 0: break; case NX_VENDOR_ID: case ONF_VENDOR_ID: { struct ext_action_header *nah = (struct ext_action_header *) oah; nah->subtype = htons(hdrs->type); break; } default: OVS_NOT_REACHED(); } if (inst->arg_len) { uint8_t *p = (uint8_t *) oah + inst->arg_ofs + inst->arg_len; int i; for (i = 0; i < inst->arg_len; i++) { *--p = arg; arg >>= 8; } } else { ovs_assert(!arg); } return oah; } static void pad_ofpat(struct ofpbuf *openflow, size_t start_ofs) { struct ofp_action_header *oah; ofpbuf_put_zeros(openflow, PAD_SIZE(openflow->size - start_ofs, OFP_ACTION_ALIGN)); oah = ofpbuf_at_assert(openflow, start_ofs, sizeof *oah); oah->len = htons(openflow->size - start_ofs); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_391_0
crossvul-cpp_data_bad_260_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Internet Control Message Protocol (ICMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "udp.h" #include "ipproto.h" #include "mpls.h" /* * Interface Control Message Protocol Definitions. * Per RFC 792, September 1981. */ /* * Structure of an icmp header. */ struct icmp { uint8_t icmp_type; /* type of message, see below */ uint8_t icmp_code; /* type sub code */ uint16_t icmp_cksum; /* ones complement cksum of struct */ union { uint8_t ih_pptr; /* ICMP_PARAMPROB */ struct in_addr ih_gwaddr; /* ICMP_REDIRECT */ struct ih_idseq { uint16_t icd_id; uint16_t icd_seq; } ih_idseq; uint32_t ih_void; } icmp_hun; #define icmp_pptr icmp_hun.ih_pptr #define icmp_gwaddr icmp_hun.ih_gwaddr #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq #define icmp_void icmp_hun.ih_void union { struct id_ts { uint32_t its_otime; uint32_t its_rtime; uint32_t its_ttime; } id_ts; struct id_ip { struct ip idi_ip; /* options and then 64 bits of data */ } id_ip; uint32_t id_mask; uint8_t id_data[1]; } icmp_dun; #define icmp_otime icmp_dun.id_ts.its_otime #define icmp_rtime icmp_dun.id_ts.its_rtime #define icmp_ttime icmp_dun.id_ts.its_ttime #define icmp_ip icmp_dun.id_ip.idi_ip #define icmp_mask icmp_dun.id_mask #define icmp_data icmp_dun.id_data }; #define ICMP_MPLS_EXT_EXTRACT_VERSION(x) (((x)&0xf0)>>4) #define ICMP_MPLS_EXT_VERSION 2 /* * Lower bounds on packet lengths for various types. * For the error advice packets must first insure that the * packet is large enought to contain the returned ip header. * Only then can we do the check to see if 64 bits of packet * data have been returned, since we need to check the returned * ip header length. */ #define ICMP_MINLEN 8 /* abs minimum */ #define ICMP_EXTD_MINLEN (156 - sizeof (struct ip)) /* draft-bonica-internet-icmp-08 */ #define ICMP_TSLEN (8 + 3 * sizeof (uint32_t)) /* timestamp */ #define ICMP_MASKLEN 12 /* address mask */ #define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */ #define ICMP_ADVLEN(p) (8 + (IP_HL(&(p)->icmp_ip) << 2) + 8) /* N.B.: must separately check that ip_hl >= 5 */ /* * Definition of type and code field values. */ #define ICMP_ECHOREPLY 0 /* echo reply */ #define ICMP_UNREACH 3 /* dest unreachable, codes: */ #define ICMP_UNREACH_NET 0 /* bad net */ #define ICMP_UNREACH_HOST 1 /* bad host */ #define ICMP_UNREACH_PROTOCOL 2 /* bad protocol */ #define ICMP_UNREACH_PORT 3 /* bad port */ #define ICMP_UNREACH_NEEDFRAG 4 /* IP_DF caused drop */ #define ICMP_UNREACH_SRCFAIL 5 /* src route failed */ #define ICMP_UNREACH_NET_UNKNOWN 6 /* unknown net */ #define ICMP_UNREACH_HOST_UNKNOWN 7 /* unknown host */ #define ICMP_UNREACH_ISOLATED 8 /* src host isolated */ #define ICMP_UNREACH_NET_PROHIB 9 /* prohibited access */ #define ICMP_UNREACH_HOST_PROHIB 10 /* ditto */ #define ICMP_UNREACH_TOSNET 11 /* bad tos for net */ #define ICMP_UNREACH_TOSHOST 12 /* bad tos for host */ #define ICMP_SOURCEQUENCH 4 /* packet lost, slow down */ #define ICMP_REDIRECT 5 /* shorter route, codes: */ #define ICMP_REDIRECT_NET 0 /* for network */ #define ICMP_REDIRECT_HOST 1 /* for host */ #define ICMP_REDIRECT_TOSNET 2 /* for tos and net */ #define ICMP_REDIRECT_TOSHOST 3 /* for tos and host */ #define ICMP_ECHO 8 /* echo service */ #define ICMP_ROUTERADVERT 9 /* router advertisement */ #define ICMP_ROUTERSOLICIT 10 /* router solicitation */ #define ICMP_TIMXCEED 11 /* time exceeded, code: */ #define ICMP_TIMXCEED_INTRANS 0 /* ttl==0 in transit */ #define ICMP_TIMXCEED_REASS 1 /* ttl==0 in reass */ #define ICMP_PARAMPROB 12 /* ip header bad */ #define ICMP_PARAMPROB_OPTABSENT 1 /* req. opt. absent */ #define ICMP_TSTAMP 13 /* timestamp request */ #define ICMP_TSTAMPREPLY 14 /* timestamp reply */ #define ICMP_IREQ 15 /* information request */ #define ICMP_IREQREPLY 16 /* information reply */ #define ICMP_MASKREQ 17 /* address mask request */ #define ICMP_MASKREPLY 18 /* address mask reply */ #define ICMP_MAXTYPE 18 #define ICMP_ERRTYPE(type) \ ((type) == ICMP_UNREACH || (type) == ICMP_SOURCEQUENCH || \ (type) == ICMP_REDIRECT || (type) == ICMP_TIMXCEED || \ (type) == ICMP_PARAMPROB) #define ICMP_MPLS_EXT_TYPE(type) \ ((type) == ICMP_UNREACH || \ (type) == ICMP_TIMXCEED || \ (type) == ICMP_PARAMPROB) /* rfc1700 */ #ifndef ICMP_UNREACH_NET_UNKNOWN #define ICMP_UNREACH_NET_UNKNOWN 6 /* destination net unknown */ #endif #ifndef ICMP_UNREACH_HOST_UNKNOWN #define ICMP_UNREACH_HOST_UNKNOWN 7 /* destination host unknown */ #endif #ifndef ICMP_UNREACH_ISOLATED #define ICMP_UNREACH_ISOLATED 8 /* source host isolated */ #endif #ifndef ICMP_UNREACH_NET_PROHIB #define ICMP_UNREACH_NET_PROHIB 9 /* admin prohibited net */ #endif #ifndef ICMP_UNREACH_HOST_PROHIB #define ICMP_UNREACH_HOST_PROHIB 10 /* admin prohibited host */ #endif #ifndef ICMP_UNREACH_TOSNET #define ICMP_UNREACH_TOSNET 11 /* tos prohibited net */ #endif #ifndef ICMP_UNREACH_TOSHOST #define ICMP_UNREACH_TOSHOST 12 /* tos prohibited host */ #endif /* rfc1716 */ #ifndef ICMP_UNREACH_FILTER_PROHIB #define ICMP_UNREACH_FILTER_PROHIB 13 /* admin prohibited filter */ #endif #ifndef ICMP_UNREACH_HOST_PRECEDENCE #define ICMP_UNREACH_HOST_PRECEDENCE 14 /* host precedence violation */ #endif #ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF #define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 /* precedence cutoff */ #endif /* Most of the icmp types */ static const struct tok icmp2str[] = { { ICMP_ECHOREPLY, "echo reply" }, { ICMP_SOURCEQUENCH, "source quench" }, { ICMP_ECHO, "echo request" }, { ICMP_ROUTERSOLICIT, "router solicitation" }, { ICMP_TSTAMP, "time stamp request" }, { ICMP_TSTAMPREPLY, "time stamp reply" }, { ICMP_IREQ, "information request" }, { ICMP_IREQREPLY, "information reply" }, { ICMP_MASKREQ, "address mask request" }, { 0, NULL } }; /* Formats for most of the ICMP_UNREACH codes */ static const struct tok unreach2str[] = { { ICMP_UNREACH_NET, "net %s unreachable" }, { ICMP_UNREACH_HOST, "host %s unreachable" }, { ICMP_UNREACH_SRCFAIL, "%s unreachable - source route failed" }, { ICMP_UNREACH_NET_UNKNOWN, "net %s unreachable - unknown" }, { ICMP_UNREACH_HOST_UNKNOWN, "host %s unreachable - unknown" }, { ICMP_UNREACH_ISOLATED, "%s unreachable - source host isolated" }, { ICMP_UNREACH_NET_PROHIB, "net %s unreachable - admin prohibited" }, { ICMP_UNREACH_HOST_PROHIB, "host %s unreachable - admin prohibited" }, { ICMP_UNREACH_TOSNET, "net %s unreachable - tos prohibited" }, { ICMP_UNREACH_TOSHOST, "host %s unreachable - tos prohibited" }, { ICMP_UNREACH_FILTER_PROHIB, "host %s unreachable - admin prohibited filter" }, { ICMP_UNREACH_HOST_PRECEDENCE, "host %s unreachable - host precedence violation" }, { ICMP_UNREACH_PRECEDENCE_CUTOFF, "host %s unreachable - precedence cutoff" }, { 0, NULL } }; /* Formats for the ICMP_REDIRECT codes */ static const struct tok type2str[] = { { ICMP_REDIRECT_NET, "redirect %s to net %s" }, { ICMP_REDIRECT_HOST, "redirect %s to host %s" }, { ICMP_REDIRECT_TOSNET, "redirect-tos %s to net %s" }, { ICMP_REDIRECT_TOSHOST, "redirect-tos %s to host %s" }, { 0, NULL } }; /* rfc1191 */ struct mtu_discovery { uint16_t unused; uint16_t nexthopmtu; }; /* rfc1256 */ struct ih_rdiscovery { uint8_t ird_addrnum; uint8_t ird_addrsiz; uint16_t ird_lifetime; }; struct id_rdiscovery { uint32_t ird_addr; uint32_t ird_pref; }; /* * draft-bonica-internet-icmp-08 * * The Destination Unreachable, Time Exceeded * and Parameter Problem messages are slighly changed as per * the above draft. A new Length field gets added to give * the caller an idea about the length of the piggypacked * IP packet before the MPLS extension header starts. * * The Length field represents length of the padded "original datagram" * field measured in 32-bit words. * * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Code | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | unused | Length | unused | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Internet Header + leading octets of original datagram | * | | * | // | * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct icmp_ext_t { uint8_t icmp_type; uint8_t icmp_code; uint8_t icmp_checksum[2]; uint8_t icmp_reserved; uint8_t icmp_length; uint8_t icmp_reserved2[2]; uint8_t icmp_ext_legacy_header[128]; /* extension header starts 128 bytes after ICMP header */ uint8_t icmp_ext_version_res[2]; uint8_t icmp_ext_checksum[2]; uint8_t icmp_ext_data[1]; }; struct icmp_mpls_ext_object_header_t { uint8_t length[2]; uint8_t class_num; uint8_t ctype; }; static const struct tok icmp_mpls_ext_obj_values[] = { { 1, "MPLS Stack Entry" }, { 2, "Extended Payload" }, { 0, NULL} }; /* prototypes */ const char *icmp_tstamp_print(u_int); /* print the milliseconds since midnight UTC */ const char * icmp_tstamp_print(u_int tstamp) { u_int msec,sec,min,hrs; static char buf[64]; msec = tstamp % 1000; sec = tstamp / 1000; min = sec / 60; sec -= min * 60; hrs = min / 60; min -= hrs * 60; snprintf(buf, sizeof(buf), "%02u:%02u:%02u.%03u",hrs,min,sec,msec); return buf; } void icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, int fragmented) { char *cp; const struct icmp *dp; const struct icmp_ext_t *ext_dp; const struct ip *ip; const char *str, *fmt; const struct ip *oip; const struct udphdr *ouh; const uint8_t *obj_tptr; uint32_t raw_label; const u_char *snapend_save; const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; char buf[MAXHOSTNAMELEN + 100]; struct cksum_vec vec[1]; dp = (const struct icmp *)bp; ext_dp = (const struct icmp_ext_t *)bp; ip = (const struct ip *)bp2; str = buf; ND_TCHECK(dp->icmp_code); switch (dp->icmp_type) { case ICMP_ECHO: case ICMP_ECHOREPLY: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u", dp->icmp_type == ICMP_ECHO ? "request" : "reply", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_UNREACH: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_UNREACH_PROTOCOL: ND_TCHECK(dp->icmp_ip.ip_p); (void)snprintf(buf, sizeof(buf), "%s protocol %d unreachable", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), dp->icmp_ip.ip_p); break; case ICMP_UNREACH_PORT: ND_TCHECK(dp->icmp_ip.ip_p); oip = &dp->icmp_ip; hlen = IP_HL(oip) * 4; ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); ND_TCHECK(ouh->uh_dport); dport = EXTRACT_16BITS(&ouh->uh_dport); switch (oip->ip_p) { case IPPROTO_TCP: (void)snprintf(buf, sizeof(buf), "%s tcp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), tcpport_string(ndo, dport)); break; case IPPROTO_UDP: (void)snprintf(buf, sizeof(buf), "%s udp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), udpport_string(ndo, dport)); break; default: (void)snprintf(buf, sizeof(buf), "%s protocol %u port %u unreachable", ipaddr_string(ndo, &oip->ip_dst), oip->ip_p, dport); break; } break; case ICMP_UNREACH_NEEDFRAG: { register const struct mtu_discovery *mp; mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; mtu = EXTRACT_16BITS(&mp->nexthopmtu); if (mtu) { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag (mtu %d)", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); } else { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag", ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); } } break; default: fmt = tok2str(unreach2str, "#%d %%s unreachable", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); break; } break; case ICMP_REDIRECT: ND_TCHECK(dp->icmp_ip.ip_dst); fmt = tok2str(type2str, "redirect-#%d %%s to net %%s", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst), ipaddr_string(ndo, &dp->icmp_gwaddr)); break; case ICMP_ROUTERADVERT: { register const struct ih_rdiscovery *ihp; register const struct id_rdiscovery *idp; u_int lifetime, num, size; (void)snprintf(buf, sizeof(buf), "router advertisement"); cp = buf + strlen(buf); ihp = (const struct ih_rdiscovery *)&dp->icmp_void; ND_TCHECK(*ihp); (void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf)); cp = buf + strlen(buf); lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); if (lifetime < 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u", lifetime); } else if (lifetime < 60 * 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u", lifetime / 60, lifetime % 60); } else { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u:%02u", lifetime / 3600, (lifetime % 3600) / 60, lifetime % 60); } cp = buf + strlen(buf); num = ihp->ird_addrnum; (void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num); cp = buf + strlen(buf); size = ihp->ird_addrsiz; if (size != 2) { (void)snprintf(cp, sizeof(buf) - (cp - buf), " [size %d]", size); break; } idp = (const struct id_rdiscovery *)&dp->icmp_data; while (num-- > 0) { ND_TCHECK(*idp); (void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}", ipaddr_string(ndo, &idp->ird_addr), EXTRACT_32BITS(&idp->ird_pref)); cp = buf + strlen(buf); ++idp; } } break; case ICMP_TIMXCEED: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_TIMXCEED_INTRANS: str = "time exceeded in-transit"; break; case ICMP_TIMXCEED_REASS: str = "ip reassembly time exceeded"; break; default: (void)snprintf(buf, sizeof(buf), "time exceeded-#%u", dp->icmp_code); break; } break; case ICMP_PARAMPROB: if (dp->icmp_code) (void)snprintf(buf, sizeof(buf), "parameter problem - code %u", dp->icmp_code); else { ND_TCHECK(dp->icmp_pptr); (void)snprintf(buf, sizeof(buf), "parameter problem - octet %u", dp->icmp_pptr); } break; case ICMP_MASKREPLY: ND_TCHECK(dp->icmp_mask); (void)snprintf(buf, sizeof(buf), "address mask is 0x%08x", EXTRACT_32BITS(&dp->icmp_mask)); break; case ICMP_TSTAMP: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "time stamp query id %u seq %u", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_TSTAMPREPLY: ND_TCHECK(dp->icmp_ttime); (void)snprintf(buf, sizeof(buf), "time stamp reply id %u seq %u: org %s", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq), icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); break; default: str = tok2str(icmp2str, "type-#%d", dp->icmp_type); break; } ND_PRINT((ndo, "ICMP %s, length %u", str, plen)); if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ if (ND_TTEST2(*bp, plen)) { uint16_t sum; vec[0].ptr = (const uint8_t *)(const void *)dp; vec[0].len = plen; sum = in_cksum(vec, 1); if (sum != 0) { uint16_t icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)", icmp_sum, in_cksum_shouldbe(icmp_sum, sum))); } } } /* * print the remnants of the IP packet. * save the snaplength as this may get overidden in the IP printer. */ if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { bp += 8; ND_PRINT((ndo, "\n\t")); ip = (const struct ip *)bp; ndo->ndo_snaplen = ndo->ndo_snapend - bp; snapend_save = ndo->ndo_snapend; ND_TCHECK_16BITS(&ip->ip_len); ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); ndo->ndo_snapend = snapend_save; } /* * Attempt to decode the MPLS extensions only for some ICMP types. */ if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { ND_TCHECK(*ext_dp); /* * Check first if the mpls extension header shows a non-zero length. * If the length field is not set then silently verify the checksum * to check if an extension header is present. This is expedient, * however not all implementations set the length field proper. */ if (!ext_dp->icmp_length && ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = plen - ICMP_EXTD_MINLEN; if (in_cksum(vec, 1)) { return; } } ND_PRINT((ndo, "\n\tMPLS extension v%u", ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); /* * Sanity checking of the header. */ if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != ICMP_MPLS_EXT_VERSION) { ND_PRINT((ndo, " packet not supported")); return; } hlen = plen - ICMP_EXTD_MINLEN; if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = hlen; ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u", EXTRACT_16BITS(ext_dp->icmp_ext_checksum), in_cksum(vec, 1) ? "in" : "", hlen)); } hlen -= 4; /* subtract common header size */ obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; ND_TCHECK(*icmp_mpls_ext_object_header); obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); obj_class_num = icmp_mpls_ext_object_header->class_num; obj_ctype = icmp_mpls_ext_object_header->ctype; obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u", tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num), obj_class_num, obj_ctype, obj_tlen)); hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ /* infinite loop protection */ if ((obj_class_num == 0) || (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { return; } obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); switch (obj_class_num) { case 1: switch(obj_ctype) { case 1: ND_TCHECK2(*obj_tptr, 4); raw_label = EXTRACT_32BITS(obj_tptr); ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); if (MPLS_STACK(raw_label)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label))); break; default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case 2: default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); break; } if (hlen < obj_tlen) break; hlen -= obj_tlen; obj_tptr += obj_tlen; } } return; trunc: ND_PRINT((ndo, "[|icmp]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_260_0
crossvul-cpp_data_good_675_0
/** * WinPR: Windows Portable Runtime * NTLM Security Package (Message) * * Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ntlm.h" #include "../sspi.h" #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/stream.h> #include <winpr/sysinfo.h> #include "ntlm_compute.h" #include "ntlm_message.h" #include "../log.h" #define TAG WINPR_TAG("sspi.NTLM") static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' }; static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56", "NTLMSSP_NEGOTIATE_KEY_EXCH", "NTLMSSP_NEGOTIATE_128", "NTLMSSP_RESERVED1", "NTLMSSP_RESERVED2", "NTLMSSP_RESERVED3", "NTLMSSP_NEGOTIATE_VERSION", "NTLMSSP_RESERVED4", "NTLMSSP_NEGOTIATE_TARGET_INFO", "NTLMSSP_REQUEST_NON_NT_SESSION_KEY", "NTLMSSP_RESERVED5", "NTLMSSP_NEGOTIATE_IDENTIFY", "NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY", "NTLMSSP_RESERVED6", "NTLMSSP_TARGET_TYPE_SERVER", "NTLMSSP_TARGET_TYPE_DOMAIN", "NTLMSSP_NEGOTIATE_ALWAYS_SIGN", "NTLMSSP_RESERVED7", "NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED", "NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED", "NTLMSSP_NEGOTIATE_ANONYMOUS", "NTLMSSP_RESERVED8", "NTLMSSP_NEGOTIATE_NTLM", "NTLMSSP_RESERVED9", "NTLMSSP_NEGOTIATE_LM_KEY", "NTLMSSP_NEGOTIATE_DATAGRAM", "NTLMSSP_NEGOTIATE_SEAL", "NTLMSSP_NEGOTIATE_SIGN", "NTLMSSP_RESERVED10", "NTLMSSP_REQUEST_TARGET", "NTLMSSP_NEGOTIATE_OEM", "NTLMSSP_NEGOTIATE_UNICODE" }; static void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } } static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { if (Stream_GetRemainingLength(s) < 12) return -1; Stream_Read(s, header->Signature, 8); Stream_Read_UINT32(s, header->MessageType); if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0) return -1; return 1; } static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->MaxLen < 1) fields->MaxLen = fields->Len; Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ } static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %"PRIu32")", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_NEGOTIATE); if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); context->NegotiateFlags = message->NegotiateFlags; /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ /* WorkstationFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; int length; PBYTE StartOffset; PBYTE PayloadOffset; NTLM_AV_PAIR* AvTimestamp; NTLM_CHALLENGE_MESSAGE* message; ntlm_generate_client_challenge(context); message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; StartOffset = Stream_Pointer(s); if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_CHALLENGE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (Stream_GetRemainingLength(s) < 4) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateFlags = message->NegotiateFlags; if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ CopyMemory(context->ServerChallenge, message->ServerChallenge, 8); if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } /* Payload (variable) */ PayloadOffset = Stream_Pointer(s); if (message->TargetName.Len > 0) { if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } } if (message->TargetInfo.Len > 0) { if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer; context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len; AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*) message->TargetInfo.Buffer, MsvAvTimestamp); if (AvTimestamp) { if (context->NTLMv2) context->UseMIC = TRUE; CopyMemory(context->ChallengeTimestamp, ntlm_av_pair_get_value_pointer(AvTimestamp), 8); } } length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(context->NegotiateFlags); if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); if (context->ChallengeTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "ChallengeTargetInfo (%"PRIu32"):", context->ChallengeTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer); } #endif /* AV_PAIRs */ if (context->NTLMv2) { if (ntlm_construct_authenticate_target_info(context) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } sspi_SecBufferFree(&context->ChallengeTargetInfo); context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer; context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer; } ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */ ntlm_generate_random_session_key(context); /* RandomSessionKey */ ntlm_generate_exported_session_key(context); /* ExportedSessionKey */ ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */ /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state using client sealing key */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_AUTHENTICATE; ntlm_free_message_fields_buffer(&(message->TargetName)); Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadOffset; NTLM_CHALLENGE_MESSAGE* message; message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_get_version_info(&(message->Version)); /* Version */ ntlm_generate_server_challenge(context); /* Server Challenge */ ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */ message->NegotiateFlags = context->NegotiateFlags; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_CHALLENGE); /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) { message->TargetName.Len = (UINT16) context->TargetName.cbBuffer; message->TargetName.Buffer = (PBYTE) context->TargetName.pvBuffer; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) { message->TargetInfo.Len = (UINT16) context->ChallengeTargetInfo.cbBuffer; message->TargetInfo.Buffer = (PBYTE) context->ChallengeTargetInfo.pvBuffer; } PayloadOffset = 48; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadOffset += 8; message->TargetName.BufferOffset = PayloadOffset; message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len; /* TargetNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetName)); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ /* TargetInfoFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetInfo)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ /* Payload (variable) */ if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) ntlm_write_message_fields_buffer(s, &(message->TargetName)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) ntlm_write_message_fields_buffer(s, &(message->TargetInfo)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); #endif context->state = NTLM_STATE_AUTHENTICATE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 flags; NTLM_AV_PAIR* AvFlags; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; flags = 0; AvFlags = NULL; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKeyFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateKeyExchange = (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE; if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) || (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len)) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } PayloadBufferOffset = Stream_GetPosition(s); if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->NtChallengeResponse.Len > 0) { wStream* snt = Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len); if (!snt) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0) { Stream_Free(s, FALSE); Stream_Free(snt, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Free(snt, FALSE); context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer; context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len; sspi_SecBufferFree(&(context->ChallengeTargetInfo)); context->ChallengeTargetInfo.pvBuffer = (void*) context->NTLMv2Response.Challenge.AvPairs; context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16); CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8); AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, MsvAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); } if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKey */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->EncryptedRandomSessionKey.Len > 0) { if (message->EncryptedRandomSessionKey.Len != 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer, 16); } length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; Stream_SetPosition(s, PayloadBufferOffset); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { context->MessageIntegrityCheckOffset = (UINT32) Stream_GetPosition(s); if (Stream_GetRemainingLength(s) < 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->MessageIntegrityCheck, 16); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %"PRIu32")", context->AuthenticateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer, context->AuthenticateMessage.cbBuffer); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { WLog_DBG(TAG, "MessageIntegrityCheck:"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif if (message->UserName.Len > 0) { credentials->identity.User = (UINT16*) malloc(message->UserName.Len); if (!credentials->identity.User) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len); credentials->identity.UserLength = message->UserName.Len / 2; } if (message->DomainName.Len > 0) { credentials->identity.Domain = (UINT16*) malloc(message->DomainName.Len); if (!credentials->identity.Domain) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.Domain, message->DomainName.Buffer, message->DomainName.Len); credentials->identity.DomainLength = message->DomainName.Len / 2; } Stream_Free(s, FALSE); /* Computations beyond this point require the NTLM hash of the password */ context->state = NTLM_STATE_COMPLETION; return SEC_I_COMPLETE_NEEDED; } /** * Send NTLMSSP AUTHENTICATE_MESSAGE.\n * AUTHENTICATE_MESSAGE @msdn{cc236643} * @param NTLM context * @param buffer */ SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; } if (context->UseMIC) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (context->SendWorkstationName) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) { message->Workstation.Len = context->Workstation.Length; message->Workstation.Buffer = (BYTE*) context->Workstation.Buffer; } if (credentials->identity.DomainLength > 0) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; message->DomainName.Len = (UINT16) credentials->identity.DomainLength * 2; message->DomainName.Buffer = (BYTE*) credentials->identity.Domain; } message->UserName.Len = (UINT16) credentials->identity.UserLength * 2; message->UserName.Buffer = (BYTE*) credentials->identity.User; message->LmChallengeResponse.Len = (UINT16) context->LmChallengeResponse.cbBuffer; message->LmChallengeResponse.Buffer = (BYTE*) context->LmChallengeResponse.pvBuffer; message->NtChallengeResponse.Len = (UINT16) context->NtChallengeResponse.cbBuffer; message->NtChallengeResponse.Buffer = (BYTE*) context->NtChallengeResponse.pvBuffer; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) { message->EncryptedRandomSessionKey.Len = 16; message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey; } PayloadBufferOffset = 64; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadBufferOffset += 8; /* Version (8 bytes) */ if (context->UseMIC) PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */ message->DomainName.BufferOffset = PayloadBufferOffset; message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len; message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len; message->LmChallengeResponse.BufferOffset = message->Workstation.BufferOffset + message->Workstation.Len; message->NtChallengeResponse.BufferOffset = message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len; message->EncryptedRandomSessionKey.BufferOffset = message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_AUTHENTICATE); ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); /* Message Header (12 bytes) */ ntlm_write_message_fields(s, & (message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */ ntlm_write_message_fields(s, & (message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */ ntlm_write_message_fields(s, & (message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */ Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ if (context->UseMIC) { context->MessageIntegrityCheckOffset = (UINT32) Stream_GetPosition(s); Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */ } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */ ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */ ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */ ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ntlm_write_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */ length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; if (context->UseMIC) { /* Message Integrity Check */ ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, context->MessageIntegrityCheckOffset); Stream_Write(s, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, length); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); if (context->AuthenticateTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "AuthenticateTargetInfo (%"PRIu32"):", context->AuthenticateTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer); } ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); if (context->UseMIC) { WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif context->state = NTLM_STATE_FINAL; Stream_Free(s, FALSE); return SEC_I_COMPLETE_NEEDED; } SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context) { UINT32 flags = 0; NTLM_AV_PAIR* AvFlags = NULL; NTLM_AUTHENTICATE_MESSAGE* message; BYTE messageIntegrityCheck[16]; if (context->state != NTLM_STATE_COMPLETION) return SEC_E_OUT_OF_SEQUENCE; message = &context->AUTHENTICATE_MESSAGE; AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, MsvAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ return SEC_E_INTERNAL_ERROR; if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ return SEC_E_INTERNAL_ERROR; /* KeyExchangeKey */ ntlm_generate_key_exchange_key(context); /* EncryptedRandomSessionKey */ ntlm_decrypt_random_session_key(context); /* ExportedSessionKey */ ntlm_generate_exported_session_key(context); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { ZeroMemory(&((PBYTE) context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], 16); ntlm_compute_message_integrity_check(context, messageIntegrityCheck, sizeof(messageIntegrityCheck)); CopyMemory(&((PBYTE) context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], message->MessageIntegrityCheck, 16); if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0) { WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!"); WLog_ERR(TAG, "Expected MIC:"); winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, 16); WLog_ERR(TAG, "Actual MIC:"); winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck, 16); return SEC_E_MESSAGE_ALTERED; } } /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_FINAL; ntlm_free_message_fields_buffer(&(message->DomainName)); ntlm_free_message_fields_buffer(&(message->UserName)); ntlm_free_message_fields_buffer(&(message->Workstation)); ntlm_free_message_fields_buffer(&(message->LmChallengeResponse)); ntlm_free_message_fields_buffer(&(message->NtChallengeResponse)); ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey)); return SEC_E_OK; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_675_0
crossvul-cpp_data_bad_2726_0
/* * Copyright (c) 1998-2011 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource Public Key Infrastructure (RPKI) to Router Protocol printer */ /* specification: RFC 6810 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" static const char tstr[] = "[|RPKI-RTR]"; /* * RPKI/Router PDU header * * Here's what the PDU header looks like. * The length does include the version and length fields. */ typedef struct rpki_rtr_pdu_ { u_char version; /* Version number */ u_char pdu_type; /* PDU type */ union { u_char session_id[2]; /* Session id */ u_char error_code[2]; /* Error code */ } u; u_char length[4]; } rpki_rtr_pdu; #define RPKI_RTR_PDU_OVERHEAD (offsetof(rpki_rtr_pdu, rpki_rtr_pdu_msg)) /* * IPv4 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv4_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[4]; u_char as[4]; } rpki_rtr_pdu_ipv4_prefix; /* * IPv6 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv6_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[16]; u_char as[4]; } rpki_rtr_pdu_ipv6_prefix; /* * Error report PDU. */ typedef struct rpki_rtr_pdu_error_report_ { rpki_rtr_pdu pdu_header; u_char encapsulated_pdu_length[4]; /* Encapsulated PDU length */ } rpki_rtr_pdu_error_report; /* * PDU type codes */ #define RPKI_RTR_SERIAL_NOTIFY_PDU 0 #define RPKI_RTR_SERIAL_QUERY_PDU 1 #define RPKI_RTR_RESET_QUERY_PDU 2 #define RPKI_RTR_CACHE_RESPONSE_PDU 3 #define RPKI_RTR_IPV4_PREFIX_PDU 4 #define RPKI_RTR_IPV6_PREFIX_PDU 6 #define RPKI_RTR_END_OF_DATA_PDU 7 #define RPKI_RTR_CACHE_RESET_PDU 8 #define RPKI_RTR_ERROR_REPORT_PDU 10 static const struct tok rpki_rtr_pdu_values[] = { { RPKI_RTR_SERIAL_NOTIFY_PDU, "Serial Notify" }, { RPKI_RTR_SERIAL_QUERY_PDU, "Serial Query" }, { RPKI_RTR_RESET_QUERY_PDU, "Reset Query" }, { RPKI_RTR_CACHE_RESPONSE_PDU, "Cache Response" }, { RPKI_RTR_IPV4_PREFIX_PDU, "IPV4 Prefix" }, { RPKI_RTR_IPV6_PREFIX_PDU, "IPV6 Prefix" }, { RPKI_RTR_END_OF_DATA_PDU, "End of Data" }, { RPKI_RTR_CACHE_RESET_PDU, "Cache Reset" }, { RPKI_RTR_ERROR_REPORT_PDU, "Error Report" }, { 0, NULL} }; static const struct tok rpki_rtr_error_codes[] = { { 0, "Corrupt Data" }, { 1, "Internal Error" }, { 2, "No Data Available" }, { 3, "Invalid Request" }, { 4, "Unsupported Protocol Version" }, { 5, "Unsupported PDU Type" }, { 6, "Withdrawal of Unknown Record" }, { 7, "Duplicate Announcement Received" }, { 0, NULL} }; /* * Build a indentation string for a given indentation level. * XXX this should be really in util.c */ static char * indent_string (u_int indent) { static char buf[20]; u_int idx; idx = 0; buf[idx] = '\0'; /* * Does the static buffer fit ? */ if (sizeof(buf) < ((indent/8) + (indent %8) + 2)) { return buf; } /* * Heading newline. */ buf[idx] = '\n'; idx++; while (indent >= 8) { buf[idx] = '\t'; idx++; indent -= 8; } while (indent > 0) { buf[idx] = ' '; idx++; indent--; } /* * Trailing zero. */ buf[idx] = '\0'; return buf; } /* * Print a single PDU. */ static int rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); ND_TCHECK2(*tptr, encapsulated_pdu_length); tlen = pdu_len; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); tptr += sizeof(*pdu); tlen -= sizeof(*pdu); /* * Recurse if there is an encapsulated PDU. */ if (encapsulated_pdu_length && (encapsulated_pdu_length <= tlen)) { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); if (rpki_rtr_pdu_print(ndo, tptr, indent+2)) goto trunc; } tptr += encapsulated_pdu_length; tlen -= encapsulated_pdu_length; /* * Extract, trail-zero and print the Error message. */ text_length = 0; if (tlen > 4) { text_length = EXTRACT_32BITS(tptr); tptr += 4; tlen -= 4; } ND_TCHECK2(*tptr, text_length); if (text_length && (text_length <= tlen )) { ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return 0; trunc: return 1; } void rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2726_0
crossvul-cpp_data_good_351_11
/* * card-piv.c: Support for PIV-II from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005-2016 Douglas E. Engert <deengert@gmail.com> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "asn1.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif enum { PIV_OBJ_CCC = 0, PIV_OBJ_CHUI, /* PIV_OBJ_UCHUI is not in new with 800-73-2 */ PIV_OBJ_X509_PIV_AUTH, PIV_OBJ_CHF, PIV_OBJ_PI, PIV_OBJ_CHFI, PIV_OBJ_X509_DS, PIV_OBJ_X509_KM, PIV_OBJ_X509_CARD_AUTH, PIV_OBJ_SEC_OBJ, PIV_OBJ_DISCOVERY, PIV_OBJ_HISTORY, PIV_OBJ_RETIRED_X509_1, PIV_OBJ_RETIRED_X509_2, PIV_OBJ_RETIRED_X509_3, PIV_OBJ_RETIRED_X509_4, PIV_OBJ_RETIRED_X509_5, PIV_OBJ_RETIRED_X509_6, PIV_OBJ_RETIRED_X509_7, PIV_OBJ_RETIRED_X509_8, PIV_OBJ_RETIRED_X509_9, PIV_OBJ_RETIRED_X509_10, PIV_OBJ_RETIRED_X509_11, PIV_OBJ_RETIRED_X509_12, PIV_OBJ_RETIRED_X509_13, PIV_OBJ_RETIRED_X509_14, PIV_OBJ_RETIRED_X509_15, PIV_OBJ_RETIRED_X509_16, PIV_OBJ_RETIRED_X509_17, PIV_OBJ_RETIRED_X509_18, PIV_OBJ_RETIRED_X509_19, PIV_OBJ_RETIRED_X509_20, PIV_OBJ_IRIS_IMAGE, PIV_OBJ_9B03, PIV_OBJ_9A06, PIV_OBJ_9C06, PIV_OBJ_9D06, PIV_OBJ_9E06, PIV_OBJ_8206, PIV_OBJ_8306, PIV_OBJ_8406, PIV_OBJ_8506, PIV_OBJ_8606, PIV_OBJ_8706, PIV_OBJ_8806, PIV_OBJ_8906, PIV_OBJ_8A06, PIV_OBJ_8B06, PIV_OBJ_8C06, PIV_OBJ_8D06, PIV_OBJ_8E06, PIV_OBJ_8F06, PIV_OBJ_9006, PIV_OBJ_9106, PIV_OBJ_9206, PIV_OBJ_9306, PIV_OBJ_9406, PIV_OBJ_9506, PIV_OBJ_LAST_ENUM }; /* * Flags in the piv_obj_cache: * PIV_OBJ_CACHE_VALID means the data in the cache can be used. * It might have zero length indicating that the object was not found. * PIV_OBJ_CACHE_NOT_PRESENT means do not even try to read the object. * These objects will only be present if the history object says * they are on the card, or the discovery or history object in not present. * If the file lilsted in the history object offCardCertURL was found, * its certs will be read into the cache and PIV_OBJ_CACHE_VALID set * and PIV_OBJ_CACHE_NOT_PRESENT unset. */ #define PIV_OBJ_CACHE_VALID 1 #define PIV_OBJ_CACHE_NOT_PRESENT 8 typedef struct piv_obj_cache { u8* obj_data; size_t obj_len; u8* internal_obj_data; /* like a cert in the object */ size_t internal_obj_len; int flags; } piv_obj_cache_t; enum { PIV_STATE_NORMAL = 0, PIV_STATE_MATCH, PIV_STATE_INIT }; typedef struct piv_private_data { sc_file_t *aid_file; int enumtag; int selected_obj; /* The index into the piv_objects last selected */ int return_only_cert; /* return the cert from the object */ int rwb_state; /* first time -1, 0, in middle, 1 at eof */ int operation; /* saved from set_security_env */ int algorithm; /* saved from set_security_env */ int key_ref; /* saved from set_security_env and */ int alg_id; /* used in decrypt, signature, derive */ int key_size; /* RSA: modulus_bits EC: field_length in bits */ u8* w_buf; /* write_binary buffer */ size_t w_buf_len; /* length of w_buff */ piv_obj_cache_t obj_cache[PIV_OBJ_LAST_ENUM]; int keysWithOnCardCerts; int keysWithOffCardCerts; char * offCardCertURL; int pin_preference; /* set from Discovery object */ int logged_in; int pstate; int pin_cmd_verify; int context_specific; int pin_cmd_noparse; unsigned int pin_cmd_verify_sw1; unsigned int pin_cmd_verify_sw2; int tries_left; /* SC_PIN_CMD_GET_INFO tries_left from last */ unsigned int card_issues; /* card_issues flags for this card */ int object_test_verify; /* Can test this object to set verification state of card */ int yubico_version; /* 3 byte version number of NEO or Yubikey4 as integer */ } piv_private_data_t; #define PIV_DATA(card) ((piv_private_data_t*)card->drv_data) struct piv_aid { int enumtag; size_t len_short; /* min length without version */ size_t len_long; /* With version and other stuff */ u8 *value; }; /* * The Generic entry should be the "A0 00 00 03 08 00 00 10 00 " * NIST published this on 10/6/2005 * 800-73-2 Part 1 now refers to version "02 00" * i.e. "A0 00 00 03 08 00 00 01 00 02 00". * but we don't need the version number. but could get it from the PIX. * * 800-73-3 Part 1 now refers to "01 00" i.e. going back to 800-73-1. * The main differences between 73-1, and 73-3 are the addition of the * key History object and keys, as well as Discovery and Iris objects. * These can be discovered by trying GET DATA */ /* all have same AID */ static struct piv_aid piv_aids[] = { {SC_CARD_TYPE_PIV_II_GENERIC, /* TODO not really card type but what PIV AID is supported */ 9, 9, (u8 *) "\xA0\x00\x00\x03\x08\x00\x00\x10\x00" }, {0, 9, 0, NULL } }; /* card_issues - bugs in PIV implementations requires special handling */ #define CI_VERIFY_630X 0x00000001U /* VERIFY tries left returns 630X rather then 63CX */ #define CI_VERIFY_LC0_FAIL 0x00000002U /* VERIFY Lc=0 never returns 90 00 if PIN not needed */ /* will also test after first PIN verify if protected object can be used instead */ #define CI_CANT_USE_GETDATA_FOR_STATE 0x00000008U /* No object to test verification inplace of VERIFY Lc=0 */ #define CI_LEAKS_FILE_NOT_FOUND 0x00000010U /* GET DATA of empty object returns 6A 82 even if PIN not verified */ #define CI_DISCOVERY_USELESS 0x00000020U /* Discovery can not be used to query active AID */ #define CI_PIV_AID_LOSE_STATE 0x00000040U /* PIV AID can lose the login state run with out it*/ #define CI_OTHER_AID_LOSE_STATE 0x00000100U /* Other drivers match routines may reset our security state and lose AID!!! */ #define CI_NFC_EXPOSE_TOO_MUCH 0x00000200U /* PIN, crypto and objects exposed over NFS in violation of 800-73-3 */ #define CI_NO_RSA2048 0x00010000U /* does not have RSA 2048 */ #define CI_NO_EC384 0x00020000U /* does not have EC 384 */ /* * Flags in the piv_object: * PIV_OBJECT_NOT_PRESENT: the presents of the object is * indicated by the History object. */ #define PIV_OBJECT_TYPE_CERT 1 #define PIV_OBJECT_TYPE_PUBKEY 2 #define PIV_OBJECT_NOT_PRESENT 4 struct piv_object { int enumtag; const char * name; const char * oidstring; size_t tag_len; u8 tag_value[3]; u8 containerid[2]; /* will use as relative paths for simulation */ int flags; /* object has some internal object like a cert */ }; /* Must be in order, and one per enumerated PIV_OBJ */ static const struct piv_object piv_objects[] = { { PIV_OBJ_CCC, "Card Capability Container", "2.16.840.1.101.3.7.1.219.0", 3, "\x5F\xC1\x07", "\xDB\x00", 0}, { PIV_OBJ_CHUI, "Card Holder Unique Identifier", "2.16.840.1.101.3.7.2.48.0", 3, "\x5F\xC1\x02", "\x30\x00", 0}, { PIV_OBJ_X509_PIV_AUTH, "X.509 Certificate for PIV Authentication", "2.16.840.1.101.3.7.2.1.1", 3, "\x5F\xC1\x05", "\x01\x01", PIV_OBJECT_TYPE_CERT} , { PIV_OBJ_CHF, "Card Holder Fingerprints", "2.16.840.1.101.3.7.2.96.16", 3, "\x5F\xC1\x03", "\x60\x10", 0}, { PIV_OBJ_PI, "Printed Information", "2.16.840.1.101.3.7.2.48.1", 3, "\x5F\xC1\x09", "\x30\x01", 0}, { PIV_OBJ_CHFI, "Cardholder Facial Images", "2.16.840.1.101.3.7.2.96.48", 3, "\x5F\xC1\x08", "\x60\x30", 0}, { PIV_OBJ_X509_DS, "X.509 Certificate for Digital Signature", "2.16.840.1.101.3.7.2.1.0", 3, "\x5F\xC1\x0A", "\x01\x00", PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_X509_KM, "X.509 Certificate for Key Management", "2.16.840.1.101.3.7.2.1.2", 3, "\x5F\xC1\x0B", "\x01\x02", PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_X509_CARD_AUTH, "X.509 Certificate for Card Authentication", "2.16.840.1.101.3.7.2.5.0", 3, "\x5F\xC1\x01", "\x05\x00", PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_SEC_OBJ, "Security Object", "2.16.840.1.101.3.7.2.144.0", 3, "\x5F\xC1\x06", "\x90\x00", 0}, { PIV_OBJ_DISCOVERY, "Discovery Object", "2.16.840.1.101.3.7.2.96.80", 1, "\x7E", "\x60\x50", 0}, { PIV_OBJ_HISTORY, "Key History Object", "2.16.840.1.101.3.7.2.96.96", 3, "\x5F\xC1\x0C", "\x60\x60", 0}, /* 800-73-3, 21 new objects, 20 history certificates */ { PIV_OBJ_RETIRED_X509_1, "Retired X.509 Certificate for Key Management 1", "2.16.840.1.101.3.7.2.16.1", 3, "\x5F\xC1\x0D", "\x10\x01", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_2, "Retired X.509 Certificate for Key Management 2", "2.16.840.1.101.3.7.2.16.2", 3, "\x5F\xC1\x0E", "\x10\x02", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_3, "Retired X.509 Certificate for Key Management 3", "2.16.840.1.101.3.7.2.16.3", 3, "\x5F\xC1\x0F", "\x10\x03", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_4, "Retired X.509 Certificate for Key Management 4", "2.16.840.1.101.3.7.2.16.4", 3, "\x5F\xC1\x10", "\x10\x04", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_5, "Retired X.509 Certificate for Key Management 5", "2.16.840.1.101.3.7.2.16.5", 3, "\x5F\xC1\x11", "\x10\x05", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_6, "Retired X.509 Certificate for Key Management 6", "2.16.840.1.101.3.7.2.16.6", 3, "\x5F\xC1\x12", "\x10\x06", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_7, "Retired X.509 Certificate for Key Management 7", "2.16.840.1.101.3.7.2.16.7", 3, "\x5F\xC1\x13", "\x10\x07", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_8, "Retired X.509 Certificate for Key Management 8", "2.16.840.1.101.3.7.2.16.8", 3, "\x5F\xC1\x14", "\x10\x08", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_9, "Retired X.509 Certificate for Key Management 9", "2.16.840.1.101.3.7.2.16.9", 3, "\x5F\xC1\x15", "\x10\x09", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_10, "Retired X.509 Certificate for Key Management 10", "2.16.840.1.101.3.7.2.16.10", 3, "\x5F\xC1\x16", "\x10\x0A", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_11, "Retired X.509 Certificate for Key Management 11", "2.16.840.1.101.3.7.2.16.11", 3, "\x5F\xC1\x17", "\x10\x0B", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_12, "Retired X.509 Certificate for Key Management 12", "2.16.840.1.101.3.7.2.16.12", 3, "\x5F\xC1\x18", "\x10\x0C", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_13, "Retired X.509 Certificate for Key Management 13", "2.16.840.1.101.3.7.2.16.13", 3, "\x5F\xC1\x19", "\x10\x0D", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_14, "Retired X.509 Certificate for Key Management 14", "2.16.840.1.101.3.7.2.16.14", 3, "\x5F\xC1\x1A", "\x10\x0E", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_15, "Retired X.509 Certificate for Key Management 15", "2.16.840.1.101.3.7.2.16.15", 3, "\x5F\xC1\x1B", "\x10\x0F", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_16, "Retired X.509 Certificate for Key Management 16", "2.16.840.1.101.3.7.2.16.16", 3, "\x5F\xC1\x1C", "\x10\x10", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_17, "Retired X.509 Certificate for Key Management 17", "2.16.840.1.101.3.7.2.16.17", 3, "\x5F\xC1\x1D", "\x10\x11", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_18, "Retired X.509 Certificate for Key Management 18", "2.16.840.1.101.3.7.2.16.18", 3, "\x5F\xC1\x1E", "\x10\x12", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_19, "Retired X.509 Certificate for Key Management 19", "2.16.840.1.101.3.7.2.16.19", 3, "\x5F\xC1\x1F", "\x10\x13", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_RETIRED_X509_20, "Retired X.509 Certificate for Key Management 20", "2.16.840.1.101.3.7.2.16.20", 3, "\x5F\xC1\x20", "\x10\x14", PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT}, { PIV_OBJ_IRIS_IMAGE, "Cardholder Iris Images", "2.16.840.1.101.3.7.2.16.21", 3, "\x5F\xC1\x21", "\x10\x15", 0}, /* following not standard , to be used by piv-tool only for testing */ { PIV_OBJ_9B03, "3DES-ECB ADM", "2.16.840.1.101.3.7.2.9999.3", 2, "\x9B\x03", "\x9B\x03", 0}, /* Only used when signing a cert req, usually from engine * after piv-tool generated the key and saved the pub key * to a file. Note RSA key can be 1024, 2048 or 3072 * but still use the "9x06" name. */ { PIV_OBJ_9A06, "RSA 9A Pub key from last genkey", "2.16.840.1.101.3.7.2.9999.20", 2, "\x9A\x06", "\x9A\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9C06, "Pub 9C key from last genkey", "2.16.840.1.101.3.7.2.9999.21", 2, "\x9C\x06", "\x9C\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9D06, "Pub 9D key from last genkey", "2.16.840.1.101.3.7.2.9999.22", 2, "\x9D\x06", "\x9D\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9E06, "Pub 9E key from last genkey", "2.16.840.1.101.3.7.2.9999.23", 2, "\x9E\x06", "\x9E\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8206, "Pub 82 key ", "2.16.840.1.101.3.7.2.9999.101", 2, "\x82\x06", "\x82\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8306, "Pub 83 key ", "2.16.840.1.101.3.7.2.9999.102", 2, "\x83\x06", "\x83\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8406, "Pub 84 key ", "2.16.840.1.101.3.7.2.9999.103", 2, "\x84\x06", "\x84\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8506, "Pub 85 key ", "2.16.840.1.101.3.7.2.9999.104", 2, "\x85\x06", "\x85\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8606, "Pub 86 key ", "2.16.840.1.101.3.7.2.9999.105", 2, "\x86\x06", "\x86\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8706, "Pub 87 key ", "2.16.840.1.101.3.7.2.9999.106", 2, "\x87\x06", "\x87\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8806, "Pub 88 key ", "2.16.840.1.101.3.7.2.9999.107", 2, "\x88\x06", "\x88\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8906, "Pub 89 key ", "2.16.840.1.101.3.7.2.9999.108", 2, "\x89\x06", "\x89\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8A06, "Pub 8A key ", "2.16.840.1.101.3.7.2.9999.109", 2, "\x8A\x06", "\x8A\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8B06, "Pub 8B key ", "2.16.840.1.101.3.7.2.9999.110", 2, "\x8B\x06", "\x8B\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8C06, "Pub 8C key ", "2.16.840.1.101.3.7.2.9999.111", 2, "\x8C\x06", "\x8C\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8D06, "Pub 8D key ", "2.16.840.1.101.3.7.2.9999.112", 2, "\x8D\x06", "\x8D\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8E06, "Pub 8E key ", "2.16.840.1.101.3.7.2.9999.113", 2, "\x8E\x06", "\x8E\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_8F06, "Pub 8F key ", "2.16.840.1.101.3.7.2.9999.114", 2, "\x8F\x06", "\x8F\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9006, "Pub 90 key ", "2.16.840.1.101.3.7.2.9999.115", 2, "\x90\x06", "\x90\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9106, "Pub 91 key ", "2.16.840.1.101.3.7.2.9999.116", 2, "\x91\x06", "\x91\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9206, "Pub 92 key ", "2.16.840.1.101.3.7.2.9999.117", 2, "\x92\x06", "\x92\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9306, "Pub 93 key ", "2.16.840.1.101.3.7.2.9999.118", 2, "\x93\x06", "\x93\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9406, "Pub 94 key ", "2.16.840.1.101.3.7.2.9999.119", 2, "\x94\x06", "\x94\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_9506, "Pub 95 key ", "2.16.840.1.101.3.7.2.9999.120", 2, "\x95\x06", "\x95\x06", PIV_OBJECT_TYPE_PUBKEY}, { PIV_OBJ_LAST_ENUM, "", "", 0, "", "", 0} }; static struct sc_card_operations piv_ops; static struct sc_card_driver piv_drv = { "Personal Identity Verification Card", "PIV-II", &piv_ops, NULL, 0, NULL }; static int piv_match_card_continued(sc_card_t *card); static int piv_find_obj_by_containerid(sc_card_t *card, const u8 * str) { int i; LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "str=0x%02X%02X\n", str[0], str[1]); for (i = 0; piv_objects[i].enumtag < PIV_OBJ_LAST_ENUM; i++) { if ( str[0] == piv_objects[i].containerid[0] && str[1] == piv_objects[i].containerid[1]) LOG_FUNC_RETURN(card->ctx, i); } LOG_FUNC_RETURN(card->ctx, -1); } /* * If ptr == NULL, just return the size of the tag and length and data * otherwise, store tag and length at **ptr, and increment */ static size_t put_tag_and_len(unsigned int tag, size_t len, u8 **ptr) { int i; u8 *p; if (len < 128) { i = 2; } else if (len < 256) { i = 3; } else { i = 4; } if (ptr) { p = *ptr; *p++ = (u8)tag; switch (i) { case 2: *p++ = len; break; case 3: *p++ = 0x81; *p++ = len; break; case 4: *p++ = 0x82; *p++ = (u8) (len >> 8); *p++ = (u8) (len & 0xff); break; } *ptr = p; } else { i += len; } return i; } /* * Send a command and receive data. There is always something to send. * Used by GET DATA, PUT DATA, GENERAL AUTHENTICATE * and GENERATE ASYMMETRIC KEY PAIR. * GET DATA may call to get the first 128 bytes to get the length from the tag. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. */ static int piv_general_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[4096]; u8 *rbuf; size_t rbuflen; unsigned int cla_out, tag_out; const u8 *body; size_t bodylen; int find_len = 0; piv_private_data_t * priv = PIV_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } r = sc_lock(card); if (r != SC_SUCCESS) LOG_FUNC_RETURN(card->ctx, r); sc_format_apdu(card, &apdu, recvbuf ? SC_APDU_CASE_4_SHORT: SC_APDU_CASE_3_SHORT, ins, p1, p2); apdu.flags |= SC_APDU_FLAGS_CHAINING; /* if looking for length of object, dont try and read the rest of buffer here */ if (rbuflen == 8 && card->reader->active_protocol == SC_PROTO_T1) { apdu.flags |= SC_APDU_FLAGS_NO_GET_RESP; find_len = 1; } apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 256) ? 256 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_log(card->ctx, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_log(card->ctx, "DEE r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_log(card->ctx, "Transmit failed"); goto err; } if (!(find_len && apdu.sw1 == 0x61)) r = sc_check_sw(card, apdu.sw1, apdu.sw2); /* TODO: - DEE look later at tag vs size read too */ if (r < 0) { sc_log(card->ctx, "Card returned error "); goto err; } /* * See how much we read and make sure it is asn1 * if not, return 0 indicating no data found */ rbuflen = 0; /* in case rseplen < 3 i.e. not parseable */ /* we may only be using get data to test the security status of the card, so zero length is OK */ if ( recvbuflen && recvbuf && apdu.resplen > 3 && priv->pin_cmd_noparse != 1) { *recvbuflen = 0; /* we should have all the tag data, so we have to tell sc_asn1_find_tag * the buffer is bigger, so it will not produce "ASN1.tag too long!" */ body = rbuf; if (sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || body == NULL) { /* only early beta cards had this problem */ sc_log(card->ctx, "***** received buffer tag MISSING "); body = rbuf; /* some readers/cards might return 6c 00 */ if (apdu.sw1 == 0x61 || apdu.sw2 == 0x6c ) bodylen = 12000; else bodylen = apdu.resplen; } rbuflen = body - rbuf + bodylen; /* if using internal buffer, alloc new one */ if (rbuf == rbufinitbuf) { *recvbuf = malloc(rbuflen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, rbuflen); /* copy tag too */ } } if (recvbuflen) { *recvbuflen = rbuflen; r = *recvbuflen; } err: sc_unlock(card); LOG_FUNC_RETURN(card->ctx, r); } /* Add the PIV-II operations */ /* Should use our own keydata, actually should be common to all cards */ /* RSA and EC are added. */ static int piv_generate_key(sc_card_t *card, sc_cardctl_piv_genkey_info_t *keydata) { int r; u8 *rbuf = NULL; size_t rbuflen = 0; u8 *p; const u8 *tag; u8 tagbuf[16]; u8 outdata[3]; /* we could also add tag 81 for exponent */ size_t taglen, i; size_t out_len; size_t in_len; unsigned int cla_out, tag_out; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); keydata->exponent = 0; keydata->pubkey = NULL; keydata->pubkey_len = 0; keydata->ecparam = NULL; /* will show size as we only support 2 curves */ keydata->ecparam_len = 0; keydata->ecpoint = NULL; keydata->ecpoint_len = 0; out_len = 3; outdata[0] = 0x80; outdata[1] = 0x01; outdata[2] = keydata->key_algid; switch (keydata->key_algid) { case 0x05: keydata->key_bits = 3072; break; case 0x06: keydata->key_bits = 1024; break; case 0x07: keydata->key_bits = 2048; break; /* TODO: - DEE For EC, also set the curve parameter as the OID */ case 0x11: keydata->key_bits = 0; keydata->ecparam =0; /* we only support prime256v1 for 11 */ keydata->ecparam_len =0; break; case 0x14: keydata->key_bits = 0; keydata->ecparam = 0; /* we only support secp384r1 */ keydata->ecparam_len = 0; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } p = tagbuf; put_tag_and_len(0xAC, out_len, &p); memcpy(p, outdata, out_len); p+=out_len; r = piv_general_io(card, 0x47, 0x00, keydata->key_num, tagbuf, p - tagbuf, &rbuf, &rbuflen); if (r >= 0) { const u8 *cp; keydata->exponent = 0; /* expected tag is 7f49. */ /* we will whatever tag is present */ cp = rbuf; in_len = rbuflen; r = sc_asn1_read_tag(&cp, rbuflen, &cla_out, &tag_out, &in_len); if (cp == NULL) { r = SC_ERROR_ASN1_OBJECT_NOT_FOUND; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Tag buffer not found"); goto err; } /* if RSA vs EC */ if (keydata->key_bits > 0 ) { tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x82, &taglen); if (tag != NULL && taglen <= 4) { keydata->exponent = 0; for (i = 0; i < taglen;i++) keydata->exponent = (keydata->exponent<<8) + tag[i]; } tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x81, &taglen); if (tag != NULL && taglen > 0) { keydata->pubkey = malloc(taglen); if (keydata->pubkey == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); keydata->pubkey_len = taglen; memcpy (keydata->pubkey, tag, taglen); } } else { /* must be EC */ tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x86, &taglen); if (tag != NULL && taglen > 0) { keydata->ecpoint = malloc(taglen); if (keydata->ecpoint == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); keydata->ecpoint_len = taglen; memcpy (keydata->ecpoint, tag, taglen); } } /* TODO: -DEE Could add key to cache so could use engine to generate key, * and sign req in single operation */ r = 0; } err: if (rbuf) free(rbuf); LOG_FUNC_RETURN(card->ctx, r); } static int piv_select_aid(sc_card_t* card, u8* aid, size_t aidlen, u8* response, size_t *responselen) { sc_apdu_t apdu; int r; LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "Got args: aid=%p, aidlen=%"SC_FORMAT_LEN_SIZE_T"u, response=%p, responselen=%"SC_FORMAT_LEN_SIZE_T"u", aid, aidlen, response, responselen ? *responselen : 0); sc_format_apdu(card, &apdu, response == NULL ? SC_APDU_CASE_3_SHORT : SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00); apdu.lc = aidlen; apdu.data = aid; apdu.datalen = aidlen; apdu.resp = response; apdu.resplen = responselen ? *responselen : 0; apdu.le = response == NULL ? 0 : 256; /* could be 21 for fci */ r = sc_transmit_apdu(card, &apdu); if (responselen) *responselen = apdu.resplen; LOG_TEST_RET(card->ctx, r, "PIV select failed"); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* find the PIV AID on the card. If card->type already filled in, * then look for specific AID only * Assumes that priv may not be present */ static int piv_find_aid(sc_card_t * card, sc_file_t *aid_file) { sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; int r,i; const u8 *tag; size_t taglen; const u8 *pix; size_t pixlen; size_t resplen = sizeof(rbuf); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* first see if the default application will return a template * that we know about. */ r = piv_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, rbuf, &resplen); if (r >= 0 && resplen > 2 ) { tag = sc_asn1_find_tag(card->ctx, rbuf, resplen, 0x61, &taglen); if (tag != NULL) { pix = sc_asn1_find_tag(card->ctx, tag, taglen, 0x4F, &pixlen); if (pix != NULL ) { sc_log(card->ctx, "found PIX"); /* early cards returned full AID, rather then just the pix */ for (i = 0; piv_aids[i].len_long != 0; i++) { if ((pixlen >= 6 && memcmp(pix, piv_aids[i].value + 5, piv_aids[i].len_long - 5 ) == 0) || ((pixlen >= piv_aids[i].len_short && memcmp(pix, piv_aids[i].value, piv_aids[i].len_short) == 0))) { if (card->type > SC_CARD_TYPE_PIV_II_BASE && card->type < SC_CARD_TYPE_PIV_II_BASE+1000 && card->type == piv_aids[i].enumtag) { LOG_FUNC_RETURN(card->ctx, i); } else { LOG_FUNC_RETURN(card->ctx, i); } } } } } } /* for testing, we can force the use of a specific AID * by using the card= parameter in conf file */ for (i = 0; piv_aids[i].len_long != 0; i++) { if (card->type > SC_CARD_TYPE_PIV_II_BASE && card->type < SC_CARD_TYPE_PIV_II_BASE+1000 && card->type != piv_aids[i].enumtag) { continue; } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00); apdu.lc = piv_aids[i].len_long; apdu.data = piv_aids[i].value; apdu.datalen = apdu.lc; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { if (card->type != 0 && card->type == piv_aids[i].enumtag) LOG_FUNC_RETURN(card->ctx, (r < 0)? r: i); continue; } if ( apdu.resplen == 0 && r == 0) { /* could be the MSU card */ continue; /* other cards will return a FCI */ } if (apdu.resp[0] != 0x6f || apdu.resp[1] > apdu.resplen - 2 ) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT); card->ops->process_fci(card, aid_file, apdu.resp+2, apdu.resp[1]); LOG_FUNC_RETURN(card->ctx, i); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT); } /* * Read a DER encoded object from a file. Allocate and return the buf. * Used to read the file defined in offCardCertURL from a cache. * Also used for testing of History and Discovery objects from a file * when testing with a card that does not support these new objects. */ static int piv_read_obj_from_file(sc_card_t * card, char * filename, u8 **buf, size_t *buf_len) { int r; int f = -1; size_t len; u8 tagbuf[16]; size_t rbuflen; const u8 * body; unsigned int cla_out, tag_out; size_t bodylen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); *buf = NULL; *buf_len = 0; f = open(filename, O_RDONLY); if (f < 0) { sc_log(card->ctx, "Unable to load PIV off card file: \"%s\"",filename); r = SC_ERROR_FILE_NOT_FOUND; goto err; } len = read(f, tagbuf, sizeof(tagbuf)); /* get tag and length */ if (len < 2 || len > sizeof(tagbuf)) { sc_log(card->ctx, "Problem with \"%s\"",filename); r = SC_ERROR_DATA_OBJECT_NOT_FOUND; goto err; } body = tagbuf; if (sc_asn1_read_tag(&body, 0xfffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || body == NULL) { sc_log(card->ctx, "DER problem"); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } rbuflen = body - tagbuf + bodylen; *buf = malloc(rbuflen); if (!*buf) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*buf, tagbuf, len); /* copy first or only part */ if (rbuflen > len + sizeof(tagbuf)) { len = read(f, *buf + sizeof(tagbuf), rbuflen - sizeof(tagbuf)); /* read rest */ if (len != rbuflen - sizeof(tagbuf)) { r = SC_ERROR_INVALID_ASN1_OBJECT; free (*buf); *buf = NULL; goto err; } } r = rbuflen; *buf_len = rbuflen; err: if (f >= 0) close(f); LOG_FUNC_RETURN(card->ctx, r); } /* the tag is the PIV_OBJ_* */ static int piv_get_data(sc_card_t * card, int enumtag, u8 **buf, size_t *buf_len) { u8 *p; int r = 0; u8 tagbuf[8]; size_t tag_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "#%d", enumtag); sc_lock(card); /* do check len and get data in same transaction */ /* assert(enumtag >= 0 && enumtag < PIV_OBJ_LAST_ENUM); */ tag_len = piv_objects[enumtag].tag_len; p = tagbuf; put_tag_and_len(0x5c, tag_len, &p); memcpy(p, piv_objects[enumtag].tag_value, tag_len); p += tag_len; if (*buf_len == 1 && *buf == NULL) { /* we need to get the length */ u8 rbufinitbuf[8]; /* tag of 53 with 82 xx xx will fit in 4 */ u8 *rbuf; size_t rbuflen; size_t bodylen; unsigned int cla_out, tag_out; const u8 *body; sc_log(card->ctx, "get len of #%d", enumtag); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); r = piv_general_io(card, 0xCB, 0x3F, 0xFF, tagbuf, p - tagbuf, &rbuf, &rbuflen); if (r > 0) { body = rbuf; if (sc_asn1_read_tag(&body, 0xffff, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || body == NULL) { sc_log(card->ctx, "***** received buffer tag MISSING "); r = SC_ERROR_FILE_NOT_FOUND; goto err; } *buf_len = r; } else if ( r == 0 ) { r = SC_ERROR_FILE_NOT_FOUND; goto err; } else { goto err; } } sc_log(card->ctx, "buffer for #%d *buf=0x%p len=%"SC_FORMAT_LEN_SIZE_T"u", enumtag, *buf, *buf_len); if (*buf == NULL && *buf_len > 0) { *buf = malloc(*buf_len); if (*buf == NULL ) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } } r = piv_general_io(card, 0xCB, 0x3F, 0xFF, tagbuf, p - tagbuf, buf, buf_len); err: sc_unlock(card); LOG_FUNC_RETURN(card->ctx, r); } static int piv_get_cached_data(sc_card_t * card, int enumtag, u8 **buf, size_t *buf_len) { piv_private_data_t * priv = PIV_DATA(card); int r; u8 *rbuf = NULL; size_t rbuflen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "#%d", enumtag); assert(enumtag >= 0 && enumtag < PIV_OBJ_LAST_ENUM); /* see if we have it cached */ if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) { sc_log(card->ctx, "found #%d %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u", enumtag, priv->obj_cache[enumtag].obj_data, priv->obj_cache[enumtag].obj_len, priv->obj_cache[enumtag].internal_obj_data, priv->obj_cache[enumtag].internal_obj_len); if (priv->obj_cache[enumtag].obj_len == 0) { r = SC_ERROR_FILE_NOT_FOUND; sc_log(card->ctx, "#%d found but len=0", enumtag); goto err; } *buf = priv->obj_cache[enumtag].obj_data; *buf_len = priv->obj_cache[enumtag].obj_len; r = *buf_len; goto ok; } /* * If we know it can not be on the card i.e. History object * has been read, and we know what other certs may or * may not be on the card. We can avoid extra overhead */ if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT) { sc_log(card->ctx, "no_obj #%d", enumtag); r = SC_ERROR_FILE_NOT_FOUND; goto err; } /* Not cached, try to get it, piv_get_data will allocate a buf */ sc_log(card->ctx, "get #%d", enumtag); rbuflen = 1; r = piv_get_data(card, enumtag, &rbuf, &rbuflen); if (r > 0) { priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID; priv->obj_cache[enumtag].obj_len = r; priv->obj_cache[enumtag].obj_data = rbuf; *buf = rbuf; *buf_len = r; sc_log(card->ctx, "added #%d %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u", enumtag, priv->obj_cache[enumtag].obj_data, priv->obj_cache[enumtag].obj_len, priv->obj_cache[enumtag].internal_obj_data, priv->obj_cache[enumtag].internal_obj_len); } else if (r == 0 || r == SC_ERROR_FILE_NOT_FOUND) { r = SC_ERROR_FILE_NOT_FOUND; priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID; priv->obj_cache[enumtag].obj_len = 0; } else if ( r < 0) { goto err; } ok: err: LOG_FUNC_RETURN(card->ctx, r); } static int piv_cache_internal_data(sc_card_t *card, int enumtag) { piv_private_data_t * priv = PIV_DATA(card); const u8* tag; const u8* body; size_t taglen; size_t bodylen; int compressed = 0; /* if already cached */ if (priv->obj_cache[enumtag].internal_obj_data && priv->obj_cache[enumtag].internal_obj_len) { sc_log(card->ctx, "#%d found internal %p:%"SC_FORMAT_LEN_SIZE_T"u", enumtag, priv->obj_cache[enumtag].internal_obj_data, priv->obj_cache[enumtag].internal_obj_len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } body = sc_asn1_find_tag(card->ctx, priv->obj_cache[enumtag].obj_data, priv->obj_cache[enumtag].obj_len, 0x53, &bodylen); if (body == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID); /* get the certificate out */ if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_CERT) { tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x71, &taglen); /* 800-72-1 not clear if this is 80 or 01 Sent comment to NIST for 800-72-2 */ /* 800-73-3 says it is 01, keep dual test so old cards still work */ if (tag && (((*tag) & 0x80) || ((*tag) & 0x01))) compressed = 1; tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x70, &taglen); if (tag == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID); if (taglen == 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND); if(compressed) { #ifdef ENABLE_ZLIB size_t len; u8* newBuf = NULL; if(SC_SUCCESS != sc_decompress_alloc(&newBuf, &len, tag, taglen, COMPRESSION_AUTO)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID); priv->obj_cache[enumtag].internal_obj_data = newBuf; priv->obj_cache[enumtag].internal_obj_len = len; #else sc_log(card->ctx, "PIV compression not supported, no zlib"); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); #endif } else { if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen))) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen); priv->obj_cache[enumtag].internal_obj_len = taglen; } /* convert pub key to internal */ /* TODO: -DEE need to fix ... would only be used if we cache the pub key, but we don't today */ } else if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) { tag = sc_asn1_find_tag(card->ctx, body, bodylen, *body, &taglen); if (tag == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID); if (taglen == 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND); if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen))) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen); priv->obj_cache[enumtag].internal_obj_len = taglen; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } sc_log(card->ctx, "added #%d internal %p:%"SC_FORMAT_LEN_SIZE_T"u", enumtag, priv->obj_cache[enumtag].internal_obj_data, priv->obj_cache[enumtag].internal_obj_len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int piv_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { piv_private_data_t * priv = PIV_DATA(card); int enumtag; int r; u8 *rbuf = NULL; size_t rbuflen = 0; const u8 *body; size_t bodylen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv->selected_obj < 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); enumtag = piv_objects[priv->selected_obj].enumtag; if (priv->rwb_state == -1) { r = piv_get_cached_data(card, enumtag, &rbuf, &rbuflen); if (r >=0) { /* an object with no data will be considered not found */ /* Discovery tag = 0x73, all others are 0x53 */ if (!rbuf || rbuf[0] == 0x00 || ((rbuf[0]&0xDF) == 0x53 && rbuf[1] == 0x00)) { r = SC_ERROR_FILE_NOT_FOUND; goto err; } sc_log(card->ctx, "DEE rbuf=%p,rbuflen=%"SC_FORMAT_LEN_SIZE_T"u,", rbuf, rbuflen); body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, rbuf[0], &bodylen); if (body == NULL) { /* if missing, assume its the body */ /* DEE bug in the beta card */ sc_log(card->ctx, " ***** tag 0x53 MISSING"); r = SC_ERROR_INVALID_DATA; goto err; } if (bodylen > body - rbuf + rbuflen) { sc_log(card->ctx, " ***** tag length > then data: %"SC_FORMAT_LEN_SIZE_T"u>%"SC_FORMAT_LEN_PTRDIFF_T"u+%"SC_FORMAT_LEN_SIZE_T"u", bodylen, body - rbuf, rbuflen); r = SC_ERROR_INVALID_DATA; goto err; } /* if cached obj has internal interesting data (cert or pub key) */ if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) { r = piv_cache_internal_data(card, enumtag); if (r < 0) goto err; } } priv->rwb_state = 0; } if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) { rbuf = priv->obj_cache[enumtag].internal_obj_data; rbuflen = priv->obj_cache[enumtag].internal_obj_len; } else { rbuf = priv->obj_cache[enumtag].obj_data; rbuflen = priv->obj_cache[enumtag].obj_len; } /* rbuf rbuflen has pointer and length to cached data */ if ( rbuflen < idx + count) count = rbuflen - idx; if (count <= 0) { r = 0; priv->rwb_state = 1; } else { memcpy(buf, rbuf + idx, count); r = count; } err: LOG_FUNC_RETURN(card->ctx, r); } /* * the tag is the PIV_OBJ_* * The buf should have the 0x53 tag+len+tags and data */ static int piv_put_data(sc_card_t *card, int tag, const u8 *buf, size_t buf_len) { int r; u8 * sbuf; size_t sbuflen; u8 * p; size_t tag_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); tag_len = piv_objects[tag].tag_len; sbuflen = put_tag_and_len(0x5c, tag_len, NULL) + buf_len; if (!(sbuf = malloc(sbuflen))) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); p = sbuf; put_tag_and_len(0x5c, tag_len, &p); memcpy(p, piv_objects[tag].tag_value, tag_len); p += tag_len; memcpy(p, buf, buf_len); p += buf_len; r = piv_general_io(card, 0xDB, 0x3F, 0xFF, sbuf, p - sbuf, NULL, NULL); if (sbuf) free(sbuf); LOG_FUNC_RETURN(card->ctx, r); } static int piv_write_certificate(sc_card_t *card, const u8* buf, size_t count, unsigned long flags) { piv_private_data_t * priv = PIV_DATA(card); int enumtag; int r = SC_SUCCESS; u8 *sbuf = NULL; u8 *p; size_t sbuflen; size_t taglen; sc_log(card->ctx, "DEE cert len=%"SC_FORMAT_LEN_SIZE_T"u", count); taglen = put_tag_and_len(0x70, count, NULL) + put_tag_and_len(0x71, 1, NULL) + put_tag_and_len(0xFE, 0, NULL); sbuflen = put_tag_and_len(0x53, taglen, NULL); sbuf = malloc(sbuflen); if (sbuf == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); p = sbuf; put_tag_and_len(0x53, taglen, &p); put_tag_and_len(0x70, count, &p); memcpy(p, buf, count); p += count; put_tag_and_len(0x71, 1, &p); /* Use 01 as per NIST 800-73-3 */ *p++ = (flags)? 0x01:0x00; /* certinfo, i.e. gzipped? */ put_tag_and_len(0xFE,0,&p); /* LRC tag */ sc_log(card->ctx, "DEE buf %p len %"SC_FORMAT_LEN_PTRDIFF_T"u %"SC_FORMAT_LEN_SIZE_T"u", sbuf, p - sbuf, sbuflen); enumtag = piv_objects[priv->selected_obj].enumtag; r = piv_put_data(card, enumtag, sbuf, sbuflen); if (sbuf) free(sbuf); LOG_FUNC_RETURN(card->ctx, r); } /* * For certs we need to add the 0x53 tag and other specific tags, * and call the piv_put_data * Note: the select file will have saved the object type for us * Write is used by piv-tool, so we will use flags: * length << 8 | 8bits: * object xxxx0000 * uncompressed cert xxx00001 * compressed cert xxx10001 * pubkey xxxx0010 * * to indicate we are writing a cert and if is compressed * or if we are writing a pubkey in to the cache. * if its not a cert or pubkey its an object. * * Therefore when idx=0, we will get the length of the object * and allocate a buffer, so we can support partial writes. * When the last chuck of the data is sent, we will write it. */ static int piv_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { piv_private_data_t * priv = PIV_DATA(card); int r; int enumtag; LOG_FUNC_CALLED(card->ctx); if (priv->selected_obj < 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); enumtag = piv_objects[priv->selected_obj].enumtag; if (priv->rwb_state == 1) /* trying to write at end */ LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); if (priv->rwb_state == -1) { /* if cached, remove old entry */ if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) { priv->obj_cache[enumtag].flags = 0; if (priv->obj_cache[enumtag].obj_data) { free(priv->obj_cache[enumtag].obj_data); priv->obj_cache[enumtag].obj_data = NULL; priv->obj_cache[enumtag].obj_len = 0; } if (priv->obj_cache[enumtag].internal_obj_data) { free(priv->obj_cache[enumtag].internal_obj_data); priv->obj_cache[enumtag].internal_obj_data = NULL; priv->obj_cache[enumtag].internal_obj_len = 0; } } if (idx != 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT); priv->w_buf_len = flags>>8; if (priv->w_buf_len == 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); priv->w_buf = malloc(priv->w_buf_len); priv-> rwb_state = 0; } /* on each pass make sure we have w_buf */ if (priv->w_buf == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); if (idx + count > priv->w_buf_len) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID); memcpy(priv->w_buf + idx, buf, count); /* copy one chunk */ /* if this was not the last chunk, return to get rest */ if (idx + count < priv->w_buf_len) LOG_FUNC_RETURN(card->ctx, count); priv-> rwb_state = 1; /* at end of object */ switch (flags & 0x0f) { case 1: r = piv_write_certificate(card, priv->w_buf, priv->w_buf_len, flags & 0x10); break; case 2: /* pubkey to be added to cache, it should have 0x53 and 0x99 tags. */ /* TODO: -DEE this is not fully implemented and not used */ r = priv->w_buf_len; break; default: r = piv_put_data(card, enumtag, priv->w_buf, priv->w_buf_len); break; } /* if it worked, will cache it */ if (r >= 0 && priv->w_buf) { priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID; priv->obj_cache[enumtag].obj_data = priv->w_buf; priv->obj_cache[enumtag].obj_len = priv->w_buf_len; } else { if (priv->w_buf) free(priv->w_buf); } priv->w_buf = NULL; priv->w_buf_len = 0; LOG_FUNC_RETURN(card->ctx, (r < 0)? r : (int)count); } /* * Card initialization is NOT standard. * Some cards use mutual or external authentication using 3des or aes key. We * will read in the key from a file either binary or hex encoded. * This is only needed during initialization/personalization of the card */ #ifdef ENABLE_OPENSSL static const EVP_CIPHER *get_cipher_for_algo(int alg_id) { switch (alg_id) { case 0x0: return EVP_des_ede3_ecb(); case 0x1: return EVP_des_ede3_ecb(); /* 2TDES */ case 0x3: return EVP_des_ede3_ecb(); case 0x8: return EVP_aes_128_ecb(); case 0xA: return EVP_aes_192_ecb(); case 0xC: return EVP_aes_256_ecb(); default: return NULL; } } static int get_keylen(unsigned int alg_id, size_t *size) { switch(alg_id) { case 0x01: *size = 192/8; /* 2TDES still has 3 single des keys phase out by 12/31/2010 */ break; case 0x00: case 0x03: *size = 192/8; break; case 0x08: *size = 128/8; break; case 0x0A: *size = 192/8; break; case 0x0C: *size = 256/8; break; default: return SC_ERROR_INVALID_ARGUMENTS; } return SC_SUCCESS; } static int piv_get_key(sc_card_t *card, unsigned int alg_id, u8 **key, size_t *len) { int r; size_t fsize; FILE *f = NULL; char * keyfilename = NULL; size_t expected_keylen; size_t keylen; u8 * keybuf = NULL; u8 * tkey = NULL; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); keyfilename = (char *)getenv("PIV_EXT_AUTH_KEY"); if (keyfilename == NULL) { sc_log(card->ctx, "Unable to get PIV_EXT_AUTH_KEY=(null) for general_external_authenticate"); r = SC_ERROR_FILE_NOT_FOUND; goto err; } r = get_keylen(alg_id, &expected_keylen); if(r) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x", alg_id); r = SC_ERROR_INVALID_ARGUMENTS; goto err; } f = fopen(keyfilename, "rb"); if (!f) { sc_log(card->ctx, " Unable to load key from file\n"); r = SC_ERROR_FILE_NOT_FOUND; goto err; } if (0 > fseek(f, 0L, SEEK_END)) r = SC_ERROR_INTERNAL; fsize = ftell(f); if (0 > (long) fsize) r = SC_ERROR_INTERNAL; if (0 > fseek(f, 0L, SEEK_SET)) r = SC_ERROR_INTERNAL; if(r) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not read %s\n", keyfilename); goto err; } keybuf = malloc(fsize+1); /* if not binary, need null to make it a string */ if (!keybuf) { sc_log(card->ctx, " Unable to allocate key memory"); r = SC_ERROR_OUT_OF_MEMORY; goto err; } keybuf[fsize] = 0x00; /* in case it is text need null */ if (fread(keybuf, 1, fsize, f) != fsize) { sc_log(card->ctx, " Unable to read key\n"); r = SC_ERROR_WRONG_LENGTH; goto err; } tkey = malloc(expected_keylen); if (!tkey) { sc_log(card->ctx, " Unable to allocate key memory"); r = SC_ERROR_OUT_OF_MEMORY; goto err; } if (fsize == expected_keylen) { /* it must be binary */ memcpy(tkey, keybuf, expected_keylen); } else { /* if the key-length is larger then binary length, we assume hex encoded */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Treating key as hex-encoded!\n"); sc_right_trim(keybuf, fsize); keylen = expected_keylen; r = sc_hex_to_bin((char *)keybuf, tkey, &keylen); if (keylen !=expected_keylen || r != 0 ) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error formatting key\n"); if (r == 0) r = SC_ERROR_INCOMPATIBLE_KEY; goto err; } } *key = tkey; tkey = NULL; *len = expected_keylen; r = SC_SUCCESS; err: if (f) fclose(f); if (keybuf) { free(keybuf); } if (tkey) { free(tkey); } LOG_FUNC_RETURN(card->ctx, r); return r; } #endif /* * will only deal with 3des for now * assumptions include: * size of encrypted data is same as unencrypted * challenges, nonces etc from card are less then 114 (keeps tags simple) */ static int piv_general_mutual_authenticate(sc_card_t *card, unsigned int key_ref, unsigned int alg_id) { int r; #ifdef ENABLE_OPENSSL int N; int locked = 0; u8 *rbuf = NULL; size_t rbuflen; u8 *nonce = NULL; size_t nonce_len; u8 *p; u8 *key = NULL; size_t keylen; u8 *plain_text = NULL; size_t plain_text_len = 0; u8 *tmp; size_t tmplen, tmplen2; u8 *built = NULL; size_t built_len; const u8 *body = NULL; size_t body_len; const u8 *witness_data = NULL; size_t witness_len; const u8 *challenge_response = NULL; size_t challenge_response_len; u8 *decrypted_reponse = NULL; size_t decrypted_reponse_len; EVP_CIPHER_CTX * ctx = NULL; u8 sbuf[255]; const EVP_CIPHER *cipher; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } cipher = get_cipher_for_algo(alg_id); if(!cipher) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x\n", alg_id); r = SC_ERROR_INVALID_ARGUMENTS; goto err; } r = piv_get_key(card, alg_id, &key, &keylen); if (r) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n"); goto err; } r = sc_lock(card); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n"); goto err; /* cleanup */ } locked = 1; p = sbuf; *p++ = 0x7C; *p++ = 0x02; *p++ = 0x80; *p++ = 0x00; /* get the encrypted nonce */ r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, &rbuf, &rbuflen); if (r < 0) goto err; /* Remove the encompassing outer TLV of 0x7C and get the data */ body = sc_asn1_find_tag(card->ctx, rbuf, r, 0x7C, &body_len); if (!body) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Witness Data response of NULL\n"); r = SC_ERROR_INVALID_DATA; goto err; } /* Get the witness data indicated by the TAG 0x80 */ witness_data = sc_asn1_find_tag(card->ctx, body, body_len, 0x80, &witness_len); if (!witness_len) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n"); r = SC_ERROR_INVALID_DATA; goto err; } /* Allocate an output buffer for openssl */ plain_text = malloc(witness_len); if (!plain_text) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for plain text\n"); r = SC_ERROR_INTERNAL; goto err; } /* decrypt the data from the card */ if (!EVP_DecryptInit(ctx, cipher, key, NULL)) { /* may fail if des parity of key is wrong. depends on OpenSSL options */ r = SC_ERROR_INTERNAL; goto err; } EVP_CIPHER_CTX_set_padding(ctx,0); p = plain_text; if (!EVP_DecryptUpdate(ctx, p, &N, witness_data, witness_len)) { r = SC_ERROR_INTERNAL; goto err; } plain_text_len = tmplen = N; p += tmplen; if(!EVP_DecryptFinal(ctx, p, &N)) { r = SC_ERROR_INTERNAL; goto err; } tmplen = N; plain_text_len += tmplen; if (plain_text_len != witness_len) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypted and decrypted lengths do not match: %"SC_FORMAT_LEN_SIZE_T"u:%"SC_FORMAT_LEN_SIZE_T"u\n", witness_len, plain_text_len); r = SC_ERROR_INTERNAL; goto err; } /* Build a response to the card of: * [GEN AUTH][ 80<decrypted witness>81 <challenge> ] * Start by computing the nonce for <challenge> the * nonce length should match the witness length of * the card. */ nonce = malloc(witness_len); if(!nonce) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM allocating nonce (%"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u)\n", witness_len, plain_text_len); r = SC_ERROR_INTERNAL; goto err; } nonce_len = witness_len; r = RAND_bytes(nonce, witness_len); if(!r) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Generating random for nonce (%"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u)\n", witness_len, plain_text_len); r = SC_ERROR_INTERNAL; goto err; } /* nonce for challenge */ tmplen = put_tag_and_len(0x81, witness_len, NULL); /* plain text witness keep a length separate for the 0x7C tag */ tmplen += put_tag_and_len(0x80, witness_len, NULL); tmplen2 = tmplen; /* outside 7C tag with 81:80 as innards */ tmplen = put_tag_and_len(0x7C, tmplen, NULL); built_len = tmplen; /* Build the response buffer */ p = built = malloc(built_len); if(!built) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Building witness response and challenge\n"); r = SC_ERROR_INTERNAL; goto err; } p = built; /* Start with the 7C Tag */ put_tag_and_len(0x7C, tmplen2, &p); /* Add the DECRYPTED witness, tag 0x80 */ put_tag_and_len(0x80, witness_len, &p); memcpy(p, plain_text, witness_len); p += witness_len; /* Add the challenge, tag 0x81 */ put_tag_and_len(0x81, witness_len, &p); memcpy(p, nonce, witness_len); /* Don't leak rbuf from above */ free(rbuf); rbuf = NULL; /* Send constructed data */ r = piv_general_io(card, 0x87, alg_id, key_ref, built,built_len, &rbuf, &rbuflen); if (r < 0) goto err; /* Remove the encompassing outer TLV of 0x7C and get the data */ body = sc_asn1_find_tag(card->ctx, rbuf, r, 0x7C, &body_len); if(!body) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find outer tag 0x7C in response"); r = SC_ERROR_INVALID_DATA; goto err; } /* SP800-73 not clear if 80 or 82 */ challenge_response = sc_asn1_find_tag(card->ctx, body, body_len, 0x82, &challenge_response_len); if(!challenge_response) { challenge_response = sc_asn1_find_tag(card->ctx, body, body_len, 0x80, &challenge_response_len); if(!challenge_response) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find tag 0x82 or 0x80 in response"); r = SC_ERROR_INVALID_DATA; goto err; } } /* Decrypt challenge and check against nonce */ decrypted_reponse = malloc(challenge_response_len); if(!decrypted_reponse) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Allocating decryption buffer"); r = SC_ERROR_INVALID_DATA; goto err; } EVP_CIPHER_CTX_cleanup(ctx); if (!EVP_DecryptInit(ctx, cipher, key, NULL)) { r = SC_ERROR_INTERNAL; goto err; } EVP_CIPHER_CTX_set_padding(ctx,0); tmp = decrypted_reponse; if (!EVP_DecryptUpdate(ctx, tmp, &N, challenge_response, challenge_response_len)) { r = SC_ERROR_INTERNAL; goto err; } decrypted_reponse_len = tmplen = N; tmp += tmplen; if(!EVP_DecryptFinal(ctx, tmp, &N)) { r = SC_ERROR_INTERNAL; goto err; } tmplen = N; decrypted_reponse_len += tmplen; if (decrypted_reponse_len != nonce_len || memcmp(nonce, decrypted_reponse, nonce_len) != 0) { sc_log(card->ctx, "mutual authentication failed, card returned wrong value %"SC_FORMAT_LEN_SIZE_T"u:%"SC_FORMAT_LEN_SIZE_T"u", decrypted_reponse_len, nonce_len); r = SC_ERROR_DECRYPT_FAILED; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_CIPHER_CTX_free(ctx); if (locked) sc_unlock(card); if (rbuf) free(rbuf); if (decrypted_reponse) free(decrypted_reponse); if (built) free(built); if (plain_text) free(plain_text); if (nonce) free(nonce); if (key) free(key); #else sc_log(card->ctx, "OpenSSL Required"); r = SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ LOG_FUNC_RETURN(card->ctx, r); } /* Currently only used for card administration */ static int piv_general_external_authenticate(sc_card_t *card, unsigned int key_ref, unsigned int alg_id) { int r; #ifdef ENABLE_OPENSSL int tmplen; int outlen; int locked = 0; u8 *p; u8 *rbuf = NULL; u8 *key = NULL; u8 *cypher_text = NULL; u8 *output_buf = NULL; const u8 *body = NULL; const u8 *challenge_data = NULL; size_t rbuflen; size_t body_len; size_t output_len; size_t challenge_len; size_t keylen = 0; size_t cypher_text_len = 0; u8 sbuf[255]; EVP_CIPHER_CTX * ctx = NULL; const EVP_CIPHER *cipher; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Selected cipher for algorithm id: %02x\n", alg_id); cipher = get_cipher_for_algo(alg_id); if(!cipher) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for: %02x\n", alg_id); r = SC_ERROR_INVALID_ARGUMENTS; goto err; } r = piv_get_key(card, alg_id, &key, &keylen); if (r) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n"); goto err; } r = sc_lock(card); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n"); goto err; /* cleanup */ } locked = 1; p = sbuf; *p++ = 0x7C; *p++ = 0x02; *p++ = 0x81; *p++ = 0x00; /* get a challenge */ r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, &rbuf, &rbuflen); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting Challenge\n"); goto err; } /* * the value here corresponds with the response size, so we use this * to alloc the response buffer, rather than re-computing it. */ output_len = r; /* Remove the encompassing outer TLV of 0x7C and get the data */ body = sc_asn1_find_tag(card->ctx, rbuf, r, 0x7C, &body_len); if (!body) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data response of NULL\n"); r = SC_ERROR_INVALID_DATA; goto err; } /* Get the challenge data indicated by the TAG 0x81 */ challenge_data = sc_asn1_find_tag(card->ctx, body, body_len, 0x81, &challenge_len); if (!challenge_data) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n"); r = SC_ERROR_INVALID_DATA; goto err; } /* Store this to sanity check that plaintext length and cyphertext lengths match */ /* TODO is this required */ tmplen = challenge_len; /* Encrypt the challenge with the secret */ if (!EVP_EncryptInit(ctx, cipher, key, NULL)) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt fail\n"); r = SC_ERROR_INTERNAL; goto err; } cypher_text = malloc(challenge_len); if (!cypher_text) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for cipher text\n"); r = SC_ERROR_INTERNAL; goto err; } EVP_CIPHER_CTX_set_padding(ctx,0); if (!EVP_EncryptUpdate(ctx, cypher_text, &outlen, challenge_data, challenge_len)) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt update fail\n"); r = SC_ERROR_INTERNAL; goto err; } cypher_text_len += outlen; if (!EVP_EncryptFinal(ctx, cypher_text + cypher_text_len, &outlen)) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Final fail\n"); r = SC_ERROR_INTERNAL; goto err; } cypher_text_len += outlen; /* * Actually perform the sanity check on lengths plaintext length vs * encrypted length */ if (cypher_text_len != (size_t)tmplen) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Length test fail\n"); r = SC_ERROR_INTERNAL; goto err; } output_buf = malloc(output_len); if(!output_buf) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate output buffer: %s\n", strerror(errno)); r = SC_ERROR_INTERNAL; goto err; } p = output_buf; /* * Build: 7C<len>[82<len><challenge>] * Start off by capturing the data of the response: * - 82<len><encrypted challenege response> * Build the outside TLV (7C) * Advance past that tag + len * Build the body (82) * memcopy the body past the 7C<len> portion * Transmit */ tmplen = put_tag_and_len(0x82, cypher_text_len, NULL); tmplen = put_tag_and_len(0x7C, tmplen, &p); /* Build the 0x82 TLV and append to the 7C<len> tag */ tmplen += put_tag_and_len(0x82, cypher_text_len, &p); memcpy(p, cypher_text, cypher_text_len); p += cypher_text_len; tmplen += cypher_text_len; /* Sanity check the lengths again */ if(output_len != (size_t)tmplen) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Allocated and computed lengths do not match! " "Expected %"SC_FORMAT_LEN_SIZE_T"d, found: %d\n", output_len, tmplen); r = SC_ERROR_INTERNAL; goto err; } r = piv_general_io(card, 0x87, alg_id, key_ref, output_buf, output_len, NULL, NULL); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Got response challenge\n"); err: if (ctx) EVP_CIPHER_CTX_free(ctx); if (locked) sc_unlock(card); if (key) { sc_mem_clear(key, keylen); free(key); } if (rbuf) free(rbuf); if (cypher_text) free(cypher_text); if (output_buf) free(output_buf); #else sc_log(card->ctx, "OpenSSL Required"); r = SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ LOG_FUNC_RETURN(card->ctx, r); } static int piv_get_serial_nr_from_CHUI(sc_card_t* card, sc_serial_number_t* serial) { int r; int i; u8 gbits; u8 *rbuf = NULL; const u8 *body; const u8 *fascn; const u8 *guid; size_t rbuflen = 0, bodylen, fascnlen, guidlen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (card->serialnr.len) { *serial = card->serialnr; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * 800-73-3 Part 1 and CIO Council docs say for PIV Compatible cards * the FASC-N Agency code should be 9999 and there should be a GUID * based on RFC 4122. If GUID present and not zero * we will use the GUID as the serial number. */ r = piv_get_cached_data(card, PIV_OBJ_CHUI, &rbuf, &rbuflen); LOG_TEST_RET(card->ctx, r, "Failure retrieving CHUI"); r = SC_ERROR_INTERNAL; if (rbuflen != 0) { body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x53, &bodylen); /* Pass the outer wrapper asn1 */ if (body != NULL && bodylen != 0) { fascn = sc_asn1_find_tag(card->ctx, body, bodylen, 0x30, &fascnlen); /* Find the FASC-N data */ guid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x34, &guidlen); gbits = 0; /* if guid is valid, gbits will not be zero */ if (guid && guidlen == 16) { for (i = 0; i < 16; i++) { gbits = gbits | guid[i]; /* if all are zero, gbits will be zero */ } } sc_log(card->ctx, "fascn=%p,fascnlen=%"SC_FORMAT_LEN_SIZE_T"u,guid=%p,guidlen=%"SC_FORMAT_LEN_SIZE_T"u,gbits=%2.2x", fascn, fascnlen, guid, guidlen, gbits); if (fascn && fascnlen == 25) { /* test if guid and the fascn starts with ;9999 (in ISO 4bit + parity code) */ if (!(gbits && fascn[0] == 0xD4 && fascn[1] == 0xE7 && fascn[2] == 0x39 && (fascn[3] | 0x7F) == 0xFF)) { serial->len = fascnlen < SC_MAX_SERIALNR ? fascnlen : SC_MAX_SERIALNR; memcpy (serial->value, fascn, serial->len); r = SC_SUCCESS; gbits = 0; /* set to skip using guid below */ } } if (guid && gbits) { serial->len = guidlen < SC_MAX_SERIALNR ? guidlen : SC_MAX_SERIALNR; memcpy (serial->value, guid, serial->len); r = SC_SUCCESS; } } } card->serialnr = *serial; LOG_FUNC_RETURN(card->ctx, r); } /* * If the object can not be present on the card, because the History * object is not present or the History object says its not present, * return 1. If object may be present return 0. * Cuts down on overhead, by not showing non existent objects to pkcs11 * The path for the object is passed in and the first 2 bytes are used. * Note: If the History or Discovery object is not found the * PIV_OBJ_CACHE_NOT_PRESENT is set, as older cards do not have these. * pkcs15-piv.c calls this via cardctl. */ static int piv_is_object_present(sc_card_t *card, u8 *ptr) { piv_private_data_t * priv = PIV_DATA(card); int r = 0; int enumtag; enumtag = piv_find_obj_by_containerid(card, ptr); if (enumtag >= 0 && priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT) r = 1; LOG_FUNC_RETURN(card->ctx, r); } /* * NIST 800-73-3 allows the default pin to be the PIV application 0x80 * or the global pin for the card 0x00. Look at Discovery object to get this. * called by pkcs15-piv.c via cardctl when setting up the pins. */ static int piv_get_pin_preference(sc_card_t *card, int *ptr) { piv_private_data_t * priv = PIV_DATA(card); *ptr = priv->pin_preference; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int piv_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { piv_private_data_t * priv = PIV_DATA(card); u8 * opts; /* A or M, key_ref, alg_id */ LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_PIV_AUTHENTICATE: opts = (u8 *)ptr; switch (*opts) { case 'A': return piv_general_external_authenticate(card, *(opts+1), *(opts+2)); break; case 'M': return piv_general_mutual_authenticate(card, *(opts+1), *(opts+2)); break; } break; case SC_CARDCTL_PIV_GENERATE_KEY: return piv_generate_key(card, (sc_cardctl_piv_genkey_info_t *) ptr); break; case SC_CARDCTL_GET_SERIALNR: return piv_get_serial_nr_from_CHUI(card, (sc_serial_number_t *) ptr); break; case SC_CARDCTL_PIV_PIN_PREFERENCE: return piv_get_pin_preference(card, ptr); break; case SC_CARDCTL_PIV_OBJECT_PRESENT: return piv_is_object_present(card, ptr); break; } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int piv_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* Dynamic Authentication Template (Challenge) */ u8 sbuf[] = {0x7c, 0x02, 0x81, 0x00}; u8 *rbuf = NULL; const u8 *p; size_t rbuf_len = 0, out_len = 0; int r; unsigned int tag, cla; LOG_FUNC_CALLED(card->ctx); /* NIST 800-73-3 says use 9B, previous verisons used 00 */ r = piv_general_io(card, 0x87, 0x00, 0x9B, sbuf, sizeof sbuf, &rbuf, &rbuf_len); LOG_TEST_GOTO_ERR(card->ctx, r, "GENERAL AUTHENTICATE failed"); p = rbuf; r = sc_asn1_read_tag(&p, rbuf_len, &cla, &tag, &out_len); if (r < 0 || (cla|tag) != 0x7C) { LOG_TEST_GOTO_ERR(card->ctx, SC_ERROR_INVALID_DATA, "Can't find Dynamic Authentication Template"); } rbuf_len = out_len; r = sc_asn1_read_tag(&p, rbuf_len, &cla, &tag, &out_len); if (r < 0 || (cla|tag) != 0x81) { LOG_TEST_GOTO_ERR(card->ctx, SC_ERROR_INVALID_DATA, "Can't find Challenge"); } if (len < out_len) { out_len = len; } memcpy(rnd, p, out_len); r = (int) out_len; err: free(rbuf); LOG_FUNC_RETURN(card->ctx, r); } static int piv_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { piv_private_data_t * priv = PIV_DATA(card); int r = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); priv->operation = env->operation; priv->algorithm = env->algorithm; if (env->algorithm == SC_ALGORITHM_RSA) { priv->alg_id = 0x06; /* Say it is RSA, set 5, 6, 7 later */ } else if (env->algorithm == SC_ALGORITHM_EC) { if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { switch (env->algorithm_ref) { case 256: priv->alg_id = 0x11; /* Say it is EC 256 */ priv->key_size = 256; break; case 384: priv->alg_id = 0x14; priv->key_size = 384; break; default: r = SC_ERROR_NO_CARD_SUPPORT; } } else r = SC_ERROR_NO_CARD_SUPPORT; } else r = SC_ERROR_NO_CARD_SUPPORT; priv->key_ref = env->key_ref[0]; LOG_FUNC_RETURN(card->ctx, r); } static int piv_restore_security_env(sc_card_t *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int piv_validate_general_authentication(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { piv_private_data_t * priv = PIV_DATA(card); int r; u8 *p; const u8 *tag; size_t taglen; const u8 *body; size_t bodylen; unsigned int real_alg_id; u8 sbuf[4096]; /* needs work. for 3072 keys, needs 384+10 or so */ u8 *rbuf = NULL; size_t rbuflen = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* should assume large send data */ p = sbuf; put_tag_and_len(0x7c, (2 + put_tag_and_len(0, datalen, NULL)) , &p); put_tag_and_len(0x82, 0, &p); if (priv->operation == SC_SEC_OPERATION_DERIVE && priv->algorithm == SC_ALGORITHM_EC) put_tag_and_len(0x85, datalen, &p); else put_tag_and_len(0x81, datalen, &p); memcpy(p, data, datalen); p += datalen; /* * alg_id=06 is a place holder for all RSA keys. * Derive the real alg_id based on the size of the * the data, as we are always using raw mode. * Non RSA keys needs some work in thia area. */ real_alg_id = priv->alg_id; if (priv->alg_id == 0x06) { switch (datalen) { case 128: real_alg_id = 0x06; break; case 256: real_alg_id = 0x07; break; case 384: real_alg_id = 0x05; break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT); } } /* EC alg_id was already set */ r = piv_general_io(card, 0x87, real_alg_id, priv->key_ref, sbuf, p - sbuf, &rbuf, &rbuflen); if ( r >= 0) { body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x7c, &bodylen); if (body) { tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x82, &taglen); if (tag) { memcpy(out, tag, taglen); r = taglen; } } else r = SC_ERROR_INVALID_DATA; } if (rbuf) free(rbuf); LOG_FUNC_RETURN(card->ctx, r); } static int piv_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { piv_private_data_t * priv = PIV_DATA(card); int r; int i; size_t nLen; u8 rbuf[128]; /* For EC conversions 384 will fit */ size_t rbuflen = sizeof(rbuf); const u8 * body; size_t bodylen; const u8 * tag; size_t taglen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* The PIV returns a DER SEQUENCE{INTEGER, INTEGER} * Which may have leading 00 to force positive * TODO: -DEE should check if PKCS15 want the same * But PKCS11 just wants 2* filed_length in bytes * So we have to strip out the integers * if present and pad on left if too short. */ if (priv->alg_id == 0x11 || priv->alg_id == 0x14 ) { nLen = (priv->key_size + 7) / 8; if (outlen < 2*nLen) { sc_log(card->ctx, " output too small for EC signature %"SC_FORMAT_LEN_SIZE_T"u < %"SC_FORMAT_LEN_SIZE_T"u", outlen, 2 * nLen); r = SC_ERROR_INVALID_DATA; goto err; } memset(out, 0, outlen); r = piv_validate_general_authentication(card, data, datalen, rbuf, rbuflen); if (r < 0) goto err; if ( r >= 0) { body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x30, &bodylen); for (i = 0; i<2; i++) { if (body) { tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x02, &taglen); if (tag) { bodylen -= taglen - (tag - body); body = tag + taglen; if (taglen > nLen) { /* drop leading 00 if present */ if (*tag != 0x00) { r = SC_ERROR_INVALID_DATA; goto err; } tag++; taglen--; } memcpy(out + nLen*i + nLen - taglen , tag, taglen); } else { r = SC_ERROR_INVALID_DATA; goto err; } } else { r = SC_ERROR_INVALID_DATA; goto err; } } r = 2 * nLen; } } else { /* RSA is all set */ r = piv_validate_general_authentication(card, data, datalen, out, outlen); } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int piv_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, piv_validate_general_authentication(card, data, datalen, out, outlen)); } /* * the PIV-II does not always support files, but we will simulate * files and reading/writing using get/put_data * The path is the containerID number * We can use this to determine the type of data requested, like a cert * or pub key. * We only support write from the piv_tool with file_out==NULL * All other requests should be to read. * Only if file_out != null, will we read to get length. */ static int piv_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { piv_private_data_t * priv = PIV_DATA(card); int r; int i; const u8 *path; int pathlen; sc_file_t *file = NULL; u8 * rbuf = NULL; size_t rbuflen = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); path = in_path->value; pathlen = in_path->len; /* only support single EF in current application */ /* * PIV emulates files, and only does so because sc_pkcs15_* uses * select_file and read_binary. The emulation adds path emulated structures * so piv_select_file will find it. * there is no dir. Only direct access to emulated files * thus opensc-tool and opensc-explorer can not read the emulated files */ if (memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } i = piv_find_obj_by_containerid(card, path); if (i < 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND); /* * pkcs15 will use a 2 byte path or a 4 byte path * with cece added to path to request only the cert from the cert obj * PIV "Container ID" is used as the path, and are two bytes long */ priv->return_only_cert = (pathlen == 4 && path[2] == 0xce && path[3] == 0xce); priv->selected_obj = i; priv->rwb_state = -1; /* make it look like the file was found. */ /* We don't want to read it now unless we need the length */ if (file_out) { /* we need to read it now, to get length into cache */ r = piv_get_cached_data(card, i, &rbuf, &rbuflen); if (r < 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND); /* get the cert or the pub key out and into the cache too */ if (priv->return_only_cert || piv_objects[i].flags & PIV_OBJECT_TYPE_PUBKEY) { r = piv_cache_internal_data(card, i); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); } file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; /* this could be like the FCI */ file->type = SC_FILE_TYPE_DF; file->shareable = 0; file->ef_structure = 0; if (priv->return_only_cert) file->size = priv->obj_cache[i].internal_obj_len; else file->size = priv->obj_cache[i].obj_len; file->id = (piv_objects[i].containerid[0]<<8) + piv_objects[i].containerid[1]; *file_out = file; } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int piv_parse_discovery(sc_card_t *card, u8 * rbuf, size_t rbuflen, int aid_only) { piv_private_data_t * priv = PIV_DATA(card); int r = 0; const u8 * body; size_t bodylen; const u8 * aid; size_t aidlen; const u8 * pinp; size_t pinplen; unsigned int cla_out, tag_out; if (rbuflen != 0) { body = rbuf; if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS) { sc_log(card->ctx, "DER problem %d",r); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } sc_log(card->ctx, "Discovery 0x%2.2x 0x%2.2x %p:%"SC_FORMAT_LEN_SIZE_T"u", cla_out, tag_out, body, bodylen); if ( cla_out+tag_out == 0x7E && body != NULL && bodylen != 0) { aidlen = 0; aid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x4F, &aidlen); sc_log(card->ctx, "Discovery aid=%p:%"SC_FORMAT_LEN_SIZE_T"u", aid, aidlen); if (aid == NULL || aidlen < piv_aids[0].len_short || memcmp(aid,piv_aids[0].value,piv_aids[0].len_short) != 0) { /*TODO look at long */ sc_log(card->ctx, "Discovery object not PIV"); r = SC_ERROR_INVALID_CARD; /* This is an error */ goto err; } if (aid_only == 0) { pinp = sc_asn1_find_tag(card->ctx, body, bodylen, 0x5F2F, &pinplen); sc_log(card->ctx, "Discovery pinp=%p:%"SC_FORMAT_LEN_SIZE_T"u", pinp, pinplen); if (pinp && pinplen == 2) { sc_log(card->ctx, "Discovery pinp flags=0x%2.2x 0x%2.2x",*pinp, *(pinp+1)); r = SC_SUCCESS; if (*pinp == 0x60 && *(pinp+1) == 0x20) { /* use Global pin */ sc_log(card->ctx, "Pin Preference - Global"); priv->pin_preference = 0x00; } } } } } err: LOG_FUNC_RETURN(card->ctx, r); } /* normal way to get the discovery object via cache */ static int piv_process_discovery(sc_card_t *card) { int r; u8 * rbuf = NULL; size_t rbuflen = 0; r = piv_get_cached_data(card, PIV_OBJ_DISCOVERY, &rbuf, &rbuflen); /* Note rbuf and rbuflen are now pointers into cache */ if (r < 0) goto err; sc_log(card->ctx, "Discovery = %p:%"SC_FORMAT_LEN_SIZE_T"u", rbuf, rbuflen); /* the object is now cached, see what we have */ r = piv_parse_discovery(card, rbuf, rbuflen, 0); err: LOG_FUNC_RETURN(card->ctx, r); } static int piv_find_discovery(sc_card_t *card) { int r = 0; u8 rbuf[256]; size_t rbuflen = sizeof(rbuf); u8 * arbuf = rbuf; piv_private_data_t * priv = PIV_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* * During piv_match or piv_card_reader_lock_obtained, * we use the discovery object to test if card present, and * if PIV AID is active. So we can not use the cache */ /* If not valid, read, cache and test */ if (!(priv->obj_cache[PIV_OBJ_DISCOVERY].flags & PIV_OBJ_CACHE_VALID)) { r = piv_process_discovery(card); } else { /* if already in cache,force read */ r = piv_get_data(card, PIV_OBJ_DISCOVERY, &arbuf, &rbuflen); if (r >= 0) /* make sure it is PIV AID */ r = piv_parse_discovery(card, rbuf, rbuflen, 1); } LOG_FUNC_RETURN(card->ctx, r); } /* * The history object lists what retired keys and certs are on the card * or listed in the offCardCertURL. The user may have read the offCardURL file, * ahead of time, and if so will use it for the certs listed. * TODO: -DEE * If the offCardCertURL is not cached by the user, should we wget it here? * Its may be out of scope to have OpenSC read the URL. */ static int piv_process_history(sc_card_t *card) { piv_private_data_t * priv = PIV_DATA(card); int r; int i; int enumtag; u8 * rbuf = NULL; size_t rbuflen = 0; const u8 * body; size_t bodylen; const u8 * num; size_t numlen; const u8 * url = NULL; size_t urllen; u8 * ocfhfbuf = NULL; unsigned int cla_out, tag_out; size_t ocfhflen; const u8 * seq; const u8 * seqtag; size_t seqlen; const u8 * keyref; size_t keyreflen; const u8 * cert; size_t certlen; size_t certobjlen, i2; u8 * certobj; u8 * cp; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = piv_get_cached_data(card, PIV_OBJ_HISTORY, &rbuf, &rbuflen); if (r == SC_ERROR_FILE_NOT_FOUND) r = 0; /* OK if not found */ if (r <= 0) { priv->obj_cache[PIV_OBJ_HISTORY].flags |= PIV_OBJ_CACHE_NOT_PRESENT; goto err; /* no file, must be pre 800-73-3 card and not on card */ } /* the object is now cached, see what we have */ if (rbuflen != 0) { body = rbuf; if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS) { sc_log(card->ctx, "DER problem %d",r); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } if ( cla_out+tag_out == 0x53 && body != NULL && bodylen != 0) { numlen = 0; num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC1, &numlen); if (num) { if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20-PIV_OBJ_RETIRED_X509_1+1) { r = SC_ERROR_INTERNAL; /* TODO some other error */ goto err; } priv->keysWithOnCardCerts = *num; } numlen = 0; num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC2, &numlen); if (num) { if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20-PIV_OBJ_RETIRED_X509_1+1) { r = SC_ERROR_INTERNAL; /* TODO some other error */ goto err; } priv->keysWithOffCardCerts = *num; } url = sc_asn1_find_tag(card->ctx, body, bodylen, 0xF3, &urllen); if (url) { priv->offCardCertURL = calloc(1,urllen+1); if (priv->offCardCertURL == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(priv->offCardCertURL, url, urllen); } } else { sc_log(card->ctx, "Problem with History object\n"); goto err; } } sc_log(card->ctx, "History on=%d off=%d URL=%s", priv->keysWithOnCardCerts, priv->keysWithOffCardCerts, priv->offCardCertURL ? priv->offCardCertURL:"NONE"); /* now mark what objects are on the card */ for (i=0; i<priv->keysWithOnCardCerts; i++) priv->obj_cache[PIV_OBJ_RETIRED_X509_1+i].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT; /* * If user has gotten copy of the file from the offCardCertsURL, * we will read in and add the certs to the cache as listed on * the card. some of the certs may be on the card as well. * * Get file name from url. verify that the filename is valid * The URL ends in a SHA1 string. We will use this as the filename * in the directory used for the PKCS15 cache */ r = 0; if (priv->offCardCertURL) { char * fp; char filename[PATH_MAX]; if (strncmp("http://", priv->offCardCertURL, 7)) { r = SC_ERROR_INVALID_DATA; goto err; } /* find the last / so we have the filename part */ fp = strrchr(priv->offCardCertURL + 7,'/'); if (fp == NULL) { r = SC_ERROR_INVALID_DATA; goto err; } fp++; /* Use the same directory as used for other OpenSC cached items */ r = sc_get_cache_dir(card->ctx, filename, sizeof(filename) - strlen(fp) - 2); if (r != SC_SUCCESS) goto err; #ifdef _WIN32 strcat(filename,"\\"); #else strcat(filename,"/"); #endif strcat(filename,fp); r = piv_read_obj_from_file(card, filename, &ocfhfbuf, &ocfhflen); if (r == SC_ERROR_FILE_NOT_FOUND) { r = 0; goto err; } /* * Its a seq of seq of a key ref and cert */ body = ocfhfbuf; if (sc_asn1_read_tag(&body, ocfhflen, &cla_out, &tag_out, &bodylen) != SC_SUCCESS || cla_out+tag_out != 0x30) { sc_log(card->ctx, "DER problem"); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } seq = body; while (bodylen > 0) { seqtag = seq; if (sc_asn1_read_tag(&seq, bodylen, &cla_out, &tag_out, &seqlen) != SC_SUCCESS || cla_out+tag_out != 0x30) { sc_log(card->ctx, "DER problem"); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } keyref = sc_asn1_find_tag(card->ctx, seq, seqlen, 0x04, &keyreflen); if (!keyref || keyreflen != 1 || (*keyref < 0x82 || *keyref > 0x95)) { sc_log(card->ctx, "DER problem"); r = SC_ERROR_INVALID_ASN1_OBJECT; goto err; } cert = keyref + keyreflen; certlen = seqlen - (cert - seq); enumtag = PIV_OBJ_RETIRED_X509_1 + *keyref - 0x82; /* now add the cert like another object */ i2 = put_tag_and_len(0x70,certlen, NULL) + put_tag_and_len(0x71, 1, NULL) + put_tag_and_len(0xFE, 0, NULL); certobjlen = put_tag_and_len(0x53, i2, NULL); certobj = malloc(certobjlen); if (certobj == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } cp = certobj; put_tag_and_len(0x53, i2, &cp); put_tag_and_len(0x70,certlen, &cp); memcpy(cp, cert, certlen); cp += certlen; put_tag_and_len(0x71, 1,&cp); *cp++ = 0x00; put_tag_and_len(0xFE, 0, &cp); priv->obj_cache[enumtag].obj_data = certobj; priv->obj_cache[enumtag].obj_len = certobjlen; priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID; priv->obj_cache[enumtag].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT; r = piv_cache_internal_data(card, enumtag); sc_log(card->ctx, "got internal r=%d",r); certobj = NULL; sc_log(card->ctx, "Added from off card file #%d %p:%"SC_FORMAT_LEN_SIZE_T"u 0x%02X", enumtag, priv->obj_cache[enumtag].obj_data, priv->obj_cache[enumtag].obj_len, *keyref); bodylen -= (seqlen + seq - seqtag); seq += seqlen; } } err: if (ocfhfbuf) free(ocfhfbuf); LOG_FUNC_RETURN(card->ctx, r); } static int piv_finish(sc_card_t *card) { piv_private_data_t * priv = PIV_DATA(card); int i; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { sc_file_free(priv->aid_file); if (priv->w_buf) free(priv->w_buf); if (priv->offCardCertURL) free(priv->offCardCertURL); for (i = 0; i < PIV_OBJ_LAST_ENUM - 1; i++) { sc_log(card->ctx, "DEE freeing #%d, 0x%02x %p:%"SC_FORMAT_LEN_SIZE_T"u %p:%"SC_FORMAT_LEN_SIZE_T"u", i, priv->obj_cache[i].flags, priv->obj_cache[i].obj_data, priv->obj_cache[i].obj_len, priv->obj_cache[i].internal_obj_data, priv->obj_cache[i].internal_obj_len); if (priv->obj_cache[i].obj_data) free(priv->obj_cache[i].obj_data); if (priv->obj_cache[i].internal_obj_data) free(priv->obj_cache[i].internal_obj_data); } free(priv); card->drv_data = NULL; /* priv */ } return 0; } static int piv_match_card(sc_card_t *card) { int r = 0; /* piv_match_card may be called with card->type, set by opensc.conf */ /* user provide card type must be one we know */ switch (card->type) { case -1: case SC_CARD_TYPE_PIV_II_GENERIC: case SC_CARD_TYPE_PIV_II_HIST: case SC_CARD_TYPE_PIV_II_NEO: case SC_CARD_TYPE_PIV_II_YUBIKEY4: case SC_CARD_TYPE_PIV_II_GI_DE: break; default: return 0; /* can not handle the card */ } /* its one we know, or we can test for it in piv_init */ /* * We will call piv_match_card_continued here then * again in piv_init to avoid any issues with passing * anything from piv_match_card * to piv_init as had been done in the past */ r = piv_match_card_continued(card); if (r == 1) { /* clean up what we left in card */ sc_unlock(card); piv_finish(card); } return r; } static int piv_match_card_continued(sc_card_t *card) { int i; int type = -1; piv_private_data_t *priv = NULL; int saved_type = card->type; /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; /* piv_match_card may be called with card->type, set by opensc.conf */ /* user provide card type must be one we know */ switch (card->type) { case -1: case SC_CARD_TYPE_PIV_II_GENERIC: case SC_CARD_TYPE_PIV_II_HIST: case SC_CARD_TYPE_PIV_II_NEO: case SC_CARD_TYPE_PIV_II_YUBIKEY4: case SC_CARD_TYPE_PIV_II_GI_DE: type = card->type; break; default: return 0; /* can not handle the card */ } if (type == -1) { /* *try to identify card by ATR or historical data in ATR * currently all PIV card will respond to piv_find_aid * the same. But in future may need to know card type first, * so do it here. */ if (card->reader->atr_info.hist_bytes != NULL) { if (card->reader->atr_info.hist_bytes_len == 8 && !(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) { type = SC_CARD_TYPE_PIV_II_YUBIKEY4; } else if (card->reader->atr_info.hist_bytes_len >= 7 && !(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) { type = SC_CARD_TYPE_PIV_II_NEO; } /* * https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf * lists 2 ATRS with historical bytes: * 73 66 74 65 2D 63 64 30 38 30 * 73 66 74 65 20 63 64 31 34 34 * will check for 73 66 74 65 */ else if (card->reader->atr_info.hist_bytes_len >= 4 && !(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) { type = SC_CARD_TYPE_PIV_II_GI_DE; } else if (card->reader->atr_info.hist_bytes_len > 0 && card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */ size_t datalen; const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1, card->reader->atr_info.hist_bytes_len - 1, 0xF0, &datalen); if (data != NULL) { int k; for (k = 0; piv_aids[k].len_long != 0; k++) { if (datalen == piv_aids[k].len_long && !memcmp(data, piv_aids[k].value, datalen)) { type = SC_CARD_TYPE_PIV_II_HIST; break; } } } } } if (type == -1) type = SC_CARD_TYPE_PIV_II_GENERIC; } /* allocate and init basic fields */ priv = calloc(1, sizeof(piv_private_data_t)); if (!priv) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); if (card->type == -1) card->type = type; card->drv_data = priv; /* will free if no match, or pass on to piv_init */ priv->aid_file = sc_file_new(); priv->selected_obj = -1; priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */ priv->logged_in = SC_PIN_STATE_UNKNOWN; priv->tries_left = 10; /* will assume OK at start */ priv->pstate = PIV_STATE_MATCH; /* Some objects will only be present if History object says so */ for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++) if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT) priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT; sc_lock(card); /* * detect if active AID is PIV. NIST 800-73 says Only one PIV application per card * and PIV must be the default application * This can avoid doing doing a select_aid and losing the login state on some cards * We may get interference on some cards by other drivers trying SELECT_AID before * we get to see if PIV application is still active. * putting PIV driver first might help. * This may fail if the wrong AID is active */ i = piv_find_discovery(card); if (i < 0) { /* Detect by selecting applet */ sc_file_t aidfile; i = piv_find_aid(card, &aidfile); } if (i >= 0) { /* * We now know PIV AID is active, test DISCOVERY object * Some CAC cards with PIV don't support DISCOVERY and return * SC_ERROR_INCORRECT_PARAMETERS. Any error other then * SC_ERROR_FILE_NOT_FOUND means we cannot use discovery * to test for active AID. */ int i7e = piv_find_discovery(card); if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) { priv->card_issues |= CI_DISCOVERY_USELESS; priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT; } } if (i < 0) { /* don't match. Does not have a PIV applet. */ sc_unlock(card); piv_finish(card); card->type = saved_type; return 0; } /* Matched, caller will use or free priv and sc_lock as needed */ priv->pstate=PIV_STATE_INIT; return 1; /* match */ } static int piv_init(sc_card_t *card) { int r = 0; piv_private_data_t * priv = NULL; sc_apdu_t apdu; unsigned long flags; unsigned long ext_flags; u8 yubico_version_buf[3]; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* continue the matching get a lock and the priv */ r = piv_match_card_continued(card); if (r != 1) { sc_log(card->ctx,"piv_match_card_continued failed"); piv_finish(card); /* tell sc_connect_card to try other drivers */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } priv = PIV_DATA(card); /* can not force the PIV driver to use non-PIV cards as tested in piv_card_match_continued */ if (!priv || card->type == -1) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); sc_log(card->ctx, "Max send = %"SC_FORMAT_LEN_SIZE_T"u recv = %"SC_FORMAT_LEN_SIZE_T"u card->type = %d", card->max_send_size, card->max_recv_size, card->type); card->cla = 0x00; if(card->name == NULL) card->name = card->driver->name; /* * Set card_issues based on card type either set by piv_match_card or by opensc.conf */ switch(card->type) { case SC_CARD_TYPE_PIV_II_NEO: case SC_CARD_TYPE_PIV_II_YUBIKEY4: sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xFD, 0x00, 0x00); apdu.lc = 0; apdu.data = NULL; apdu.datalen = 0; apdu.resp = yubico_version_buf; apdu.resplen = sizeof(yubico_version_buf); apdu.le = apdu.resplen; r = sc_transmit_apdu(card, &apdu); priv->yubico_version = (yubico_version_buf[0]<<16) | (yubico_version_buf[1] <<8) | yubico_version_buf[2]; sc_log(card->ctx, "Yubico card->type=%d, r=0x%08x version=0x%08x", card->type, r, priv->yubico_version); break; } /* * Set card_issues flags based card->type and version numbers if available. * * YubiKey NEO, Yubikey 4 and other devices with PIV applets, have compliance * issues with the NIST 800-73-3 specs. The OpenSC developers do not have * access to all the different devices or versions of the devices. * Vendor and user input is welcome on any compliance issues. * * For the Yubico devices The assumption is also made that if a bug is * fixed in a Yubico version that means it is fixed on both NEO and Yubikey 4. * * The flags CI_CANT_USE_GETDATA_FOR_STATE and CI_DISCOVERY_USELESS * may be set earlier or later then in the following code. */ switch(card->type) { case SC_CARD_TYPE_PIV_II_NEO: priv->card_issues |= CI_NO_EC384 | CI_VERIFY_630X | CI_OTHER_AID_LOSE_STATE | CI_LEAKS_FILE_NOT_FOUND | CI_NFC_EXPOSE_TOO_MUCH; if (priv->yubico_version < 0x00040302) priv->card_issues |= CI_VERIFY_LC0_FAIL; break; case SC_CARD_TYPE_PIV_II_YUBIKEY4: priv->card_issues |= CI_OTHER_AID_LOSE_STATE | CI_LEAKS_FILE_NOT_FOUND; if (priv->yubico_version < 0x00040302) priv->card_issues |= CI_VERIFY_LC0_FAIL; break; case SC_CARD_TYPE_PIV_II_HIST: priv->card_issues |= 0; break; case SC_CARD_TYPE_PIV_II_GI_DE: priv->card_issues |= CI_VERIFY_LC0_FAIL | CI_PIV_AID_LOSE_STATE | CI_OTHER_AID_LOSE_STATE;; /* TODO may need more research */ break; case SC_CARD_TYPE_PIV_II_GENERIC: priv->card_issues |= CI_VERIFY_LC0_FAIL | CI_OTHER_AID_LOSE_STATE; /* TODO may need more research */ break; default: priv->card_issues = 0; /* opensc.conf may have it wrong, continue anyway */ sc_log(card->ctx, "Unknown PIV card->type %d", card->type); card->type = SC_CARD_TYPE_PIV_II_BASE; } sc_log(card->ctx, "PIV card-type=%d card_issues=0x%08x", card->type, priv->card_issues); priv->enumtag = piv_aids[0].enumtag; /* PKCS#11 may try to generate session keys, and get confused * if SC_ALGORITHM_ONBOARD_KEY_GEN is present * piv-tool can still do this, just don't tell PKCS#11 */ flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ flags = SC_ALGORITHM_ECDSA_RAW | SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ECDSA_HASH_NONE; ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE | SC_ALGORITHM_EXT_EC_UNCOMPRESES; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); if (!(priv->card_issues & CI_NO_EC384)) _sc_card_add_ec_alg(card, 384, flags, ext_flags, NULL); /* TODO may turn off SC_CARD_CAP_ISO7816_PIN_INFO later */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; /* * 800-73-3 cards may have a history object and/or a discovery object * We want to process them now as this has information on what * keys and certs the card has and how the pin might be used. * If they fail, ignore it there are optional and introduced in * NIST 800-73-3 and NIST 800-73-2 so some older cards may * not handle the request. */ piv_process_history(card); piv_process_discovery(card); priv->pstate=PIV_STATE_NORMAL; sc_unlock(card) ; /* obtained in piv_match */ LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int piv_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); int r; piv_private_data_t * priv = PIV_DATA(card); /* may be called before piv_init has allocated priv */ if (priv) { /* need to save sw1 and sw2 if trying to determine card_state from pin_cmd */ if (priv->pin_cmd_verify) { priv->pin_cmd_verify_sw1 = sw1; priv->pin_cmd_verify_sw2 = sw2; } else { /* a command has completed and it is not verify */ /* If we are in a context_specific sequence, unlock */ if (priv->context_specific) { sc_log(card->ctx,"Clearing CONTEXT_SPECIFIC lock"); priv->context_specific = 0; sc_unlock(card); } } if (priv->card_issues & CI_VERIFY_630X) { /* Handle the Yubikey NEO or any other PIV card which returns in response to a verify * 63 0X rather than 63 CX indicate the number of remaining PIN retries. * Perhaps they misread the spec and thought 0xCX meant "clear" or "don't care", not a literal 0xC! */ if (priv->pin_cmd_verify && sw1 == 0x63U) { priv->pin_cmd_verify_sw2 |= 0xC0U; /* make it easier to test in other code */ if ((sw2 & ~0x0fU) == 0x00U) { sc_log(card->ctx, "Verification failed (remaining tries: %d)", (sw2 & 0x0f)); return SC_ERROR_PIN_CODE_INCORRECT; /* this is what the iso_check_sw returns for 63 C0 */ } } } } r = iso_drv->ops->check_sw(card, sw1, sw2); return r; } static int piv_check_protected_objects(sc_card_t *card) { int r = 0; int i; piv_private_data_t * priv = PIV_DATA(card); u8 buf[8]; /* tag of 53 with 82 xx xx will fit in 4 */ u8 * rbuf; size_t buf_len; static int protected_objects[] = {PIV_OBJ_PI, PIV_OBJ_CHF, PIV_OBJ_IRIS_IMAGE}; LOG_FUNC_CALLED(card->ctx); /* * routine only called from piv_pin_cmd after verify lc=0 did not return 90 00 * We will test for a protected object using GET DATA. * * Based on observations, of cards using the GET DATA APDU, * SC_ERROR_SECURITY_STATUS_NOT_SATISFIED means the PIN not verified, * SC_SUCCESS means PIN has been verified even if it has length 0 * SC_ERROR_FILE_NOT_FOUND (which is the bug) does not tell us anything * about the state of the PIN and we will try the next object. * * If we can't determine the security state from this process, * set card_issues CI_CANT_USE_GETDATA_FOR_STATE * and return SC_ERROR_PIN_CODE_INCORRECT * The circumvention is to add a dummy Printed Info object in the card. * so we will have an object to test. * * We save the object's number to use in the future. * */ if (priv->object_test_verify == 0) { for (i = 0; i < (int)(sizeof(protected_objects)/sizeof(int)); i++) { buf_len = sizeof(buf); priv->pin_cmd_noparse = 1; /* tell piv_general_io dont need to parse at all. */ rbuf = buf; r = piv_get_data(card, protected_objects[i], &rbuf, &buf_len); priv->pin_cmd_noparse = 0; /* TODO may need to check sw1 and sw2 to see what really happened */ if (r >= 0 || r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { /* we can use this object next time if needed */ priv->object_test_verify = protected_objects[i]; break; } } if (priv->object_test_verify == 0) { /* * none of the objects returned acceptable sw1, sw2 */ sc_log(card->ctx, "No protected objects found, setting CI_CANT_USE_GETDATA_FOR_STATE"); priv->card_issues |= CI_CANT_USE_GETDATA_FOR_STATE; r = SC_ERROR_PIN_CODE_INCORRECT; } } else { /* use the one object we found earlier. Test is security status has changed */ buf_len = sizeof(buf); priv->pin_cmd_noparse = 1; /* tell piv_general_io dont need to parse at all. */ rbuf = buf; r = piv_get_data(card, priv->object_test_verify, &rbuf, &buf_len); priv->pin_cmd_noparse = 0; } if (r == SC_ERROR_FILE_NOT_FOUND) r = SC_ERROR_PIN_CODE_INCORRECT; else if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) r = SC_ERROR_PIN_CODE_INCORRECT; else if (r > 0) r = SC_SUCCESS; sc_log(card->ctx, "object_test_verify=%d, card_issues = 0x%08x", priv->object_test_verify, priv->card_issues); LOG_FUNC_RETURN(card->ctx, r); } static int piv_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { int r = 0; piv_private_data_t * priv = PIV_DATA(card); /* Extra validation of (new) PIN during a PIN change request, to * ensure it's not outside the FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d", priv->tries_left, priv->logged_in); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } priv->pin_cmd_verify_sw1 = 0x00U; if (data->cmd == SC_PIN_CMD_GET_INFO) { /* fill in what we think it should be */ data->pin1.logged_in = priv->logged_in; data->pin1.tries_left = priv->tries_left; if (tries_left) *tries_left = priv->tries_left; /* * If called to check on the login state for a context specific login * return not logged in. Needed because of logic in e6f7373ef066 */ if (data->pin_type == SC_AC_CONTEXT_SPECIFIC) { data->pin1.logged_in = 0; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } if (priv->logged_in == SC_PIN_STATE_LOGGED_IN) { /* Avoid status requests when the user is logged in to handle NIST * 800-73-4 Part 2: * The PKI cryptographic function (see Table 4b) is protected with * a “PIN Always” or “OCC Always” access rule. In other words, the * PIN or OCC data must be submitted and verified every time * immediately before a digital signature key operation. This * ensures cardholder participation every time the private key is * used for digital signature generation */ LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } } /* * If this was for a CKU_CONTEXT_SPECFIC login, lock the card one more time. * to avoid any interference from other applications. * Sc_unlock will be called at a later time after the next card command * that should be a crypto operation. If its not then it is a error by the * calling application. */ if (data->cmd == SC_PIN_CMD_VERIFY && data->pin_type == SC_AC_CONTEXT_SPECIFIC) { priv->context_specific = 1; sc_log(card->ctx,"Starting CONTEXT_SPECIFIC verify"); sc_lock(card); } priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */ r = iso_drv->ops->pin_cmd(card, data, tries_left); priv->pin_cmd_verify = 0; /* if verify failed, release the lock */ if (data->cmd == SC_PIN_CMD_VERIFY && r < 0 && priv->context_specific) { sc_log(card->ctx,"Clearing CONTEXT_SPECIFIC"); priv->context_specific = 0; sc_unlock(card); } /* if access to applet is know to be reset by other driver we select_aid and try again */ if ( priv->card_issues & CI_OTHER_AID_LOSE_STATE && priv->pin_cmd_verify_sw1 == 0x6DU) { sc_log(card->ctx, "AID may be lost doing piv_find_aid and retry pin_cmd"); piv_find_aid(card, priv->aid_file); /* return not tested */ priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */ r = iso_drv->ops->pin_cmd(card, data, tries_left); priv->pin_cmd_verify = 0; } /* If verify worked, we are logged_in */ if (data->cmd == SC_PIN_CMD_VERIFY) { if (r >= 0) priv->logged_in = SC_PIN_STATE_LOGGED_IN; else priv->logged_in = SC_PIN_STATE_LOGGED_OUT; } /* Some cards never return 90 00 for SC_PIN_CMD_GET_INFO even if the card state is verified */ /* PR 797 has changed the return codes from pin_cmd, and added a data->pin1.logged_in flag */ if (data->cmd == SC_PIN_CMD_GET_INFO) { if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) { sc_log(card->ctx, "CI_CANT_USE_GETDATA_FOR_STATE set, assume logged_in=%d", priv->logged_in); data->pin1.logged_in = priv->logged_in; /* use what ever we saw last */ } else if (priv->card_issues & CI_VERIFY_LC0_FAIL && priv->pin_cmd_verify_sw1 == 0x63U ) { /* can not use modified return codes from iso->drv->pin_cmd */ /* try another method, looking at a protected object this may require adding one of these to NEO */ r = piv_check_protected_objects(card); if (r == SC_SUCCESS) data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; else if (r == SC_ERROR_PIN_CODE_INCORRECT) { if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) { /* we still can not determine login state */ data->pin1.logged_in = priv->logged_in; /* may have be set from SC_PIN_CMD_VERIFY */ /* TODO a reset may have logged us out. need to detect resets */ } else { data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT; } r = SC_SUCCESS; } } priv->logged_in = data->pin1.logged_in; priv->tries_left = data->pin1.tries_left; } sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d",priv->tries_left, priv->logged_in); LOG_FUNC_RETURN(card->ctx, r); } static int piv_logout(sc_card_t *card) { int r = SC_ERROR_NOT_SUPPORTED; /* TODO Some PIV cards may support a logout */ /* piv_private_data_t * priv = PIV_DATA(card); */ LOG_FUNC_CALLED(card->ctx); /* TODO 800-73-3 does not define a logout, 800-73-4 does */ LOG_FUNC_RETURN(card->ctx, r); } /* * Called when a sc_lock gets a reader lock and PCSC SCardBeginTransaction * If SCardBeginTransaction may pass back tha a card reset was seen since * the last transaction completed. * There may have been one or more resets, by other card drivers in different * processes, and they may have taken action already * and changed the AID and or may have sent a VERIFY with PIN * So test the state of the card. * this is very similar to what the piv_match routine does, */ static int piv_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = 0; u8 temp[256]; size_t templen = sizeof(temp); piv_private_data_t * priv = PIV_DATA(card); /* may be null */ SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* We have a PCSC transaction and sc_lock */ if (priv == NULL || priv->pstate == PIV_STATE_MATCH) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, priv ? "PIV_STATE_MATCH" : "priv==NULL"); r = 0; /* do nothing, piv_match will take care of it */ goto err; } /* make sure our application is active */ /* first see if AID is active AID by reading discovery object '7E' */ /* If not try selecting AID */ /* but if card does not support DISCOVERY object we can not use it */ if (priv->card_issues & CI_DISCOVERY_USELESS) { r = SC_ERROR_NO_CARD_SUPPORT; } else { r = piv_find_discovery(card); } if (r < 0) { if (was_reset > 0 || !(priv->card_issues & CI_PIV_AID_LOSE_STATE)) { r = piv_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, temp, &templen); } else { r = 0; /* cant do anything with this card, hope there was no interference */ } } if (r < 0) /* bad error return will show up in sc_lock as error*/ goto err; if (was_reset > 0) priv->logged_in = SC_PIN_STATE_UNKNOWN; r = 0; err: LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); piv_ops = *iso_drv->ops; piv_ops.match_card = piv_match_card; piv_ops.init = piv_init; piv_ops.finish = piv_finish; piv_ops.select_file = piv_select_file; /* must use get/put, could emulate? */ piv_ops.get_challenge = piv_get_challenge; piv_ops.logout = piv_logout; piv_ops.read_binary = piv_read_binary; piv_ops.write_binary = piv_write_binary; piv_ops.set_security_env = piv_set_security_env; piv_ops.restore_security_env = piv_restore_security_env; piv_ops.compute_signature = piv_compute_signature; piv_ops.decipher = piv_decipher; piv_ops.check_sw = piv_check_sw; piv_ops.card_ctl = piv_card_ctl; piv_ops.pin_cmd = piv_pin_cmd; piv_ops.card_reader_lock_obtained = piv_card_reader_lock_obtained; return &piv_drv; } #if 1 struct sc_card_driver * sc_get_piv_driver(void) { return sc_get_driver(); } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_11
crossvul-cpp_data_bad_2442_0
/* * base64.c * base64 encode/decode implementation * * Copyright (c) 2011 Nikias Bassen, All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <string.h> #include "base64.h" static const char base64_str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char base64_pad = '='; static const signed char base64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; size_t base64encode(char *outbuf, const unsigned char *buf, size_t size) { if (!outbuf || !buf || (size <= 0)) { return 0; } size_t n = 0; size_t m = 0; unsigned char input[3]; unsigned int output[4]; while (n < size) { input[0] = buf[n]; input[1] = (n+1 < size) ? buf[n+1] : 0; input[2] = (n+2 < size) ? buf[n+2] : 0; output[0] = input[0] >> 2; output[1] = ((input[0] & 3) << 4) + (input[1] >> 4); output[2] = ((input[1] & 15) << 2) + (input[2] >> 6); output[3] = input[2] & 63; outbuf[m++] = base64_str[(int)output[0]]; outbuf[m++] = base64_str[(int)output[1]]; outbuf[m++] = (n+1 < size) ? base64_str[(int)output[2]] : base64_pad; outbuf[m++] = (n+2 < size) ? base64_str[(int)output[3]] : base64_pad; n+=3; } outbuf[m] = 0; // 0-termination! return m; } static int base64decode_block(unsigned char *target, const char *data, size_t data_size) { int w1,w2,w3,w4; int i; size_t n; if (!data || (data_size <= 0)) { return 0; } n = 0; i = 0; while (n < data_size-3) { w1 = base64_table[(int)data[n]]; w2 = base64_table[(int)data[n+1]]; w3 = base64_table[(int)data[n+2]]; w4 = base64_table[(int)data[n+3]]; if (w2 >= 0) { target[i++] = (char)((w1*4 + (w2 >> 4)) & 255); } if (w3 >= 0) { target[i++] = (char)((w2*16 + (w3 >> 2)) & 255); } if (w4 >= 0) { target[i++] = (char)((w3*64 + w4) & 255); } n+=4; } return i; } unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2442_0
crossvul-cpp_data_bad_2728_0
/* * Copyright (c) 1998-2006 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: IEEE 802.1ag Connectivity Fault Management (CFM) protocols printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include "netdissect.h" #include "extract.h" #include "ether.h" #include "addrtoname.h" #include "oui.h" #include "af.h" struct cfm_common_header_t { uint8_t mdlevel_version; uint8_t opcode; uint8_t flags; uint8_t first_tlv_offset; }; #define CFM_VERSION 0 #define CFM_EXTRACT_VERSION(x) (((x)&0x1f)) #define CFM_EXTRACT_MD_LEVEL(x) (((x)&0xe0)>>5) #define CFM_OPCODE_CCM 1 #define CFM_OPCODE_LBR 2 #define CFM_OPCODE_LBM 3 #define CFM_OPCODE_LTR 4 #define CFM_OPCODE_LTM 5 static const struct tok cfm_opcode_values[] = { { CFM_OPCODE_CCM, "Continuity Check Message"}, { CFM_OPCODE_LBR, "Loopback Reply"}, { CFM_OPCODE_LBM, "Loopback Message"}, { CFM_OPCODE_LTR, "Linktrace Reply"}, { CFM_OPCODE_LTM, "Linktrace Message"}, { 0, NULL} }; /* * Message Formats. */ struct cfm_ccm_t { uint8_t sequence[4]; uint8_t ma_epi[2]; uint8_t names[48]; uint8_t itu_t_y_1731[16]; }; /* * Timer Bases for the CCM Interval field. * Expressed in units of seconds. */ static const float ccm_interval_base[8] = {0, 0.003333, 0.01, 0.1, 1, 10, 60, 600}; #define CCM_INTERVAL_MIN_MULTIPLIER 3.25 #define CCM_INTERVAL_MAX_MULTIPLIER 3.5 #define CFM_CCM_RDI_FLAG 0x80 #define CFM_EXTRACT_CCM_INTERVAL(x) (((x)&0x07)) #define CFM_CCM_MD_FORMAT_8021 0 #define CFM_CCM_MD_FORMAT_NONE 1 #define CFM_CCM_MD_FORMAT_DNS 2 #define CFM_CCM_MD_FORMAT_MAC 3 #define CFM_CCM_MD_FORMAT_CHAR 4 static const struct tok cfm_md_nameformat_values[] = { { CFM_CCM_MD_FORMAT_8021, "IEEE 802.1"}, { CFM_CCM_MD_FORMAT_NONE, "No MD Name present"}, { CFM_CCM_MD_FORMAT_DNS, "DNS string"}, { CFM_CCM_MD_FORMAT_MAC, "MAC + 16Bit Integer"}, { CFM_CCM_MD_FORMAT_CHAR, "Character string"}, { 0, NULL} }; #define CFM_CCM_MA_FORMAT_8021 0 #define CFM_CCM_MA_FORMAT_VID 1 #define CFM_CCM_MA_FORMAT_CHAR 2 #define CFM_CCM_MA_FORMAT_INT 3 #define CFM_CCM_MA_FORMAT_VPN 4 static const struct tok cfm_ma_nameformat_values[] = { { CFM_CCM_MA_FORMAT_8021, "IEEE 802.1"}, { CFM_CCM_MA_FORMAT_VID, "Primary VID"}, { CFM_CCM_MA_FORMAT_CHAR, "Character string"}, { CFM_CCM_MA_FORMAT_INT, "16Bit Integer"}, { CFM_CCM_MA_FORMAT_VPN, "RFC2685 VPN-ID"}, { 0, NULL} }; struct cfm_lbm_t { uint8_t transaction_id[4]; }; struct cfm_ltm_t { uint8_t transaction_id[4]; uint8_t ttl; uint8_t original_mac[ETHER_ADDR_LEN]; uint8_t target_mac[ETHER_ADDR_LEN]; }; static const struct tok cfm_ltm_flag_values[] = { { 0x80, "Use Forwarding-DB only"}, { 0, NULL} }; struct cfm_ltr_t { uint8_t transaction_id[4]; uint8_t ttl; uint8_t replay_action; }; static const struct tok cfm_ltr_flag_values[] = { { 0x80, "UseFDB Only"}, { 0x40, "FwdYes"}, { 0x20, "Terminal MEP"}, { 0, NULL} }; static const struct tok cfm_ltr_replay_action_values[] = { { 1, "Exact Match"}, { 2, "Filtering DB"}, { 3, "MIP CCM DB"}, { 0, NULL} }; #define CFM_TLV_END 0 #define CFM_TLV_SENDER_ID 1 #define CFM_TLV_PORT_STATUS 2 #define CFM_TLV_INTERFACE_STATUS 3 #define CFM_TLV_DATA 4 #define CFM_TLV_REPLY_INGRESS 5 #define CFM_TLV_REPLY_EGRESS 6 #define CFM_TLV_PRIVATE 31 static const struct tok cfm_tlv_values[] = { { CFM_TLV_END, "End"}, { CFM_TLV_SENDER_ID, "Sender ID"}, { CFM_TLV_PORT_STATUS, "Port status"}, { CFM_TLV_INTERFACE_STATUS, "Interface status"}, { CFM_TLV_DATA, "Data"}, { CFM_TLV_REPLY_INGRESS, "Reply Ingress"}, { CFM_TLV_REPLY_EGRESS, "Reply Egress"}, { CFM_TLV_PRIVATE, "Organization Specific"}, { 0, NULL} }; /* * TLVs */ struct cfm_tlv_header_t { uint8_t type; uint8_t length[2]; }; /* FIXME define TLV formats */ static const struct tok cfm_tlv_port_status_values[] = { { 1, "Blocked"}, { 2, "Up"}, { 0, NULL} }; static const struct tok cfm_tlv_interface_status_values[] = { { 1, "Up"}, { 2, "Down"}, { 3, "Testing"}, { 5, "Dormant"}, { 6, "not present"}, { 7, "lower Layer down"}, { 0, NULL} }; #define CFM_CHASSIS_ID_CHASSIS_COMPONENT 1 #define CFM_CHASSIS_ID_INTERFACE_ALIAS 2 #define CFM_CHASSIS_ID_PORT_COMPONENT 3 #define CFM_CHASSIS_ID_MAC_ADDRESS 4 #define CFM_CHASSIS_ID_NETWORK_ADDRESS 5 #define CFM_CHASSIS_ID_INTERFACE_NAME 6 #define CFM_CHASSIS_ID_LOCAL 7 static const struct tok cfm_tlv_senderid_chassisid_values[] = { { 0, "Reserved"}, { CFM_CHASSIS_ID_CHASSIS_COMPONENT, "Chassis component"}, { CFM_CHASSIS_ID_INTERFACE_ALIAS, "Interface alias"}, { CFM_CHASSIS_ID_PORT_COMPONENT, "Port component"}, { CFM_CHASSIS_ID_MAC_ADDRESS, "MAC address"}, { CFM_CHASSIS_ID_NETWORK_ADDRESS, "Network address"}, { CFM_CHASSIS_ID_INTERFACE_NAME, "Interface name"}, { CFM_CHASSIS_ID_LOCAL, "Locally assigned"}, { 0, NULL} }; static int cfm_network_addr_print(netdissect_options *ndo, register const u_char *tptr) { u_int network_addr_type; u_int hexdump = FALSE; /* * Altough AFIs are tpically 2 octects wide, * 802.1ab specifies that this field width * is only once octet */ network_addr_type = *tptr; ND_PRINT((ndo, "\n\t Network Address Type %s (%u)", tok2str(af_values, "Unknown", network_addr_type), network_addr_type)); /* * Resolve the passed in Address. */ switch(network_addr_type) { case AFNUM_INET: ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1))); break; case AFNUM_INET6: ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1))); break; default: hexdump = TRUE; break; } return hexdump; } void cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, "CFMv%u not supported, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, "CFMv%u %s, MD Level %u, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, "unknown (%u)", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, "\n\tFirst TLV offset %u", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, " (too large, must be <= %u)", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, " (too small 1, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, ", Flags [CCM Interval %u%s]", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? ", RDI" : "")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, "\n\t CCM Interval %.3fs" ", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, "\n\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, "\n\t MD Name Format %s (%u), MD Name length %u", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, "\n\t MD Name: ")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, "\n\t MAC (length invalid)")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, "\n\t ", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, "\n\t MD Name Format %s (%u)", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, "\n\t MA Name-Format %s (%u), MA name length %u", tok2str(cfm_ma_nameformat_values, "Unknown", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, "\n\t MA Name: ")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, "\n\t ", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, " (too small 4, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltm_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, "\n\t Original-MAC %s, Target-MAC %s", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, " (too small 5, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltr_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, "\n\t Replay-Action %s (%u)", tok2str(cfm_ltr_replay_action_values, "Unknown", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, "\n\t ", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, "\n\t%s TLV (0x%02x)", tok2str(cfm_tlv_values, "Unknown", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is "Not present if the Type field is 0." */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, ", length %u", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_port_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_interface_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, " (too short, must be >= 4)")); return; } ND_PRINT((ndo, ", Vendor: %s (%u), Sub-Type %u", tok2str(oui_values,"Unknown", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } /* * Get the Chassis ID length and check it. */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Chassis-ID Type %s (%u), Chassis-ID length %u", tok2str(cfm_tlv_senderid_chassisid_values, "Unknown", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, "\n\t ", cfm_tlv_len); tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, "\n\t\t packet is too short")); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2728_0
crossvul-cpp_data_bad_3254_2
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * 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 module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/ptp_classify.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <linux/xattr.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> #include <net/busy_poll.h> #include <linux/errqueue.h> #ifdef CONFIG_NET_RX_BUSY_POLL unsigned int sysctl_net_busy_read __read_mostly; unsigned int sysctl_net_busy_poll __read_mostly; #endif static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to); static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .read_iter = sock_read_iter, .write_iter = sock_write_iter, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; BUG_ON(klen > sizeof(struct sockaddr_storage)); err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; wq->flags = 0; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static void init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT), init_once); BUG_ON(sock_inode_cachep == NULL); } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", d_inode(dentry)->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static int sockfs_xattr_get(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, void *value, size_t size) { if (value) { if (dentry->d_name.len + 1 > size) return -ERANGE; memcpy(value, dentry->d_name.name, dentry->d_name.len + 1); } return dentry->d_name.len + 1; } #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname" #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX) #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1) static const struct xattr_handler sockfs_xattr_handler = { .name = XATTR_NAME_SOCKPROTONAME, .get = sockfs_xattr_get, }; static int sockfs_security_xattr_set(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, const void *value, size_t size, int flags) { /* Handled by LSM. */ return -EAGAIN; } static const struct xattr_handler sockfs_security_xattr_handler = { .prefix = XATTR_SECURITY_PREFIX, .set = sockfs_security_xattr_set, }; static const struct xattr_handler *sockfs_xattr_handlers[] = { &sockfs_xattr_handler, &sockfs_security_xattr_handler, NULL }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo_xattr(fs_type, "socket:", &sockfs_ops, sockfs_xattr_handlers, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname) { struct qstr name = { .name = "" }; struct path path; struct file *file; if (dname) { name.name = dname; name.len = strlen(name.name); } else if (sock->sk) { name.name = sock->sk->sk_prot_creator->name; name.len = strlen(name.name); } path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) return ERR_PTR(-ENOMEM); path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (IS_ERR(file)) { /* drop dentry, keep inode */ ihold(d_inode(path.dentry)); path_put(&path); return file; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->private_data = sock; return file; } EXPORT_SYMBOL(sock_alloc_file); static int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; newfile = sock_alloc_file(sock, flags, NULL); if (likely(!IS_ERR(newfile))) { fd_install(fd, newfile); return fd; } put_unused_fd(fd); return PTR_ERR(newfile); } struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } EXPORT_SYMBOL(sock_from_file); /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct fd f = fdget(fd); struct socket *sock; *err = -EBADF; if (f.file) { sock = sock_from_file(f.file, err); if (likely(sock)) { *fput_needed = f.flags; return sock; } fdput(f); } return NULL; } static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer, size_t size) { ssize_t len; ssize_t used = 0; len = security_inode_listsecurity(d_inode(dentry), buffer, size); if (len < 0) return len; used += len; if (buffer) { if (size < used) return -ERANGE; buffer += len; } len = (XATTR_NAME_SOCKPROTONAME_LEN + 1); used += len; if (buffer) { if (size < used) return -ERANGE; memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len); buffer += len; } return used; } static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr) { int err = simple_setattr(dentry, iattr); if (!err && (iattr->ia_valid & ATTR_UID)) { struct socket *sock = SOCKET_I(d_inode(dentry)); sock->sk->sk_uid = iattr->ia_uid; } return err; } static const struct inode_operations sockfs_inode_ops = { .listxattr = sockfs_listxattr, .setattr = sockfs_setattr, }; /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_op = &sockfs_inode_ops; this_cpu_add(sockets_in_use, 1); return sock; } EXPORT_SYMBOL(sock_alloc); /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); this_cpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags) { u8 flags = *tx_flags; if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE) flags |= SKBTX_HW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE) flags |= SKBTX_SW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SCHED) flags |= SKBTX_SCHED_TSTAMP; *tx_flags = flags; } EXPORT_SYMBOL(__sock_tx_timestamp); static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg) { int ret = sock->ops->sendmsg(sock, msg, msg_data_left(msg)); BUG_ON(ret == -EIOCBQUEUED); return ret; } int sock_sendmsg(struct socket *sock, struct msghdr *msg) { int err = security_socket_sendmsg(sock, msg, msg_data_left(msg)); return err ?: sock_sendmsg_nosec(sock, msg); } EXPORT_SYMBOL(sock_sendmsg); int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { iov_iter_kvec(&msg->msg_iter, WRITE | ITER_KVEC, vec, num, size); return sock_sendmsg(sock, msg); } EXPORT_SYMBOL(kernel_sendmsg); static bool skb_is_err_queue(const struct sk_buff *skb) { /* pkt_type of skbs enqueued on the error queue are set to * PACKET_OUTGOING in skb_set_err_queue(). This is only safe to do * in recvmsg, since skbs received on a local socket will never * have a pkt_type of PACKET_OUTGOING. */ return skb->pkt_type == PACKET_OUTGOING; } /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int ack; if (!sock_flag(sk, SOCK_WIFI_STATUS)) return; if (!skb->wifi_acked_valid) return; ack = skb->wifi_acked; put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack); } EXPORT_SYMBOL_GPL(__sock_recv_wifi_status); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, int flags) { return sock->ops->recvmsg(sock, msg, msg_data_left(msg), flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags) { int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags); return err ?: sock_recvmsg_nosec(sock, msg, flags); } EXPORT_SYMBOL(sock_recvmsg); /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; iov_iter_kvec(&msg->msg_iter, READ | ITER_KVEC, vec, num, size); set_fs(KERNEL_DS); result = sock_recvmsg(sock, msg, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *to, .msg_iocb = iocb}; ssize_t res; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (iocb->ki_pos != 0) return -ESPIPE; if (!iov_iter_count(to)) /* Match SYS5 behaviour */ return 0; res = sock_recvmsg(sock, &msg, msg.msg_flags); *to = msg.msg_iter; return res; } static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *from, .msg_iocb = iocb}; ssize_t res; if (iocb->ki_pos != 0) return -ESPIPE; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (sock->type == SOCK_SEQPACKET) msg.msg_flags |= MSG_EOR; res = sock_sendmsg(sock, &msg); *from = msg.msg_iter; return res; } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static struct ns_common *get_net_ns(struct ns_common *ns) { return &get_net(container_of(ns, struct net, ns))->ns; } static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; f_setown(sock->file, pid, 1); err = 0; break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; case SIOCGSKNS: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) break; err = open_related_ns(&net->ns, get_net_ns); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { unsigned int busy_flag = 0; struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; if (sk_can_busy_loop(sock->sk)) { /* this socket can poll_ll so tell the system call */ busy_flag = POLL_BUSY_LOOP; /* once, only if requested by syscall */ if (wait && (wait->_key & POLL_BUSY_LOOP)) sk_busy_loop(sock->sk, 1); } return busy_flag | sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, lockdep_sock_is_held(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under rcu_lock */ int sock_wake_async(struct socket_wq *wq, int how, int band) { if (!wq || !wq->fasync_list) return -1; switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { net_warn_ratelimited("socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res) { return __sock_create(net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = get_unused_fd_flags(flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = get_unused_fd_flags(flags); if (unlikely(fd2 < 0)) { err = fd2; goto out_put_unused_1; } newfile1 = sock_alloc_file(sock1, flags, NULL); if (IS_ERR(newfile1)) { err = PTR_ERR(newfile1); goto out_put_unused_both; } newfile2 = sock_alloc_file(sock2, flags, NULL); if (IS_ERR(newfile2)) { err = PTR_ERR(newfile2); goto out_fput_1; } err = put_user(fd1, &usockvec[0]); if (err) goto out_fput_both; err = put_user(fd2, &usockvec[1]); if (err) goto out_fput_both; audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ return 0; out_fput_both: fput(newfile2); fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); goto out; out_fput_1: fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); sock_release(sock2); goto out; out_put_unused_both: put_unused_fd(fd2); out_put_unused_1: put_unused_fd(fd1); out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, &address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = get_unused_fd_flags(flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name); if (IS_ERR(newfile)) { err = PTR_ERR(newfile); put_unused_fd(newfd); sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags, false); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user(&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, &address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; err = import_single_range(WRITE, buff, len, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_name = NULL; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned int, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; err = import_single_range(READ, ubuf, size, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; msg.msg_iocb = NULL; msg.msg_flags = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static int copy_msghdr_from_user(struct msghdr *kmsg, struct user_msghdr __user *umsg, struct sockaddr __user **save_addr, struct iovec **iov) { struct sockaddr __user *uaddr; struct iovec __user *uiov; size_t nr_segs; ssize_t err; if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) || __get_user(uaddr, &umsg->msg_name) || __get_user(kmsg->msg_namelen, &umsg->msg_namelen) || __get_user(uiov, &umsg->msg_iov) || __get_user(nr_segs, &umsg->msg_iovlen) || __get_user(kmsg->msg_control, &umsg->msg_control) || __get_user(kmsg->msg_controllen, &umsg->msg_controllen) || __get_user(kmsg->msg_flags, &umsg->msg_flags)) return -EFAULT; if (!uaddr) kmsg->msg_namelen = 0; if (kmsg->msg_namelen < 0) return -EINVAL; if (kmsg->msg_namelen > sizeof(struct sockaddr_storage)) kmsg->msg_namelen = sizeof(struct sockaddr_storage); if (save_addr) *save_addr = uaddr; if (uaddr && kmsg->msg_namelen) { if (!save_addr) { err = move_addr_to_kernel(uaddr, kmsg->msg_namelen, kmsg->msg_name); if (err < 0) return err; } } else { kmsg->msg_name = NULL; kmsg->msg_namelen = 0; } if (nr_segs > UIO_MAXIOV) return -EMSGSIZE; kmsg->msg_iocb = NULL; return import_iovec(save_addr ? READ : WRITE, uiov, nr_segs, UIO_FASTIOV, iov, &kmsg->msg_iter); } static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, struct used_address *used_address, unsigned int allowed_msghdr_flags) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __aligned(sizeof(__kernel_size_t)); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int ctl_len; ssize_t err; msg_sys->msg_name = &address; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov); else err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov); if (err < 0) return err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; flags |= (msg_sys->msg_flags & allowed_msghdr_flags); ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { BUILD_BUG_ON(sizeof(struct cmsghdr) != CMSG_ALIGN(sizeof(struct cmsghdr))); if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys); goto out_freectl; } err = sock_sendmsg(sock, msg_sys); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: kfree(iov); return err; } /* * BSD sendmsg interface */ long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmsg(fd, msg, flags); } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; unsigned int oflags = flags; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; flags |= MSG_BATCH; while (datagrams < vlen) { if (datagrams == vlen - 1) flags = oflags; if (MSG_CMSG_COMPAT & flags) { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; if (msg_data_left(&msg_sys)) break; cond_resched(); } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int len; ssize_t err; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len = COMPAT_NAMELEN(msg); msg_sys->msg_name = &addr; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, &uaddr, &iov); else err = copy_msghdr_from_user(msg_sys, msg, &uaddr, &iov); if (err < 0) return err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: kfree(iov); return err; } /* * BSD recvmsg interface */ long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_recvmsg(fd, msg, flags); } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec64 end_time; struct timespec64 timeout64; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) { datagrams = err; goto out_put; } entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts64(&timeout64); *timeout = timespec64_to_timespec( timespec64_sub(end_time, timeout64)); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; cond_resched(); } if (err == 0) goto out_put; if (datagrams == 0) { datagrams = err; goto out_put; } /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } out_put: fput_light(sock->file, fput_needed); return datagrams; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[AUDITSC_ARGS]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); if (err) return err; a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family corresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); pr_info("NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); RCU_INIT_POINTER(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); pr_info("NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize the network sysctl infrastructure. */ err = net_sysctl_init(); if (err) goto out; /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER err = netfilter_init(); if (err) goto out; #endif ptp_classifier_init(); out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) err = compat_put_timeval(&ktv, up); return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; memset(&ifc, 0, sizeof(ifc)); if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: case ETHTOOL_SRXCLSRLINS: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void __user *)(&rxnfc->fs.m_ext + 1) - (void __user *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void __user *)(&rxnfc->fs.location + 1) - (void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void __user *)(&rxnfc->fs.m_ext + 1) - (const void __user *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void __user *)(&rxnfc->fs.location + 1) - (const void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; mm_segment_t old_fs; int err; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; default: return -ENOIOCTLCMD; } } /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */ static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= get_user(r4.rt_window, &(ur4->rt_window)); ret |= get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return compat_ifr_data_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCSHWTSTAMP: case SIOCGHWTSTAMP: return compat_ifr_data_ioctl(net, cmd, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: case SIOCGSKNS: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags, true); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3254_2
crossvul-cpp_data_bad_2676_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Network File System (NFS) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "nfs.h" #include "nfsfh.h" #include "ip.h" #include "ip6.h" #include "rpc_auth.h" #include "rpc_msg.h" static const char tstr[] = " [|nfs]"; static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int); static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *); static int xid_map_find(const struct sunrpc_msg *, const u_char *, uint32_t *, uint32_t *); static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int); static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int); /* * Mapping of old NFS Version 2 RPC numbers to generic numbers. */ static uint32_t nfsv3_procid[NFS_NPROCS] = { NFSPROC_NULL, NFSPROC_GETATTR, NFSPROC_SETATTR, NFSPROC_NOOP, NFSPROC_LOOKUP, NFSPROC_READLINK, NFSPROC_READ, NFSPROC_NOOP, NFSPROC_WRITE, NFSPROC_CREATE, NFSPROC_REMOVE, NFSPROC_RENAME, NFSPROC_LINK, NFSPROC_SYMLINK, NFSPROC_MKDIR, NFSPROC_RMDIR, NFSPROC_READDIR, NFSPROC_FSSTAT, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP }; static const struct tok nfsproc_str[] = { { NFSPROC_NOOP, "nop" }, { NFSPROC_NULL, "null" }, { NFSPROC_GETATTR, "getattr" }, { NFSPROC_SETATTR, "setattr" }, { NFSPROC_LOOKUP, "lookup" }, { NFSPROC_ACCESS, "access" }, { NFSPROC_READLINK, "readlink" }, { NFSPROC_READ, "read" }, { NFSPROC_WRITE, "write" }, { NFSPROC_CREATE, "create" }, { NFSPROC_MKDIR, "mkdir" }, { NFSPROC_SYMLINK, "symlink" }, { NFSPROC_MKNOD, "mknod" }, { NFSPROC_REMOVE, "remove" }, { NFSPROC_RMDIR, "rmdir" }, { NFSPROC_RENAME, "rename" }, { NFSPROC_LINK, "link" }, { NFSPROC_READDIR, "readdir" }, { NFSPROC_READDIRPLUS, "readdirplus" }, { NFSPROC_FSSTAT, "fsstat" }, { NFSPROC_FSINFO, "fsinfo" }, { NFSPROC_PATHCONF, "pathconf" }, { NFSPROC_COMMIT, "commit" }, { 0, NULL } }; /* * NFS V2 and V3 status values. * * Some of these come from the RFCs for NFS V2 and V3, with the message * strings taken from the FreeBSD C library "errlst.c". * * Others are errors that are not in the RFC but that I suspect some * NFS servers could return; the values are FreeBSD errno values, as * the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS * was primarily BSD-derived. */ static const struct tok status2str[] = { { 1, "Operation not permitted" }, /* EPERM */ { 2, "No such file or directory" }, /* ENOENT */ { 5, "Input/output error" }, /* EIO */ { 6, "Device not configured" }, /* ENXIO */ { 11, "Resource deadlock avoided" }, /* EDEADLK */ { 12, "Cannot allocate memory" }, /* ENOMEM */ { 13, "Permission denied" }, /* EACCES */ { 17, "File exists" }, /* EEXIST */ { 18, "Cross-device link" }, /* EXDEV */ { 19, "Operation not supported by device" }, /* ENODEV */ { 20, "Not a directory" }, /* ENOTDIR */ { 21, "Is a directory" }, /* EISDIR */ { 22, "Invalid argument" }, /* EINVAL */ { 26, "Text file busy" }, /* ETXTBSY */ { 27, "File too large" }, /* EFBIG */ { 28, "No space left on device" }, /* ENOSPC */ { 30, "Read-only file system" }, /* EROFS */ { 31, "Too many links" }, /* EMLINK */ { 45, "Operation not supported" }, /* EOPNOTSUPP */ { 62, "Too many levels of symbolic links" }, /* ELOOP */ { 63, "File name too long" }, /* ENAMETOOLONG */ { 66, "Directory not empty" }, /* ENOTEMPTY */ { 69, "Disc quota exceeded" }, /* EDQUOT */ { 70, "Stale NFS file handle" }, /* ESTALE */ { 71, "Too many levels of remote in path" }, /* EREMOTE */ { 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */ { 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */ { 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */ { 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */ { 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */ { 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */ { 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */ { 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */ { 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */ { 0, NULL } }; static const struct tok nfsv3_writemodes[] = { { 0, "unstable" }, { 1, "datasync" }, { 2, "filesync" }, { 0, NULL } }; static const struct tok type2str[] = { { NFNON, "NON" }, { NFREG, "REG" }, { NFDIR, "DIR" }, { NFBLK, "BLK" }, { NFCHR, "CHR" }, { NFLNK, "LNK" }, { NFFIFO, "FIFO" }, { 0, NULL } }; static const struct tok sunrpc_auth_str[] = { { SUNRPC_AUTH_OK, "OK" }, { SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" }, { SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" }, { SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" }, { SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" }, { SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" }, { SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" }, { SUNRPC_AUTH_FAILED, "Unknown failure" }, { 0, NULL } }; static const struct tok sunrpc_str[] = { { SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" }, { SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" }, { SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" }, { SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" }, { SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" }, { 0, NULL } }; static void print_nfsaddr(netdissect_options *ndo, const u_char *bp, const char *s, const char *d) { const struct ip *ip; const struct ip6_hdr *ip6; char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN]; srcaddr[0] = dstaddr[0] = '\0'; switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr)); strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr)); break; case 6: ip6 = (const struct ip6_hdr *)bp; strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src), sizeof(srcaddr)); strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst), sizeof(dstaddr)); break; default: strlcpy(srcaddr, "?", sizeof(srcaddr)); strlcpy(dstaddr, "?", sizeof(dstaddr)); break; } ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d)); } static const uint32_t * parse_sattr3(netdissect_options *ndo, const uint32_t *dp, struct nfsv3_sattr *sa3) { ND_TCHECK(dp[0]); sa3->sa_modeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_modeset) { ND_TCHECK(dp[0]); sa3->sa_mode = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_uidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_uidset) { ND_TCHECK(dp[0]); sa3->sa_uid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_gidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_gidset) { ND_TCHECK(dp[0]); sa3->sa_gid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_sizeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_sizeset) { ND_TCHECK(dp[0]); sa3->sa_size = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_atimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_mtimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } return dp; trunc: return NULL; } static int nfserr; /* true if we error rather than trunc */ static void print_sattr3(netdissect_options *ndo, const struct nfsv3_sattr *sa3, int verbose) { if (sa3->sa_modeset) ND_PRINT((ndo, " mode %o", sa3->sa_mode)); if (sa3->sa_uidset) ND_PRINT((ndo, " uid %u", sa3->sa_uid)); if (sa3->sa_gidset) ND_PRINT((ndo, " gid %u", sa3->sa_gid)); if (verbose > 1) { if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec, sa3->sa_atime.nfsv3_nsec)); if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec, sa3->sa_mtime.nfsv3_nsec)); } } void nfsreply_print(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; char srcid[20], dstid[20]; /*fits 32bit*/ nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_xid); if (!ndo->ndo_nflag) { strlcpy(srcid, "nfs", sizeof(srcid)); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } else { snprintf(srcid, sizeof(srcid), "%u", NFS_PORT); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } print_nfsaddr(ndo, bp2, srcid, dstid); nfsreply_print_noaddr(ndo, bp, length, bp2); return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } void nfsreply_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; uint32_t proc, vers, reply_stat; enum sunrpc_reject_stat rstat; uint32_t rlow; uint32_t rhigh; enum sunrpc_auth_stat rwhy; nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_reply.rp_stat); reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat); switch (reply_stat) { case SUNRPC_MSG_ACCEPTED: ND_PRINT((ndo, "reply ok %u", length)); if (xid_map_find(rp, bp2, &proc, &vers) >= 0) interp_reply(ndo, rp, proc, vers, length); break; case SUNRPC_MSG_DENIED: ND_PRINT((ndo, "reply ERR %u: ", length)); ND_TCHECK(rp->rm_reply.rp_reject.rj_stat); rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat); switch (rstat) { case SUNRPC_RPC_MISMATCH: ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high); rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low); rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high); ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh)); break; case SUNRPC_AUTH_ERROR: ND_TCHECK(rp->rm_reply.rp_reject.rj_why); rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why); ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy))); break; default: ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat)); break; } break; default: ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length)); break; } return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Return a pointer to the first file handle in the packet. * If the packet was truncated, return 0. */ static const uint32_t * parsereq(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; register u_int len; /* * find the start of the req data (if we captured it) */ dp = (const uint32_t *)&rp->rm_call.cb_cred; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK2(dp[0], 0); return (dp); } } trunc: return (NULL); } /* * Print out an NFS file handle and return a pointer to following word. * If packet was truncated, return 0. */ static const uint32_t * parsefh(netdissect_options *ndo, register const uint32_t *dp, int v3) { u_int len; if (v3) { ND_TCHECK(dp[0]); len = EXTRACT_32BITS(dp) / 4; dp++; } else len = NFSX_V2FH / 4; if (ND_TTEST2(*dp, len * sizeof(*dp))) { nfs_printfh(ndo, dp, len); return (dp + len); } trunc: return (NULL); } /* * Print out a file name and return pointer to 32-bit word past it. * If packet was truncated, return 0. */ static const uint32_t * parsefn(netdissect_options *ndo, register const uint32_t *dp) { register uint32_t len; register const u_char *cp; /* Bail if we don't have the string length */ ND_TCHECK(*dp); /* Fetch string length; convert to host order */ len = *dp++; NTOHL(len); ND_TCHECK2(*dp, ((len + 3) & ~3)); cp = (const u_char *)dp; /* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */ dp += ((len + 3) & ~3) / sizeof(*dp); ND_PRINT((ndo, "\"")); if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); return (dp); trunc: return NULL; } /* * Print out file handle and file name. * Return pointer to 32-bit word past file name. * If packet was truncated (or there was some other error), return 0. */ static const uint32_t * parsefhn(netdissect_options *ndo, register const uint32_t *dp, int v3) { dp = parsefh(ndo, dp, v3); if (dp == NULL) return (NULL); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp)); } void nfsreq_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; register const uint32_t *dp; nfs_type type; int v3; uint32_t proc; uint32_t access_flags; struct nfsv3_sattr sa3; ND_PRINT((ndo, "%d", length)); nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */ goto trunc; v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3); proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: case NFSPROC_SETATTR: case NFSPROC_READLINK: case NFSPROC_FSSTAT: case NFSPROC_FSINFO: case NFSPROC_PATHCONF: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefh(ndo, dp, v3) != NULL) return; break; case NFSPROC_LOOKUP: case NFSPROC_CREATE: case NFSPROC_MKDIR: case NFSPROC_REMOVE: case NFSPROC_RMDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefhn(ndo, dp, v3) != NULL) return; break; case NFSPROC_ACCESS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[0]); access_flags = EXTRACT_32BITS(&dp[0]); if (access_flags & ~NFSV3ACCESS_FULL) { /* NFSV3ACCESS definitions aren't up to date */ ND_PRINT((ndo, " %04x", access_flags)); } else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) { ND_PRINT((ndo, " NFS_ACCESS_FULL")); } else { char separator = ' '; if (access_flags & NFSV3ACCESS_READ) { ND_PRINT((ndo, " NFS_ACCESS_READ")); separator = '|'; } if (access_flags & NFSV3ACCESS_LOOKUP) { ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_MODIFY) { ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXTEND) { ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_DELETE) { ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXECUTE) ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator)); } return; } break; case NFSPROC_READ: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); } else { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes @ %u", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_WRITE: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64, EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[3])))); } } else { ND_TCHECK(dp[3]); ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)", EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_SYMLINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; if (parsefn(ndo, dp) == NULL) break; if (v3 && ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_MKNOD: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_TCHECK(*dp); type = (nfs_type)EXTRACT_32BITS(dp); dp++; if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type))); if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u/%u", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); dp += 2; } if (ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_RENAME: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_LINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_READDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); /* * We shouldn't really try to interpret the * offset cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3])); } else { ND_TCHECK(dp[1]); /* * Print the offset as signed, since -1 is * common, but offsets > 2^31 aren't. */ ND_PRINT((ndo, " %u bytes @ %d", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_READDIRPLUS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[4]); /* * We don't try to interpret the offset * cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_TCHECK(dp[5]); ND_PRINT((ndo, " max %u verf %08x%08x", EXTRACT_32BITS(&dp[5]), dp[2], dp[3])); } return; } break; case NFSPROC_COMMIT: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); return; } break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Print out an NFS file handle. * We assume packet was not truncated before the end of the * file handle pointed to by dp. * * Note: new version (using portable file-handle parser) doesn't produce * generation number. It probably could be made to do that, with some * additional hacking on the parser code. */ static void nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ static char temp[NFSX_V3FHMAX+1]; /* Make sure string is null-terminated */ strncpy(temp, sfsname, NFSX_V3FHMAX); temp[sizeof(temp) - 1] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } /* * Maintain a small cache of recent client.XID.server/proc pairs, to allow * us to match up replies with requests and thus to know how to parse * the reply. */ struct xid_map_entry { uint32_t xid; /* transaction ID (net order) */ int ipver; /* IP version (4 or 6) */ struct in6_addr client; /* client IP address (net order) */ struct in6_addr server; /* server IP address (net order) */ uint32_t proc; /* call proc number (host order) */ uint32_t vers; /* program version (host order) */ }; /* * Map entries are kept in an array that we manage as a ring; * new entries are always added at the tail of the ring. Initially, * all the entries are zero and hence don't match anything. */ #define XIDMAPSIZE 64 static struct xid_map_entry xid_map[XIDMAPSIZE]; static int xid_map_next = 0; static int xid_map_hint = 0; static int xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } /* * Returns 0 and puts NFSPROC_xxx in proc return and * version in vers return, or returns -1 on failure */ static int xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc, uint32_t *vers) { int i; struct xid_map_entry *xmep; uint32_t xid; const struct ip *ip = (const struct ip *)bp; const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp; int cmp; UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid)); /* Start searching from where we last left off */ i = xid_map_hint; do { xmep = &xid_map[i]; cmp = 1; if (xmep->ipver != IP_V(ip) || xmep->xid != xid) goto nextitem; switch (xmep->ipver) { case 4: if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server, sizeof(ip->ip_src)) != 0 || UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client, sizeof(ip->ip_dst)) != 0) { cmp = 0; } break; case 6: if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server, sizeof(ip6->ip6_src)) != 0 || UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client, sizeof(ip6->ip6_dst)) != 0) { cmp = 0; } break; default: cmp = 0; break; } if (cmp) { /* match */ xid_map_hint = i; *proc = xmep->proc; *vers = xmep->vers; return 0; } nextitem: if (++i >= XIDMAPSIZE) i = 0; } while (i != xid_map_hint); /* search failed */ return (-1); } /* * Routines for parsing reply packets */ /* * Return a pointer to the beginning of the actual results. * If the packet was truncated, return 0. */ static const uint32_t * parserep(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; u_int len; enum sunrpc_accept_stat astat; /* * Portability note: * Here we find the address of the ar_verf credentials. * Originally, this calculation was * dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf * On the wire, the rp_acpt field starts immediately after * the (32 bit) rp_stat field. However, rp_acpt (which is a * "struct accepted_reply") contains a "struct opaque_auth", * whose internal representation contains a pointer, so on a * 64-bit machine the compiler inserts 32 bits of padding * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use * the internal representation to parse the on-the-wire * representation. Instead, we skip past the rp_stat field, * which is an "enum" and so occupies one 32-bit word. */ dp = ((const uint32_t *)&rp->rm_reply) + 1; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len >= length) return (NULL); /* * skip past the ar_verf credentials. */ dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t); /* * now we can check the ar_stat field */ ND_TCHECK(dp[0]); astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp); if (astat != SUNRPC_SUCCESS) { ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat))); nfserr = 1; /* suppress trunc string */ return (NULL); } /* successful return */ ND_TCHECK2(*dp, sizeof(astat)); return ((const uint32_t *) (sizeof(astat) + ((const char *)dp))); trunc: return (0); } static const uint32_t * parsestatus(netdissect_options *ndo, const uint32_t *dp, int *er) { int errnum; ND_TCHECK(dp[0]); errnum = EXTRACT_32BITS(&dp[0]); if (er) *er = errnum; if (errnum != 0) { if (!ndo->ndo_qflag) ND_PRINT((ndo, " ERROR: %s", tok2str(status2str, "unk %d", errnum))); nfserr = 1; } return (dp + 1); trunc: return NULL; } static const uint32_t * parsefattr(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { const struct nfs_fattr *fap; fap = (const struct nfs_fattr *)dp; ND_TCHECK(fap->fa_gid); if (verbose) { ND_PRINT((ndo, " %s %o ids %d/%d", tok2str(type2str, "unk-ft %d ", EXTRACT_32BITS(&fap->fa_type)), EXTRACT_32BITS(&fap->fa_mode), EXTRACT_32BITS(&fap->fa_uid), EXTRACT_32BITS(&fap->fa_gid))); if (v3) { ND_TCHECK(fap->fa3_size); ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_size))); } else { ND_TCHECK(fap->fa2_size); ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size))); } } /* print lots more stuff */ if (verbose > 1) { if (v3) { ND_TCHECK(fap->fa3_ctime); ND_PRINT((ndo, " nlink %d rdev %d/%d", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa3_rdev.specdata1), EXTRACT_32BITS(&fap->fa3_rdev.specdata2))); ND_PRINT((ndo, " fsid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid))); ND_PRINT((ndo, " fileid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid))); ND_PRINT((ndo, " a/m/ctime %u.%06u", EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec))); } else { ND_TCHECK(fap->fa2_ctime); ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa2_rdev), EXTRACT_32BITS(&fap->fa2_fsid), EXTRACT_32BITS(&fap->fa2_fileid))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec))); } } return ((const uint32_t *)((const unsigned char *)dp + (v3 ? NFSX_V3FATTR : NFSX_V2FATTR))); trunc: return (NULL); } static int parseattrstat(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); return (parsefattr(ndo, dp, verbose, v3) != NULL); } static int parsediropres(netdissect_options *ndo, const uint32_t *dp) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) return (1); dp = parsefh(ndo, dp, 0); if (dp == NULL) return (0); return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL); } static int parselinkres(netdissect_options *ndo, const uint32_t *dp, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return(0); if (er) return(1); if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp) != NULL); } static int parsestatfs(netdissect_options *ndo, const uint32_t *dp, int v3) { const struct nfs_statfs *sfsp; int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (!v3 && er) return (1); if (ndo->ndo_qflag) return(1); if (v3) { if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); } ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS)); sfsp = (const struct nfs_statfs *)dp; if (v3) { ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64, EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u", EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles), EXTRACT_32BITS(&sfsp->sf_invarsec))); } } else { ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d", EXTRACT_32BITS(&sfsp->sf_tsize), EXTRACT_32BITS(&sfsp->sf_bsize), EXTRACT_32BITS(&sfsp->sf_blocks), EXTRACT_32BITS(&sfsp->sf_bfree), EXTRACT_32BITS(&sfsp->sf_bavail))); } return (1); trunc: return (0); } static int parserddires(netdissect_options *ndo, const uint32_t *dp) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); if (ndo->ndo_qflag) return (1); ND_TCHECK(dp[2]); ND_PRINT((ndo, " offset 0x%x size %d ", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); if (dp[2] != 0) ND_PRINT((ndo, " eof")); return (1); trunc: return (0); } static const uint32_t * parse_wcc_attr(netdissect_options *ndo, const uint32_t *dp) { /* Our caller has already checked this */ ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0]))); ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u", EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5]))); return (dp + 6); } /* * Pre operation attributes. Print only if vflag > 1. */ static const uint32_t * parse_pre_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; ND_TCHECK2(*dp, 24); if (verbose > 1) { return parse_wcc_attr(ndo, dp); } else { /* If not verbose enough, just skip over wcc_attr */ return (dp + 6); } trunc: return (NULL); } /* * Post operation attributes are printed if vflag >= 1 */ static const uint32_t * parse_post_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (verbose) { return parsefattr(ndo, dp, verbose, 1); } else return (dp + (NFSX_V3FATTR / sizeof (uint32_t))); trunc: return (NULL); } static const uint32_t * parse_wcc_data(netdissect_options *ndo, const uint32_t *dp, int verbose) { if (verbose > 1) ND_PRINT((ndo, " PRE:")); if (!(dp = parse_pre_op_attr(ndo, dp, verbose))) return (0); if (verbose) ND_PRINT((ndo, " POST:")); return parse_post_op_attr(ndo, dp, verbose); } static const uint32_t * parsecreateopres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) dp = parse_wcc_data(ndo, dp, verbose); else { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (!(dp = parsefh(ndo, dp, 1))) return (0); if (verbose) { if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " dir attr:")); dp = parse_wcc_data(ndo, dp, verbose); } } } return (dp); trunc: return (NULL); } static int parsewccres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); return parse_wcc_data(ndo, dp, verbose) != NULL; } static const uint32_t * parsev3rddirres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (er) return dp; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1])); dp += 2; } return dp; trunc: return (NULL); } static int parsefsinfo(netdissect_options *ndo, const uint32_t *dp) { const struct nfsv3_fsinfo *sfp; int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); sfp = (const struct nfsv3_fsinfo *)dp; ND_TCHECK(*sfp); ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u", EXTRACT_32BITS(&sfp->fs_rtmax), EXTRACT_32BITS(&sfp->fs_rtpref), EXTRACT_32BITS(&sfp->fs_wtmax), EXTRACT_32BITS(&sfp->fs_wtpref), EXTRACT_32BITS(&sfp->fs_dtpref))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64, EXTRACT_32BITS(&sfp->fs_rtmult), EXTRACT_32BITS(&sfp->fs_wtmult), EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize))); ND_PRINT((ndo, " delta %u.%06u ", EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec), EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec))); } return (1); trunc: return (0); } static int parsepathconf(netdissect_options *ndo, const uint32_t *dp) { int er; const struct nfsv3_pathconf *spp; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); spp = (const struct nfsv3_pathconf *)dp; ND_TCHECK(*spp); ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s", EXTRACT_32BITS(&spp->pc_linkmax), EXTRACT_32BITS(&spp->pc_namemax), EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "", EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "", EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "", EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : "")); return (1); trunc: return (0); } static void interp_reply(netdissect_options *ndo, const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length) { register const uint32_t *dp; register int v3; int er; v3 = (vers == NFS_VER3); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: dp = parserep(ndo, rp, length); if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0) return; break; case NFSPROC_SETATTR: if (!(dp = parserep(ndo, rp, length))) return; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0) return; } break; case NFSPROC_LOOKUP: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (er) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } else { if (!(dp = parsefh(ndo, dp, v3))) break; if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) && ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } if (dp) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_ACCESS: if (!(dp = parserep(ndo, rp, length))) break; if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) ND_PRINT((ndo, " attr:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (!er) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0]))); } return; case NFSPROC_READLINK: dp = parserep(ndo, rp, length); if (dp != NULL && parselinkres(ndo, dp, v3) != 0) return; break; case NFSPROC_READ: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (EXTRACT_32BITS(&dp[1])) ND_PRINT((ndo, " EOF")); } return; } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0) return; } break; case NFSPROC_WRITE: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (ndo->ndo_vflag > 1) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[1])))); } return; } } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0) return; } break; case NFSPROC_CREATE: case NFSPROC_MKDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_SYMLINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_MKNOD: if (!(dp = parserep(ndo, rp, length))) break; if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; break; case NFSPROC_REMOVE: case NFSPROC_RMDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_RENAME: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " from:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " to:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; } return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_LINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " file POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " dir:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; return; } } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_READDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parserddires(ndo, dp) != 0) return; } break; case NFSPROC_READDIRPLUS: if (!(dp = parserep(ndo, rp, length))) break; if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; break; case NFSPROC_FSSTAT: dp = parserep(ndo, rp, length); if (dp != NULL && parsestatfs(ndo, dp, v3) != 0) return; break; case NFSPROC_FSINFO: dp = parserep(ndo, rp, length); if (dp != NULL && parsefsinfo(ndo, dp) != 0) return; break; case NFSPROC_PATHCONF: dp = parserep(ndo, rp, length); if (dp != NULL && parsepathconf(ndo, dp) != 0) return; break; case NFSPROC_COMMIT: dp = parserep(ndo, rp, length); if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0) return; break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2676_0
crossvul-cpp_data_good_1011_0
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * memcached - memory caching daemon * * https://www.memcached.org/ * * Copyright 2003 Danga Interactive, Inc. All rights reserved. * * Use and distribution licensed under the BSD license. See * the LICENSE file for full text. * * Authors: * Anatoly Vorobey <mellon@pobox.com> * Brad Fitzpatrick <brad@danga.com> */ #include "memcached.h" #ifdef EXTSTORE #include "storage.h" #endif #include "authfile.h" #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/uio.h> #include <ctype.h> #include <stdarg.h> /* some POSIX systems need the following definition * to get mlockall flags out of sys/mman.h. */ #ifndef _P1003_1B_VISIBLE #define _P1003_1B_VISIBLE #endif /* need this to get IOV_MAX on some platforms. */ #ifndef __need_IOV_MAX #define __need_IOV_MAX #endif #include <pwd.h> #include <sys/mman.h> #include <fcntl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <assert.h> #include <limits.h> #include <sysexits.h> #include <stddef.h> #ifdef HAVE_GETOPT_LONG #include <getopt.h> #endif #ifdef TLS #include "tls.h" #endif #if defined(__FreeBSD__) #include <sys/sysctl.h> #endif /* FreeBSD 4.x doesn't have IOV_MAX exposed. */ #ifndef IOV_MAX #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__) # define IOV_MAX 1024 /* GNU/Hurd don't set MAXPATHLEN * http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */ #ifndef MAXPATHLEN #define MAXPATHLEN 4096 #endif #endif #endif /* * forward declarations */ static void drive_machine(conn *c); static int new_socket(struct addrinfo *ai); static ssize_t tcp_read(conn *arg, void *buf, size_t count); static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags); static ssize_t tcp_write(conn *arg, void *buf, size_t count); enum try_read_result { READ_DATA_RECEIVED, READ_NO_DATA_RECEIVED, READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */ READ_MEMORY_ERROR /** failed to allocate more memory */ }; static int try_read_command_negotiate(conn *c); static int try_read_command_udp(conn *c); static int try_read_command_binary(conn *c); static int try_read_command_ascii(conn *c); static int try_read_command_asciiauth(conn *c); static enum try_read_result try_read_network(conn *c); static enum try_read_result try_read_udp(conn *c); static void conn_set_state(conn *c, enum conn_states state); static int start_conn_timeout_thread(); /* stats */ static void stats_init(void); static void server_stats(ADD_STAT add_stats, conn *c); static void process_stat_settings(ADD_STAT add_stats, void *c); static void conn_to_str(const conn *c, char *addr, char *svr_addr); /** Return a datum for stats in binary protocol */ static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c); /* defaults */ static void settings_init(void); /* event handling, network IO */ static void event_handler(const int fd, const short which, void *arg); static void conn_close(conn *c); static void conn_init(void); static bool update_event(conn *c, const int new_flags); static void complete_nread(conn *c); static void process_command(conn *c, char *command); static void write_and_free(conn *c, char *buf, int bytes); static int ensure_iov_space(conn *c); static int add_iov(conn *c, const void *buf, int len); static int add_chunked_item_iovs(conn *c, item *it, int len); static int add_msghdr(conn *c); static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow); static void write_bin_miss_response(conn *c, char *key, size_t nkey); #ifdef EXTSTORE static void _get_extstore_cb(void *e, obj_io *io, int ret); static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt); #endif static void conn_free(conn *c); /** exported globals **/ struct stats stats; struct stats_state stats_state; struct settings settings; time_t process_started; /* when the process was started */ conn **conns; struct slab_rebalance slab_rebal; volatile int slab_rebalance_signal; #ifdef EXTSTORE /* hoping this is temporary; I'd prefer to cut globals, but will complete this * battle another day. */ void *ext_storage; #endif /** file scope variables **/ static conn *listen_conn = NULL; static int max_fds; static struct event_base *main_base; enum transmit_result { TRANSMIT_COMPLETE, /** All done writing. */ TRANSMIT_INCOMPLETE, /** More data remaining to write. */ TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */ TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */ }; /* Default methods to read from/ write to a socket */ ssize_t tcp_read(conn *c, void *buf, size_t count) { assert (c != NULL); return read(c->sfd, buf, count); } ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) { assert (c != NULL); return sendmsg(c->sfd, msg, flags); } ssize_t tcp_write(conn *c, void *buf, size_t count) { assert (c != NULL); return write(c->sfd, buf, count); } static enum transmit_result transmit(conn *c); /* This reduces the latency without adding lots of extra wiring to be able to * notify the listener thread of when to listen again. * Also, the clock timer could be broken out into its own thread and we * can block the listener via a condition. */ static volatile bool allow_new_conns = true; static struct event maxconnsevent; static void maxconns_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 0, .tv_usec = 10000}; if (fd == -42 || allow_new_conns == false) { /* reschedule in 10ms if we need to keep polling */ evtimer_set(&maxconnsevent, maxconns_handler, 0); event_base_set(main_base, &maxconnsevent); evtimer_add(&maxconnsevent, &t); } else { evtimer_del(&maxconnsevent); accept_new_conns(true); } } #define REALTIME_MAXDELTA 60*60*24*30 /* * given time value that's either unix time or delta from current unix time, return * unix time. Use the fact that delta can't exceed one month (and real time value can't * be that low). */ static rel_time_t realtime(const time_t exptime) { /* no. of seconds in 30 days - largest possible delta exptime */ if (exptime == 0) return 0; /* 0 means never expire */ if (exptime > REALTIME_MAXDELTA) { /* if item expiration is at/before the server started, give it an expiration time of 1 second after the server started. (because 0 means don't expire). without this, we'd underflow and wrap around to some large value way in the future, effectively making items expiring in the past really expiring never */ if (exptime <= process_started) return (rel_time_t)1; return (rel_time_t)(exptime - process_started); } else { return (rel_time_t)(exptime + current_time); } } static void stats_init(void) { memset(&stats, 0, sizeof(struct stats)); memset(&stats_state, 0, sizeof(struct stats_state)); stats_state.accepting_conns = true; /* assuming we start in this state. */ /* make the time we started always be 2 seconds before we really did, so time(0) - time.started is never zero. if so, things like 'settings.oldest_live' which act as booleans as well as values are now false in boolean context... */ process_started = time(0) - ITEM_UPDATE_INTERVAL - 2; stats_prefix_init(); } static void stats_reset(void) { STATS_LOCK(); memset(&stats, 0, sizeof(struct stats)); stats_prefix_clear(); STATS_UNLOCK(); threadlocal_stats_reset(); item_stats_reset(); } static void settings_init(void) { settings.use_cas = true; settings.access = 0700; settings.port = 11211; settings.udpport = 0; #ifdef TLS settings.ssl_enabled = false; settings.ssl_ctx = NULL; settings.ssl_chain_cert = NULL; settings.ssl_key = NULL; settings.ssl_verify_mode = SSL_VERIFY_NONE; settings.ssl_keyformat = SSL_FILETYPE_PEM; settings.ssl_ciphers = NULL; settings.ssl_ca_cert = NULL; settings.ssl_last_cert_refresh_time = current_time; settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB) #endif /* By default this string should be NULL for getaddrinfo() */ settings.inter = NULL; settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */ settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */ settings.verbose = 0; settings.oldest_live = 0; settings.oldest_cas = 0; /* supplements accuracy of oldest_live */ settings.evict_to_free = 1; /* push old items out of cache when memory runs out */ settings.socketpath = NULL; /* by default, not using a unix socket */ settings.auth_file = NULL; /* by default, not using ASCII authentication tokens */ settings.factor = 1.25; settings.chunk_size = 48; /* space for a modest key and value */ settings.num_threads = 4; /* N workers */ settings.num_threads_per_udp = 0; settings.prefix_delimiter = ':'; settings.detail_enabled = 0; settings.reqs_per_event = 20; settings.backlog = 1024; settings.binding_protocol = negotiating_prot; settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */ settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */ settings.slab_chunk_size_max = settings.slab_page_size / 2; settings.sasl = false; settings.maxconns_fast = true; settings.lru_crawler = false; settings.lru_crawler_sleep = 100; settings.lru_crawler_tocrawl = 0; settings.lru_maintainer_thread = false; settings.lru_segmented = true; settings.hot_lru_pct = 20; settings.warm_lru_pct = 40; settings.hot_max_factor = 0.2; settings.warm_max_factor = 2.0; settings.temp_lru = false; settings.temporary_ttl = 61; settings.idle_timeout = 0; /* disabled */ settings.hashpower_init = 0; settings.slab_reassign = true; settings.slab_automove = 1; settings.slab_automove_ratio = 0.8; settings.slab_automove_window = 30; settings.shutdown_command = false; settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT; settings.flush_enabled = true; settings.dump_enabled = true; settings.crawls_persleep = 1000; settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE; settings.logger_buf_size = LOGGER_BUF_SIZE; settings.drop_privileges = false; #ifdef MEMCACHED_DEBUG settings.relaxed_privileges = false; #endif } /* * Adds a message header to a connection. * * Returns 0 on success, -1 on out-of-memory. */ static int add_msghdr(conn *c) { struct msghdr *msg; assert(c != NULL); if (c->msgsize == c->msgused) { msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr)); if (! msg) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->msglist = msg; c->msgsize *= 2; } msg = c->msglist + c->msgused; /* this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the last 3 of which aren't defined on solaris: */ memset(msg, 0, sizeof(struct msghdr)); msg->msg_iov = &c->iov[c->iovused]; if (IS_UDP(c->transport) && c->request_addr_size > 0) { msg->msg_name = &c->request_addr; msg->msg_namelen = c->request_addr_size; } c->msgbytes = 0; c->msgused++; if (IS_UDP(c->transport)) { /* Leave room for the UDP header, which we'll fill in later. */ return add_iov(c, NULL, UDP_HEADER_SIZE); } return 0; } extern pthread_mutex_t conn_lock; /* Connection timeout thread bits */ static pthread_t conn_timeout_tid; #define CONNS_PER_SLICE 100 #define TIMEOUT_MSG_SIZE (1 + sizeof(int)) static void *conn_timeout_thread(void *arg) { int i; conn *c; char buf[TIMEOUT_MSG_SIZE]; rel_time_t oldest_last_cmd; int sleep_time; useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE); while(1) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread at top of connection list\n"); oldest_last_cmd = current_time; for (i = 0; i < max_fds; i++) { if ((i % CONNS_PER_SLICE) == 0) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread sleeping for %ulus\n", (unsigned int)timeslice); usleep(timeslice); } if (!conns[i]) continue; c = conns[i]; if (!IS_TCP(c->transport)) continue; if (c->state != conn_new_cmd && c->state != conn_read) continue; if ((current_time - c->last_cmd_time) > settings.idle_timeout) { buf[0] = 't'; memcpy(&buf[1], &i, sizeof(int)); if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE) != TIMEOUT_MSG_SIZE) perror("Failed to write timeout to notify pipe"); } else { if (c->last_cmd_time < oldest_last_cmd) oldest_last_cmd = c->last_cmd_time; } } /* This is the soonest we could have another connection time out */ sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1; if (sleep_time <= 0) sleep_time = 1; if (settings.verbose > 2) fprintf(stderr, "idle timeout thread finished pass, sleeping for %ds\n", sleep_time); usleep((useconds_t) sleep_time * 1000000); } return NULL; } static int start_conn_timeout_thread() { int ret; if (settings.idle_timeout == 0) return -1; if ((ret = pthread_create(&conn_timeout_tid, NULL, conn_timeout_thread, NULL)) != 0) { fprintf(stderr, "Can't create idle connection timeout thread: %s\n", strerror(ret)); return -1; } return 0; } /* * Initializes the connections array. We don't actually allocate connection * structures until they're needed, so as to avoid wasting memory when the * maximum connection count is much higher than the actual number of * connections. * * This does end up wasting a few pointers' worth of memory for FDs that are * used for things other than connections, but that's worth it in exchange for * being able to directly index the conns array by FD. */ static void conn_init(void) { /* We're unlikely to see an FD much higher than maxconns. */ int next_fd = dup(1); if (next_fd < 0) { perror("Failed to duplicate file descriptor\n"); exit(1); } int headroom = 10; /* account for extra unexpected open FDs */ struct rlimit rl; max_fds = settings.maxconns + headroom + next_fd; /* But if possible, get the actual highest FD we can possibly ever see. */ if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { max_fds = rl.rlim_max; } else { fprintf(stderr, "Failed to query maximum file descriptor; " "falling back to maxconns\n"); } close(next_fd); if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) { fprintf(stderr, "Failed to allocate connection structures\n"); /* This is unrecoverable so bail out early. */ exit(1); } } static const char *prot_text(enum protocol prot) { char *rv = "unknown"; switch(prot) { case ascii_prot: rv = "ascii"; break; case binary_prot: rv = "binary"; break; case negotiating_prot: rv = "auto-negotiate"; break; } return rv; } void conn_close_idle(conn *c) { if (settings.idle_timeout > 0 && (current_time - c->last_cmd_time) > settings.idle_timeout) { if (c->state != conn_new_cmd && c->state != conn_read) { if (settings.verbose > 1) fprintf(stderr, "fd %d wants to timeout, but isn't in read state", c->sfd); return; } if (settings.verbose > 1) fprintf(stderr, "Closing idle fd %d\n", c->sfd); c->thread->stats.idle_kicks++; conn_set_state(c, conn_closing); drive_machine(c); } } /* bring conn back from a sidethread. could have had its event base moved. */ void conn_worker_readd(conn *c) { c->ev_flags = EV_READ | EV_PERSIST; event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c); event_base_set(c->thread->base, &c->event); c->state = conn_new_cmd; // TODO: call conn_cleanup/fail/etc if (event_add(&c->event, 0) == -1) { perror("event_add"); } #ifdef EXTSTORE // If we had IO objects, process if (c->io_wraplist) { //assert(c->io_wrapleft == 0); // assert no more to process conn_set_state(c, conn_mwrite); drive_machine(c); } #endif } conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base, void *ssl) { conn *c; assert(sfd >= 0 && sfd < max_fds); c = conns[sfd]; if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->read = NULL; c->sendmsg = NULL; c->write = NULL; c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats_state.conn_structs++; STATS_UNLOCK(); c->sfd = sfd; conns[sfd] = c; } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (transport == tcp_transport && init_state == conn_new_cmd) { if (getpeername(sfd, (struct sockaddr *) &c->request_addr, &c->request_addr_size)) { perror("getpeername"); memset(&c->request_addr, 0, sizeof(c->request_addr)); } } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } #ifdef TLS c->ssl = NULL; c->ssl_wbuf = NULL; c->ssl_enabled = false; #endif c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->sasl_started = false; c->last_cmd_time = current_time; /* initialize for idle kicker */ #ifdef EXTSTORE c->io_wraplist = NULL; c->io_wrapleft = 0; #endif c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; #ifdef TLS if (ssl) { c->ssl = (SSL*)ssl; c->read = ssl_read; c->sendmsg = ssl_sendmsg; c->write = ssl_write; c->ssl_enabled = true; SSL_set_info_callback(c->ssl, ssl_callback); } else #else // This must be NULL if TLS is not enabled. assert(ssl == NULL); #endif { c->read = tcp_read; c->sendmsg = tcp_sendmsg; c->write = tcp_write; } if (IS_UDP(transport)) { c->try_read_command = try_read_command_udp; } else { switch (c->protocol) { case ascii_prot: if (settings.auth_file == NULL) { c->authenticated = true; c->try_read_command = try_read_command_ascii; } else { c->authenticated = false; c->try_read_command = try_read_command_asciiauth; } break; case binary_prot: // binprot handles its own authentication via SASL parsing. c->authenticated = false; c->try_read_command = try_read_command_binary; break; case negotiating_prot: c->try_read_command = try_read_command_negotiate; break; } } event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { perror("event_add"); return NULL; } STATS_LOCK(); stats_state.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } #ifdef EXTSTORE static void recache_or_free(conn *c, io_wrap *wrap) { item *it; it = (item *)wrap->io.buf; bool do_free = true; if (wrap->active) { // If request never dispatched, free the read buffer but leave the // item header alone. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); c->io_wrapleft--; assert(c->io_wrapleft >= 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_aborted_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (wrap->miss) { // If request was ultimately a miss, unlink the header. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); item_unlink(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.miss_from_extstore++; if (wrap->badcrc) c->thread->stats.badcrc_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (settings.ext_recache_rate) { // hashvalue is cuddled during store uint32_t hv = (uint32_t)it->time; // opt to throw away rather than wait on a lock. void *hold_lock = item_trylock(hv); if (hold_lock != NULL) { item *h_it = wrap->hdr_it; uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE; // Item must be recently hit at least twice to recache. if (((h_it->it_flags & flags) == flags) && h_it->time > current_time - ITEM_UPDATE_INTERVAL && c->recache_counter++ % settings.ext_recache_rate == 0) { do_free = false; // In case it's been updated. it->exptime = h_it->exptime; it->it_flags &= ~ITEM_LINKED; it->refcount = 0; it->h_next = NULL; // might not be necessary. STORAGE_delete(c->thread->storage, h_it); item_replace(h_it, it, hv); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.recache_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } } if (hold_lock) item_trylock_unlock(hold_lock); } if (do_free) slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it)); wrap->io.buf = NULL; // sanity. wrap->io.next = NULL; wrap->next = NULL; wrap->active = false; // TODO: reuse lock and/or hv. item_remove(wrap->hdr_it); } #endif static void conn_release_items(conn *c) { assert(c != NULL); if (c->item) { item_remove(c->item); c->item = 0; } while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } if (c->suffixleft != 0) { for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) { do_cache_free(c->thread->suffix_cache, *(c->suffixcurr)); } } #ifdef EXTSTORE if (c->io_wraplist) { io_wrap *tmp = c->io_wraplist; while (tmp) { io_wrap *next = tmp->next; recache_or_free(c, tmp); do_cache_free(c->thread->io_cache, tmp); // lockless tmp = next; } c->io_wraplist = NULL; } #endif c->icurr = c->ilist; c->suffixcurr = c->suffixlist; } static void conn_cleanup(conn *c) { assert(c != NULL); conn_release_items(c); if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } if (c->sasl_conn) { assert(settings.sasl); sasl_dispose(&c->sasl_conn); c->sasl_conn = NULL; } if (IS_UDP(c->transport)) { conn_set_state(c, conn_read); } } /* * Frees a connection. */ void conn_free(conn *c) { if (c) { assert(c != NULL); assert(c->sfd >= 0 && c->sfd < max_fds); MEMCACHED_CONN_DESTROY(c); conns[c->sfd] = NULL; if (c->hdrbuf) free(c->hdrbuf); if (c->msglist) free(c->msglist); if (c->rbuf) free(c->rbuf); if (c->wbuf) free(c->wbuf); if (c->ilist) free(c->ilist); if (c->suffixlist) free(c->suffixlist); if (c->iov) free(c->iov); #ifdef TLS if (c->ssl_wbuf) c->ssl_wbuf = NULL; #endif free(c); } } static void conn_close(conn *c) { assert(c != NULL); /* delete the event, the socket and the conn */ event_del(&c->event); if (settings.verbose > 1) fprintf(stderr, "<%d connection closed.\n", c->sfd); conn_cleanup(c); MEMCACHED_CONN_RELEASE(c->sfd); conn_set_state(c, conn_closed); #ifdef TLS if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); } #endif close(c->sfd); pthread_mutex_lock(&conn_lock); allow_new_conns = true; pthread_mutex_unlock(&conn_lock); STATS_LOCK(); stats_state.curr_conns--; STATS_UNLOCK(); return; } /* * Shrinks a connection's buffers if they're too big. This prevents * periodic large "get" requests from permanently chewing lots of server * memory. * * This should only be called in between requests since it can wipe output * buffers! */ static void conn_shrink(conn *c) { assert(c != NULL); if (IS_UDP(c->transport)) return; if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) { char *newbuf; if (c->rcurr != c->rbuf) memmove(c->rbuf, c->rcurr, (size_t)c->rbytes); newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE); if (newbuf) { c->rbuf = newbuf; c->rsize = DATA_BUFFER_SIZE; } /* TODO check other branch... */ c->rcurr = c->rbuf; } if (c->isize > ITEM_LIST_HIGHWAT) { item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0])); if (newbuf) { c->ilist = newbuf; c->isize = ITEM_LIST_INITIAL; } /* TODO check error condition? */ } if (c->msgsize > MSG_LIST_HIGHWAT) { struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0])); if (newbuf) { c->msglist = newbuf; c->msgsize = MSG_LIST_INITIAL; } /* TODO check error condition? */ } if (c->iovsize > IOV_LIST_HIGHWAT) { struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0])); if (newbuf) { c->iov = newbuf; c->iovsize = IOV_LIST_INITIAL; } /* TODO check return value */ } } /** * Convert a state name to a human readable form. */ static const char *state_text(enum conn_states state) { const char* const statenames[] = { "conn_listening", "conn_new_cmd", "conn_waiting", "conn_read", "conn_parse_cmd", "conn_write", "conn_nread", "conn_swallow", "conn_closing", "conn_mwrite", "conn_closed", "conn_watch" }; return statenames[state]; } /* * Sets a connection's current state in the state machine. Any special * processing that needs to happen on certain state transitions can * happen here. */ static void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state >= conn_listening && state < conn_max_state); if (state != c->state) { if (settings.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } if (state == conn_write || state == conn_mwrite) { MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes); } c->state = state; } } /* * Ensures that there is room for another struct iovec in a connection's * iov list. * * Returns 0 on success, -1 on out-of-memory. */ static int ensure_iov_space(conn *c) { assert(c != NULL); if (c->iovused >= c->iovsize) { int i, iovnum; struct iovec *new_iov = (struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec)); if (! new_iov) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->iov = new_iov; c->iovsize *= 2; /* Point all the msghdr structures at the new list. */ for (i = 0, iovnum = 0; i < c->msgused; i++) { c->msglist[i].msg_iov = &c->iov[iovnum]; iovnum += c->msglist[i].msg_iovlen; } } return 0; } /* * Adds data to the list of pending data that will be written out to a * connection. * * Returns 0 on success, -1 on out-of-memory. * Note: This is a hot path for at least ASCII protocol. While there is * redundant code in splitting TCP/UDP handling, any reduction in steps has a * large impact for TCP connections. */ static int add_iov(conn *c, const void *buf, int len) { struct msghdr *m; int leftover; assert(c != NULL); if (IS_UDP(c->transport)) { do { m = &c->msglist[c->msgused - 1]; /* * Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes. */ /* We may need to start a new msghdr if this one is full. */ if (m->msg_iovlen == IOV_MAX || (c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; /* If the fragment is too big to fit in the datagram, split it up */ if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) { leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE; len -= leftover; } else { leftover = 0; } m = &c->msglist[c->msgused - 1]; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; buf = ((char *)buf) + len; len = leftover; } while (leftover > 0); } else { /* Optimized path for TCP connections */ m = &c->msglist[c->msgused - 1]; if (m->msg_iovlen == IOV_MAX) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; } return 0; } static int add_chunked_item_iovs(conn *c, item *it, int len) { assert(it->it_flags & ITEM_CHUNKED); item_chunk *ch = (item_chunk *) ITEM_schunk(it); while (ch) { int todo = (len > ch->used) ? ch->used : len; if (add_iov(c, ch->data, todo) != 0) { return -1; } ch = ch->next; len -= todo; } return 0; } /* * Constructs a set of UDP headers and attaches them to the outgoing messages. */ static int build_udp_headers(conn *c) { int i; unsigned char *hdr; assert(c != NULL); if (c->msgused > c->hdrsize) { void *new_hdrbuf; if (c->hdrbuf) { new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE); } else { new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE); } if (! new_hdrbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->hdrbuf = (unsigned char *)new_hdrbuf; c->hdrsize = c->msgused * 2; } hdr = c->hdrbuf; for (i = 0; i < c->msgused; i++) { c->msglist[i].msg_iov[0].iov_base = (void*)hdr; c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE; *hdr++ = c->request_id / 256; *hdr++ = c->request_id % 256; *hdr++ = i / 256; *hdr++ = i % 256; *hdr++ = c->msgused / 256; *hdr++ = c->msgused % 256; *hdr++ = 0; *hdr++ = 0; assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE); } return 0; } static void out_string(conn *c, const char *str) { size_t len; assert(c != NULL); if (c->noreply) { if (settings.verbose > 1) fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str); c->noreply = false; conn_set_state(c, conn_new_cmd); return; } if (settings.verbose > 1) fprintf(stderr, ">%d %s\n", c->sfd, str); /* Nuke a partial output... */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; add_msghdr(c); len = strlen(str); if ((len + 2) > c->wsize) { /* ought to be always enough. just fail for simplicity */ str = "SERVER_ERROR output line too long"; len = strlen(str); } memcpy(c->wbuf, str, len); memcpy(c->wbuf + len, "\r\n", 2); c->wbytes = len + 2; c->wcurr = c->wbuf; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; return; } /* * Outputs a protocol-specific "out of memory" error. For ASCII clients, * this is equivalent to out_string(). */ static void out_of_memory(conn *c, char *ascii_error) { const static char error_prefix[] = "SERVER_ERROR "; const static int error_prefix_len = sizeof(error_prefix) - 1; if (c->protocol == binary_prot) { /* Strip off the generic error prefix; it's irrelevant in binary */ if (!strncmp(ascii_error, error_prefix, error_prefix_len)) { ascii_error += error_prefix_len; } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0); } else { out_string(c, ascii_error); } } /* * we get here after reading the value in set/add/replace commands. The command * has been stored in c->cmd, and the item is ready in c->item. */ static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } /** * get a pointer to the start of the request struct for the current command */ static void* binary_get_request(conn *c) { char *ret = c->rcurr; ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen + c->binary_header.request.extlen); assert(ret >= c->rbuf); return ret; } /** * get a pointer to the key in this request */ static char* binary_get_key(conn *c) { return c->rcurr - (c->binary_header.request.keylen); } static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) { protocol_binary_response_header* header; assert(c); c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { /* This should never run out of memory because iov and msg lists * have minimum sizes big enough to hold an error response. */ out_of_memory(c, "SERVER_ERROR out of memory adding binary header"); return; } header = (protocol_binary_response_header *)c->wbuf; header->response.magic = (uint8_t)PROTOCOL_BINARY_RES; header->response.opcode = c->binary_header.request.opcode; header->response.keylen = (uint16_t)htons(key_len); header->response.extlen = (uint8_t)hdr_len; header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES; header->response.status = (uint16_t)htons(err); header->response.bodylen = htonl(body_len); header->response.opaque = c->opaque; header->response.cas = htonll(c->cas); if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d Writing bin response:", c->sfd); for (ii = 0; ii < sizeof(header->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n>%d ", c->sfd); } fprintf(stderr, " 0x%02x", header->bytes[ii]); } fprintf(stderr, "\n"); } add_iov(c, c->wbuf, sizeof(header->response)); } /** * Writes a binary error response. If errstr is supplied, it is used as the * error text; otherwise a generic description of the error status code is * included. */ static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow) { size_t len; if (!errstr) { switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } /* Form and send a response to a command over the binary protocol */ static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) { if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET || c->cmd == PROTOCOL_BINARY_CMD_GETK) { add_bin_header(c, 0, hlen, keylen, dlen); if(dlen > 0) { add_iov(c, d, dlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { conn_set_state(c, conn_new_cmd); } } static void complete_incr_bin(conn *c) { item *it; char *key; size_t nkey; /* Weird magic in add_delta forces me to pad here */ char tmpbuf[INCR_MAX_STORAGE_LEN]; uint64_t cas = 0; protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf; protocol_binary_request_incr* req = binary_get_request(c); assert(c != NULL); assert(c->wsize >= sizeof(*rsp)); /* fix byteorder in the request */ req->message.body.delta = ntohll(req->message.body.delta); req->message.body.initial = ntohll(req->message.body.initial); req->message.body.expiration = ntohl(req->message.body.expiration); key = binary_get_key(c); nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int i; fprintf(stderr, "incr "); for (i = 0; i < nkey; i++) { fprintf(stderr, "%c", key[i]); } fprintf(stderr, " %lld, %llu, %d\n", (long long)req->message.body.delta, (long long)req->message.body.initial, req->message.body.expiration); } if (c->binary_header.request.cas != 0) { cas = c->binary_header.request.cas; } switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT, req->message.body.delta, tmpbuf, &cas)) { case OK: rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10)); if (cas) { c->cas = cas; } write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); break; case NON_NUMERIC: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0); break; case EOM: out_of_memory(c, "SERVER_ERROR Out of memory incrementing value"); break; case DELTA_ITEM_NOT_FOUND: if (req->message.body.expiration != 0xffffffff) { /* Save some room for the response */ rsp->message.body.value = htonll(req->message.body.initial); snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)req->message.body.initial); int res = strlen(tmpbuf); it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration), res + 2); if (it != NULL) { memcpy(ITEM_data(it), tmpbuf, res); memcpy(ITEM_data(it) + res, "\r\n", 2); if (store_item(it, NREAD_ADD, c)) { c->cas = ITEM_get_cas(it); write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, NULL, 0); } item_remove(it); /* release our reference */ } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating new item"); } } else { pthread_mutex_lock(&c->thread->stats.mutex); if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } break; case DELTA_ITEM_CAS_MISMATCH: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; } } static void complete_update_bin(conn *c) { protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL; enum store_item_type ret = NOT_STORED; assert(c != NULL); item *it = c->item; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); /* We don't actually receive the trailing two characters in the bin * protocol, so we're going to just set them here */ if ((it->it_flags & ITEM_CHUNKED) == 0) { *(ITEM_data(it) + it->nbytes - 2) = '\r'; *(ITEM_data(it) + it->nbytes - 1) = '\n'; } else { assert(c->ritem); item_chunk *ch = (item_chunk *) c->ritem; if (ch->size == ch->used) ch = ch->next; assert(ch->size - ch->used >= 2); ch->data[ch->used] = '\r'; ch->data[ch->used + 1] = '\n'; ch->used += 2; } ret = store_item(it, c->cmd, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; } #endif switch (ret) { case STORED: /* Stored */ write_bin_response(c, NULL, 0, 0, 0); break; case EXISTS: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; case NOT_FOUND: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); break; case NOT_STORED: case TOO_LARGE: case NO_MEMORY: if (c->cmd == NREAD_ADD) { eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } else if(c->cmd == NREAD_REPLACE) { eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED; } write_bin_error(c, eno, NULL, 0); } item_remove(c->item); /* release the c->item reference */ c->item = 0; } static void write_bin_miss_response(conn *c, char *key, size_t nkey) { if (nkey) { char *ofs = c->wbuf + sizeof(protocol_binary_response_header); add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0, nkey, nkey); memcpy(ofs, key, nkey); add_iov(c, ofs, nkey); conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } } static void process_bin_get_or_touch(conn *c) { item *it; protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf; char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH || c->cmd == PROTOCOL_BINARY_CMD_GAT || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH); bool failed = false; if (settings.verbose > 1) { fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET"); if (fwrite(key, 1, nkey, stderr)) {} fputc('\n', stderr); } if (should_touch) { protocol_binary_request_touch *t = binary_get_request(c); time_t exptime = ntohl(t->message.body.expiration); it = item_touch(key, nkey, realtime(exptime), c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it) { /* the length has two unnecessary bytes ("\r\n") */ uint16_t keylen = 0; uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2); pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.get_cmds++; c->thread->stats.lru_hits[it->slabs_clsid]++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) { bodylen -= it->nbytes - 2; } else if (should_return_key) { bodylen += nkey; keylen = nkey; } add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen); rsp->message.header.response.cas = htonll(ITEM_get_cas(it)); // add the flags FLAGS_CONV(it, rsp->message.body.flags); rsp->message.body.flags = htonl(rsp->message.body.flags); add_iov(c, &rsp->message.body, sizeof(rsp->message.body)); if (should_return_key) { add_iov(c, ITEM_key(it), nkey); } if (should_return_value) { /* Add the data minus the CRLF */ #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { int iovcnt = 4; int iovst = c->iovused - 3; if (!should_return_key) { iovcnt = 3; iovst = c->iovused - 2; } if (_get_extstore(c, it, iovst, iovcnt) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); failed = true; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #endif } if (!failed) { conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; /* Remember this command so we can garbage collect it later */ #ifdef EXTSTORE if ((it->it_flags & ITEM_HDR) != 0 && should_return_value) { // Only have extstore clean if header and returning value. c->item = NULL; } else { c->item = it; } #else c->item = it; #endif } else { item_remove(it); } } else { failed = true; } if (failed) { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_cmds++; c->thread->stats.get_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0); } else { MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } if (c->noreply) { conn_set_state(c, conn_new_cmd); } else { if (should_return_key) { write_bin_miss_response(c, key, nkey); } else { write_bin_miss_response(c, NULL, 0); } } } if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } } static void append_bin_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *buf = c->stats.buffer + c->stats.offset; uint32_t bodylen = klen + vlen; protocol_binary_response_header header = { .response.magic = (uint8_t)PROTOCOL_BINARY_RES, .response.opcode = PROTOCOL_BINARY_CMD_STAT, .response.keylen = (uint16_t)htons(klen), .response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES, .response.bodylen = htonl(bodylen), .response.opaque = c->opaque }; memcpy(buf, header.bytes, sizeof(header.response)); buf += sizeof(header.response); if (klen > 0) { memcpy(buf, key, klen); buf += klen; if (vlen > 0) { memcpy(buf, val, vlen); } } c->stats.offset += sizeof(header.response) + bodylen; } static void append_ascii_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *pos = c->stats.buffer + c->stats.offset; uint32_t nbytes = 0; int remaining = c->stats.size - c->stats.offset; int room = remaining - 1; if (klen == 0 && vlen == 0) { nbytes = snprintf(pos, room, "END\r\n"); } else if (vlen == 0) { nbytes = snprintf(pos, room, "STAT %s\r\n", key); } else { nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val); } c->stats.offset += nbytes; } static bool grow_stats_buf(conn *c, size_t needed) { size_t nsize = c->stats.size; size_t available = nsize - c->stats.offset; bool rv = true; /* Special case: No buffer -- need to allocate fresh */ if (c->stats.buffer == NULL) { nsize = 1024; available = c->stats.size = c->stats.offset = 0; } while (needed > available) { assert(nsize > 0); nsize = nsize << 1; available = nsize - c->stats.offset; } if (nsize != c->stats.size) { char *ptr = realloc(c->stats.buffer, nsize); if (ptr) { c->stats.buffer = ptr; c->stats.size = nsize; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); rv = false; } } return rv; } static void append_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, const void *cookie) { /* value without a key is invalid */ if (klen == 0 && vlen > 0) { return ; } conn *c = (conn*)cookie; if (c->protocol == binary_prot) { size_t needed = vlen + klen + sizeof(protocol_binary_response_header); if (!grow_stats_buf(c, needed)) { return ; } append_bin_stats(key, klen, val, vlen, c); } else { size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n" if (!grow_stats_buf(c, needed)) { return ; } append_ascii_stats(key, klen, val, vlen, c); } assert(c->stats.offset <= c->stats.size); } static void process_bin_stat(conn *c) { char *subcommand = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int ii; fprintf(stderr, "<%d STATS ", c->sfd); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", subcommand[ii]); } fprintf(stderr, "\n"); } if (nkey == 0) { /* request all statistics */ server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strncmp(subcommand, "reset", 5) == 0) { stats_reset(); } else if (strncmp(subcommand, "settings", 8) == 0) { process_stat_settings(&append_stats, c); } else if (strncmp(subcommand, "detail", 6) == 0) { char *subcmd_pos = subcommand + 6; if (strncmp(subcmd_pos, " dump", 5) == 0) { int len; char *dump_buf = stats_prefix_dump(&len); if (dump_buf == NULL || len <= 0) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); if (dump_buf != NULL) free(dump_buf); return; } else { append_stats("detailed", strlen("detailed"), dump_buf, len, c); free(dump_buf); } } else if (strncmp(subcmd_pos, " on", 3) == 0) { settings.detail_enabled = 1; } else if (strncmp(subcmd_pos, " off", 4) == 0) { settings.detail_enabled = 0; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); return; } } else { if (get_stats(subcommand, nkey, &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } return; } /* Append termination package and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) { assert(c); c->substate = next_substate; c->rlbytes = c->keylen + extra; /* Ok... do we have room for the extras and the key in the input buffer? */ ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf; if (c->rlbytes > c->rsize - offset) { size_t nsize = c->rsize; size_t size = c->rlbytes + sizeof(protocol_binary_request_header); while (size > nsize) { nsize *= 2; } if (nsize != c->rsize) { if (settings.verbose > 1) { fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n", c->sfd, (unsigned long)c->rsize, (unsigned long)nsize); } char *newm = realloc(c->rbuf, nsize); if (newm == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose) { fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n", c->sfd); } conn_set_state(c, conn_closing); return; } c->rbuf= newm; /* rcurr should point to the same offset in the packet */ c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header); c->rsize = nsize; } if (c->rbuf != c->rcurr) { memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Repack input buffer\n", c->sfd); } } } /* preserve the header in the buffer.. */ c->ritem = c->rcurr + sizeof(protocol_binary_request_header); conn_set_state(c, conn_nread); } /* Just write an error message and disconnect the client */ static void handle_binary_protocol_error(conn *c) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0); if (settings.verbose) { fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n", c->binary_header.request.opcode, c->sfd); } c->write_and_go = conn_closing; } static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; c->authenticated = false; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } static void bin_list_sasl_mechs(conn *c) { // Guard against a disabled SASL. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } init_sasl_conn(c); const char *result_string = NULL; unsigned int string_length = 0; int result=sasl_listmech(c->sasl_conn, NULL, "", /* What to prepend the string with */ " ", /* What to separate mechanisms with */ "", /* What to append to the string */ &result_string, &string_length, NULL); if (result != SASL_OK) { /* Perhaps there's a better error for this... */ if (settings.verbose) { fprintf(stderr, "Failed to list SASL mechanisms.\n"); } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } write_bin_response(c, (char*)result_string, 0, 0, string_length); } static void process_bin_sasl_auth(conn *c) { // Guard for handling disabled SASL on the server. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } assert(c->binary_header.request.extlen == 0); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > MAX_SASL_MECH_LEN) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; return; } char *key = binary_get_key(c); assert(key); item *it = item_alloc(key, nkey, 0, 0, vlen+2); /* Can't use a chunked item for SASL authentication. */ if (it == 0 || (it->it_flags & ITEM_CHUNKED)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen); c->write_and_go = conn_swallow; return; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_reading_sasl_auth_data; } static void process_bin_complete_sasl_auth(conn *c) { assert(settings.sasl); const char *out = NULL; unsigned int outlen = 0; assert(c->item); init_sasl_conn(c); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > ((item*) c->item)->nkey) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } char mech[nkey+1]; memcpy(mech, ITEM_key((item*)c->item), nkey); mech[nkey] = 0x00; if (settings.verbose) fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen); const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item); if (vlen > ((item*) c->item)->nbytes) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } int result=-1; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_AUTH: result = sasl_server_start(c->sasl_conn, mech, challenge, vlen, &out, &outlen); c->sasl_started = (result == SASL_OK || result == SASL_CONTINUE); break; case PROTOCOL_BINARY_CMD_SASL_STEP: if (!c->sasl_started) { if (settings.verbose) { fprintf(stderr, "%d: SASL_STEP called but sasl_server_start " "not called for this connection!\n", c->sfd); } break; } result = sasl_server_step(c->sasl_conn, challenge, vlen, &out, &outlen); break; default: assert(false); /* CMD should be one of the above */ /* This code is pretty much impossible, but makes the compiler happier */ if (settings.verbose) { fprintf(stderr, "Unhandled command %d with challenge %s\n", c->cmd, challenge); } break; } item_unlink(c->item); if (settings.verbose) { fprintf(stderr, "sasl result code: %d\n", result); } switch(result) { case SASL_OK: c->authenticated = true; write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated")); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); break; case SASL_CONTINUE: add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen); if(outlen > 0) { add_iov(c, out, outlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; break; default: if (settings.verbose) fprintf(stderr, "Unknown sasl response: %d\n", result); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: rv = c->authenticated; } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } static void dispatch_bin_command(conn *c) { int protocol_error = 0; uint8_t extlen = c->binary_header.request.extlen; uint16_t keylen = c->binary_header.request.keylen; uint32_t bodylen = c->binary_header.request.bodylen; if (keylen > bodylen || keylen + extlen > bodylen) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0); c->write_and_go = conn_closing; return; } if (settings.sasl && !authenticated(c)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); c->write_and_go = conn_closing; return; } MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); c->noreply = true; /* binprot supports 16bit keys, but internals are still 8bit */ if (keylen > KEY_MAX_LENGTH) { handle_binary_protocol_error(c); return; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_SETQ: c->cmd = PROTOCOL_BINARY_CMD_SET; break; case PROTOCOL_BINARY_CMD_ADDQ: c->cmd = PROTOCOL_BINARY_CMD_ADD; break; case PROTOCOL_BINARY_CMD_REPLACEQ: c->cmd = PROTOCOL_BINARY_CMD_REPLACE; break; case PROTOCOL_BINARY_CMD_DELETEQ: c->cmd = PROTOCOL_BINARY_CMD_DELETE; break; case PROTOCOL_BINARY_CMD_INCREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_INCREMENT; break; case PROTOCOL_BINARY_CMD_DECREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_DECREMENT; break; case PROTOCOL_BINARY_CMD_QUITQ: c->cmd = PROTOCOL_BINARY_CMD_QUIT; break; case PROTOCOL_BINARY_CMD_FLUSHQ: c->cmd = PROTOCOL_BINARY_CMD_FLUSH; break; case PROTOCOL_BINARY_CMD_APPENDQ: c->cmd = PROTOCOL_BINARY_CMD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPENDQ: c->cmd = PROTOCOL_BINARY_CMD_PREPEND; break; case PROTOCOL_BINARY_CMD_GETQ: c->cmd = PROTOCOL_BINARY_CMD_GET; break; case PROTOCOL_BINARY_CMD_GETKQ: c->cmd = PROTOCOL_BINARY_CMD_GETK; break; case PROTOCOL_BINARY_CMD_GATQ: c->cmd = PROTOCOL_BINARY_CMD_GAT; break; case PROTOCOL_BINARY_CMD_GATKQ: c->cmd = PROTOCOL_BINARY_CMD_GATK; break; default: c->noreply = false; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_VERSION: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, VERSION, 0, 0, strlen(VERSION)); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_FLUSH: if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) { bin_read_key(c, bin_read_flush_exptime, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_NOOP: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_REPLACE: if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) { bin_read_key(c, bin_reading_set_header, 8); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETK: if (extlen == 0 && bodylen == keylen && keylen > 0) { bin_read_key(c, bin_reading_get_key, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_DELETE: if (keylen > 0 && extlen == 0 && bodylen == keylen) { bin_read_key(c, bin_reading_del_header, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_INCREMENT: case PROTOCOL_BINARY_CMD_DECREMENT: if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) { bin_read_key(c, bin_reading_incr_header, 20); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_APPEND: case PROTOCOL_BINARY_CMD_PREPEND: if (keylen > 0 && extlen == 0) { bin_read_key(c, bin_reading_set_header, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_STAT: if (extlen == 0) { bin_read_key(c, bin_reading_stat, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_QUIT: if (keylen == 0 && extlen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); c->write_and_go = conn_closing; if (c->noreply) { conn_set_state(c, conn_closing); } } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: if (extlen == 0 && keylen == 0 && bodylen == 0) { bin_list_sasl_mechs(c); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_AUTH: case PROTOCOL_BINARY_CMD_SASL_STEP: if (extlen == 0 && keylen != 0) { bin_read_key(c, bin_reading_sasl_auth, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_TOUCH: case PROTOCOL_BINARY_CMD_GAT: case PROTOCOL_BINARY_CMD_GATQ: case PROTOCOL_BINARY_CMD_GATK: case PROTOCOL_BINARY_CMD_GATKQ: if (extlen == 4 && keylen != 0) { bin_read_key(c, bin_reading_touch_key, 4); } else { protocol_error = 1; } break; default: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, bodylen); } if (protocol_error) handle_binary_protocol_error(c); } static void process_bin_update(conn *c) { char *key; int nkey; int vlen; item *it; protocol_binary_request_set* req = binary_get_request(c); assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; /* fix byteorder in the request */ req->message.body.flags = ntohl(req->message.body.flags); req->message.body.expiration = ntohl(req->message.body.expiration); vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen); if (settings.verbose > 1) { int ii; if (c->cmd == PROTOCOL_BINARY_CMD_ADD) { fprintf(stderr, "<%d ADD ", c->sfd); } else if (c->cmd == PROTOCOL_BINARY_CMD_SET) { fprintf(stderr, "<%d SET ", c->sfd); } else { fprintf(stderr, "<%d REPLACE ", c->sfd); } for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, " Value len is %d", vlen); fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, req->message.body.flags, realtime(req->message.body.expiration), vlen+2); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* This error generating method eats the swallow value. Add here. */ c->sbytes = vlen; status = NO_MEMORY; } /* FIXME: losing c->cmd since it's translated below. refactor? */ LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, 0, key, nkey, req->message.body.expiration, ITEM_clsid(it), c->sfd); /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (c->cmd == PROTOCOL_BINARY_CMD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_ADD: c->cmd = NREAD_ADD; break; case PROTOCOL_BINARY_CMD_SET: c->cmd = NREAD_SET; break; case PROTOCOL_BINARY_CMD_REPLACE: c->cmd = NREAD_REPLACE; break; default: assert(0); } if (ITEM_get_cas(it) != 0) { c->cmd = NREAD_CAS; } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_append_prepend(conn *c) { char *key; int nkey; int vlen; item *it; assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; vlen = c->binary_header.request.bodylen - nkey; if (settings.verbose > 1) { fprintf(stderr, "Value len is %d\n", vlen); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, 0, 0, vlen+2); if (it == 0) { if (! item_size_ok(nkey, 0, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* OOM calls eat the swallow value. Add here. */ c->sbytes = vlen; } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_APPEND: c->cmd = NREAD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPEND: c->cmd = NREAD_PREPEND; break; default: assert(0); } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_flush(conn *c) { time_t exptime = 0; protocol_binary_request_flush* req = binary_get_request(c); rel_time_t new_oldest = 0; if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } if (c->binary_header.request.extlen == sizeof(req->message.body)) { exptime = ntohl(req->message.body.expiration); } if (exptime > 0) { new_oldest = realtime(exptime); } else { new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_response(c, NULL, 0, 0, 0); } static void process_bin_delete(conn *c) { item *it; uint32_t hv; protocol_binary_request_delete* req = binary_get_request(c); char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; assert(c != NULL); if (settings.verbose > 1) { int ii; fprintf(stderr, "Deleting "); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { uint64_t cas = ntohll(req->message.header.request.cas); if (cas == 0 || cas == ITEM_get_cas(it)) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); write_bin_response(c, NULL, 0, 0, 0); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); } do_item_remove(it); /* release our reference */ } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } item_unlock(hv); } static void complete_nread_binary(conn *c) { assert(c != NULL); assert(c->cmd >= 0); switch(c->substate) { case bin_reading_set_header: if (c->cmd == PROTOCOL_BINARY_CMD_APPEND || c->cmd == PROTOCOL_BINARY_CMD_PREPEND) { process_bin_append_prepend(c); } else { process_bin_update(c); } break; case bin_read_set_value: complete_update_bin(c); break; case bin_reading_get_key: case bin_reading_touch_key: process_bin_get_or_touch(c); break; case bin_reading_stat: process_bin_stat(c); break; case bin_reading_del_header: process_bin_delete(c); break; case bin_reading_incr_header: complete_incr_bin(c); break; case bin_read_flush_exptime: process_bin_flush(c); break; case bin_reading_sasl_auth: process_bin_sasl_auth(c); break; case bin_reading_sasl_auth_data: process_bin_complete_sasl_auth(c); break; default: fprintf(stderr, "Not handling substate %d\n", c->substate); assert(0); } } static void reset_cmd_handler(conn *c) { c->cmd = -1; c->substate = bin_no_state; if(c->item != NULL) { item_remove(c->item); c->item = NULL; } conn_shrink(c); if (c->rbytes > 0) { conn_set_state(c, conn_parse_cmd); } else { conn_set_state(c, conn_waiting); } } static void complete_nread(conn *c) { assert(c != NULL); assert(c->protocol == ascii_prot || c->protocol == binary_prot); if (c->protocol == ascii_prot) { complete_nread_ascii(c); } else if (c->protocol == binary_prot) { complete_nread_binary(c); } } /* Destination must always be chunked */ /* This should be part of item.c */ static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) { item_chunk *dch = (item_chunk *) ITEM_schunk(d_it); /* Advance dch until we find free space */ while (dch->size == dch->used) { if (dch->next) { dch = dch->next; } else { break; } } if (s_it->it_flags & ITEM_CHUNKED) { int remain = len; item_chunk *sch = (item_chunk *) ITEM_schunk(s_it); int copied = 0; /* Fills dch's to capacity, not straight copy sch in case data is * being added or removed (ie append/prepend) */ while (sch && dch && remain) { assert(dch->used <= dch->size); int todo = (dch->size - dch->used < sch->used - copied) ? dch->size - dch->used : sch->used - copied; if (remain < todo) todo = remain; memcpy(dch->data + dch->used, sch->data + copied, todo); dch->used += todo; copied += todo; remain -= todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, remain); if (tch) { dch = tch; } else { return -1; } } assert(copied <= sch->used); if (copied == sch->used) { copied = 0; sch = sch->next; } } /* assert that the destination had enough space for the source */ assert(remain == 0); } else { int done = 0; /* Fill dch's via a non-chunked item. */ while (len > done && dch) { int todo = (dch->size - dch->used < len - done) ? dch->size - dch->used : len - done; //assert(dch->size - dch->used != 0); memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo); done += todo; dch->used += todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, len - done); if (tch) { dch = tch; } else { return -1; } } } assert(len == done); } return 0; } static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) { if (comm == NREAD_APPEND) { if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes); memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes); } } else { /* NREAD_PREPEND */ if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes); memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes); } } return 0; } /* * Stores an item in the cache according to the semantics of one of the set * commands. In threaded mode, this is protected by the cache lock. * * Returns the state of storage. */ enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) { char *key = ITEM_key(it); item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE); enum store_item_type stored = NOT_STORED; item *new_it = NULL; uint32_t flags; if (old_it != NULL && comm == NREAD_ADD) { /* add only adds a nonexistent item, but promote to head of LRU */ do_item_update(old_it); } else if (!old_it && (comm == NREAD_REPLACE || comm == NREAD_APPEND || comm == NREAD_PREPEND)) { /* replace only replaces an existing value; don't store */ } else if (comm == NREAD_CAS) { /* validate cas operation */ if(old_it == NULL) { // LRU expired stored = NOT_FOUND; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.cas_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) { // cas validates // it and old_it may belong to different classes. // I'm updating the stats for the one that's getting pushed out pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); stored = STORED; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++; pthread_mutex_unlock(&c->thread->stats.mutex); if(settings.verbose > 1) { fprintf(stderr, "CAS: failure: expected %llu, got %llu\n", (unsigned long long)ITEM_get_cas(old_it), (unsigned long long)ITEM_get_cas(it)); } stored = EXISTS; } } else { int failed_alloc = 0; /* * Append - combine new and old record into single one. Here it's * atomic and thread-safe. */ if (comm == NREAD_APPEND || comm == NREAD_PREPEND) { /* * Validate CAS */ if (ITEM_get_cas(it) != 0) { // CAS much be equal if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) { stored = EXISTS; } } #ifdef EXTSTORE if ((old_it->it_flags & ITEM_HDR) != 0) { /* block append/prepend from working with extstore-d items. * also don't replace the header with the append chunk * accidentally, so mark as a failed_alloc. */ failed_alloc = 1; } else #endif if (stored == NOT_STORED) { /* we have it and old_it here - alloc memory to hold both */ /* flags was already lost - so recover them from ITEM_suffix(it) */ FLAGS_CONV(old_it, flags); new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */); /* copy data from it and old_it to new_it */ if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) { failed_alloc = 1; stored = NOT_STORED; // failed data copy, free up. if (new_it != NULL) item_remove(new_it); } else { it = new_it; } } } if (stored == NOT_STORED && failed_alloc == 0) { if (old_it != NULL) { STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); } else { do_item_link(it, hv); } c->cas = ITEM_get_cas(it); stored = STORED; } } if (old_it != NULL) do_item_remove(old_it); /* release our reference */ if (new_it != NULL) do_item_remove(new_it); if (stored == STORED) { c->cas = ITEM_get_cas(it); } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it), c->sfd); return stored; } typedef struct token_s { char *value; size_t length; } token_t; #define COMMAND_TOKEN 0 #define SUBCOMMAND_TOKEN 1 #define KEY_TOKEN 1 #define MAX_TOKENS 8 /* * Tokenize the command string by replacing whitespace with '\0' and update * the token array tokens with pointer to start of each token and length. * Returns total number of tokens. The last valid token is the terminal * token (value points to the first unprocessed character of the string and * length zero). * * Usage example: * * while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) { * for(int ix = 0; tokens[ix].length != 0; ix++) { * ... * } * ncommand = tokens[ix].value - command; * command = tokens[ix].value; * } */ static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) { char *s, *e; size_t ntokens = 0; size_t len = strlen(command); unsigned int i = 0; assert(command != NULL && tokens != NULL && max_tokens > 1); s = e = command; for (i = 0; i < len; i++) { if (*e == ' ') { if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; *e = '\0'; if (ntokens == max_tokens - 1) { e++; s = e; /* so we don't add an extra token */ break; } } s = e + 1; } e++; } if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; } /* * If we scanned the whole string, the terminal value pointer is null, * otherwise it is the first unprocessed character. */ tokens[ntokens].value = *e == '\0' ? NULL : e; tokens[ntokens].length = 0; ntokens++; return ntokens; } /* set up a connection to write a buffer then free it, used for stats */ static void write_and_free(conn *c, char *buf, int bytes) { if (buf) { c->write_and_free = buf; c->wcurr = buf; c->wbytes = bytes; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; } else { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } } static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens) { int noreply_index = ntokens - 2; /* NOTE: this function is not the first place where we are going to send the reply. We could send it instead from process_command() if the request line has wrong number of tokens. However parsing malformed line for "noreply" option is not reliable anyway, so it can't be helped. */ if (tokens[noreply_index].value && strcmp(tokens[noreply_index].value, "noreply") == 0) { c->noreply = true; } return c->noreply; } void append_stat(const char *name, ADD_STAT add_stats, conn *c, const char *fmt, ...) { char val_str[STAT_VAL_LEN]; int vlen; va_list ap; assert(name); assert(add_stats); assert(c); assert(fmt); va_start(ap, fmt); vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap); va_end(ap); add_stats(name, strlen(name), val_str, vlen, c); } inline static void process_stats_detail(conn *c, const char *command) { assert(c != NULL); if (strcmp(command, "on") == 0) { settings.detail_enabled = 1; out_string(c, "OK"); } else if (strcmp(command, "off") == 0) { settings.detail_enabled = 0; out_string(c, "OK"); } else if (strcmp(command, "dump") == 0) { int len; char *stats = stats_prefix_dump(&len); write_and_free(c, stats, len); } else { out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump"); } } /* return server specific stats only */ static void server_stats(ADD_STAT add_stats, conn *c) { pid_t pid = getpid(); rel_time_t now = current_time; struct thread_stats thread_stats; threadlocal_stats_aggregate(&thread_stats); struct slab_stats slab_stats; slab_stats_aggregate(&thread_stats, &slab_stats); #ifdef EXTSTORE struct extstore_stats st; #endif #ifndef WIN32 struct rusage usage; getrusage(RUSAGE_SELF, &usage); #endif /* !WIN32 */ STATS_LOCK(); APPEND_STAT("pid", "%lu", (long)pid); APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL); APPEND_STAT("time", "%ld", now + (long)process_started); APPEND_STAT("version", "%s", VERSION); APPEND_STAT("libevent", "%s", event_get_version()); APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *))); #ifndef WIN32 append_stat("rusage_user", add_stats, c, "%ld.%06ld", (long)usage.ru_utime.tv_sec, (long)usage.ru_utime.tv_usec); append_stat("rusage_system", add_stats, c, "%ld.%06ld", (long)usage.ru_stime.tv_sec, (long)usage.ru_stime.tv_usec); #endif /* !WIN32 */ APPEND_STAT("max_connections", "%d", settings.maxconns); APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1); APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns); if (settings.maxconns_fast) { APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns); } APPEND_STAT("connection_structures", "%u", stats_state.conn_structs); APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds); APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds); APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds); APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds); APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds); APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits); APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses); APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired); APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed); #ifdef EXTSTORE if (c->thread->storage) { APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore); APPEND_STAT("get_aborted_extstore", "%llu", (unsigned long long)thread_stats.get_aborted_extstore); APPEND_STAT("get_oom_extstore", "%llu", (unsigned long long)thread_stats.get_oom_extstore); APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore); APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore); APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore); } #endif APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses); APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits); APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses); APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits); APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses); APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits); APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses); APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits); APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval); APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits); APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses); APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds); APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors); if (settings.idle_timeout) { APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks); } APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read); APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written); APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns); APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num); APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us); APPEND_STAT("threads", "%d", settings.num_threads); APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields); APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level); APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes); APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding); if (settings.slab_reassign) { APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues); APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues); APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem); APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim); APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items); APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes); APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running); APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved); } if (settings.lru_crawler) { APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running); APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts); } if (settings.lru_maintainer_thread) { APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles); } APPEND_STAT("malloc_fails", "%llu", (unsigned long long)stats.malloc_fails); APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped); APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written); APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped); APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent); STATS_UNLOCK(); #ifdef EXTSTORE if (c->thread->storage) { STATS_LOCK(); APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost); APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues); APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped); STATS_UNLOCK(); extstore_get_stats(c->thread->storage, &st); APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs); APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions); APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims); APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free); APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used); APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted); APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read); APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written); APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used); APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted); APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written); APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read); APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used); APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented); APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size)); APPEND_STAT("extstore_io_queue", "%llu", (unsigned long long)(st.io_queue)); } #endif #ifdef TLS if (settings.ssl_enabled) { SSL_LOCK(); APPEND_STAT("time_since_server_cert_refresh", "%u", now - settings.ssl_last_cert_refresh_time); SSL_UNLOCK(); } #endif } static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("auth_enabled_ascii", "%s", settings.auth_file ? settings.auth_file : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio); APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", "no"); // setting is dead, cannot be yes. #ifdef HAVE_DROP_PRIVILEGES APPEND_STAT("drop_privileges", "%s", settings.drop_privileges ? "yes" : "no"); #endif #ifdef EXTSTORE APPEND_STAT("ext_item_size", "%u", settings.ext_item_size); APPEND_STAT("ext_item_age", "%u", settings.ext_item_age); APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl); APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate); APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size); APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under); APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under); APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag); APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio); APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no"); #endif #ifdef TLS APPEND_STAT("ssl_enabled", "%s", settings.ssl_enabled ? "yes" : "no"); APPEND_STAT("ssl_chain_cert", "%s", settings.ssl_chain_cert); APPEND_STAT("ssl_key", "%s", settings.ssl_key); APPEND_STAT("ssl_verify_mode", "%d", settings.ssl_verify_mode); APPEND_STAT("ssl_keyformat", "%d", settings.ssl_keyformat); APPEND_STAT("ssl_ciphers", "%s", settings.ssl_ciphers ? settings.ssl_ciphers : "NULL"); APPEND_STAT("ssl_ca_cert", "%s", settings.ssl_ca_cert ? settings.ssl_ca_cert : "NULL"); APPEND_STAT("ssl_wbuf_size", "%u", settings.ssl_wbuf_size); #endif } static int nz_strcmp(int nzlength, const char *nz, const char *z) { int zlength=strlen(z); return (zlength == nzlength) && (strncmp(nz, z, zlength) == 0) ? 0 : -1; } static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c) { bool ret = true; if (add_stats != NULL) { if (!stat_type) { /* prepare general statistics for the engine */ STATS_LOCK(); APPEND_STAT("bytes", "%llu", (unsigned long long)stats_state.curr_bytes); APPEND_STAT("curr_items", "%llu", (unsigned long long)stats_state.curr_items); APPEND_STAT("total_items", "%llu", (unsigned long long)stats.total_items); STATS_UNLOCK(); APPEND_STAT("slab_global_page_pool", "%u", global_page_pool_size(NULL)); item_stats_totals(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "items") == 0) { item_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "slabs") == 0) { slabs_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes") == 0) { item_stats_sizes(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_enable") == 0) { item_stats_sizes_enable(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_disable") == 0) { item_stats_sizes_disable(add_stats, c); } else { ret = false; } } else { ret = false; } return ret; } static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; size_t pathlen = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: // this strncpy call originally could piss off an address // sanitizer; we supplied the size of the dest buf as a limiter, // but optimized versions of strncpy could read past the end of // *src while looking for a null terminator. Since buf and // sun_path here are both on the stack they could even overlap, // which is "undefined". In all OSS versions of strncpy I could // find this has no effect; it'll still only copy until the first null // terminator is found. Thus it's possible to get the OS to // examine past the end of sun_path but it's unclear to me if this // can cause any actual problem. // // We need a safe_strncpy util function but I'll punt on figuring // that out for now. pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path); if (MAXPATHLEN <= pathlen) { pathlen = MAXPATHLEN - 1; } strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, pathlen); addr_text[pathlen] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } } static void conn_to_str(const conn *c, char *addr, char *svr_addr) { if (!c) { strcpy(addr, "<null>"); } else if (c->state == conn_closed) { strcpy(addr, "<closed>"); } else { struct sockaddr_in6 local_addr; struct sockaddr *sock_addr = (void *)&c->request_addr; /* For listen ports and idle UDP ports, show listen address */ if (c->state == conn_listening || (IS_UDP(c->transport) && c->state == conn_read)) { socklen_t local_addr_len = sizeof(local_addr); if (getsockname(c->sfd, (struct sockaddr *)&local_addr, &local_addr_len) == 0) { sock_addr = (struct sockaddr *)&local_addr; } } get_conn_text(c, sock_addr->sa_family, addr, sock_addr); if (c->state != conn_listening && !(IS_UDP(c->transport) && c->state == conn_read)) { struct sockaddr_storage svr_sock_addr; socklen_t svr_addr_len = sizeof(svr_sock_addr); getsockname(c->sfd, (struct sockaddr *)&svr_sock_addr, &svr_addr_len); get_conn_text(c, svr_sock_addr.ss_family, svr_addr, (struct sockaddr *)&svr_sock_addr); } } } static void process_stats_conns(ADD_STAT add_stats, void *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; size_t extras_len = sizeof("unix:") + sizeof("65535"); char addr[MAXPATHLEN + extras_len]; char svr_addr[MAXPATHLEN + extras_len]; int klen = 0, vlen = 0; assert(add_stats); for (i = 0; i < max_fds; i++) { if (conns[i]) { /* This is safe to do unlocked because conns are never freed; the * worst that'll happen will be a minor inconsistency in the * output -- not worth the complexity of the locking that'd be * required to prevent it. */ if (IS_UDP(conns[i]->transport)) { APPEND_NUM_STAT(i, "UDP", "%s", "UDP"); } if (conns[i]->state != conn_closed) { conn_to_str(conns[i], addr, svr_addr); APPEND_NUM_STAT(i, "addr", "%s", addr); if (conns[i]->state != conn_listening && !(IS_UDP(conns[i]->transport) && conns[i]->state == conn_read)) { APPEND_NUM_STAT(i, "listen_addr", "%s", svr_addr); } APPEND_NUM_STAT(i, "state", "%s", state_text(conns[i]->state)); APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d", current_time - conns[i]->last_cmd_time); } } } } #ifdef EXTSTORE static void process_extstore_stats(ADD_STAT add_stats, conn *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; int klen = 0, vlen = 0; struct extstore_stats st; assert(add_stats); void *storage = c->thread->storage; extstore_get_stats(storage, &st); st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data)); extstore_get_page_data(storage, &st); for (i = 0; i < st.page_count; i++) { APPEND_NUM_STAT(i, "version", "%llu", (unsigned long long) st.page_data[i].version); APPEND_NUM_STAT(i, "bytes", "%llu", (unsigned long long) st.page_data[i].bytes_used); APPEND_NUM_STAT(i, "bucket", "%u", st.page_data[i].bucket); APPEND_NUM_STAT(i, "free_bucket", "%u", st.page_data[i].free_bucket); } } #endif static void process_stat(conn *c, token_t *tokens, const size_t ntokens) { const char *subcommand = tokens[SUBCOMMAND_TOKEN].value; assert(c != NULL); if (ntokens < 2) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (ntokens == 2) { server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strcmp(subcommand, "reset") == 0) { stats_reset(); out_string(c, "RESET"); return ; } else if (strcmp(subcommand, "detail") == 0) { /* NOTE: how to tackle detail with binary? */ if (ntokens < 4) process_stats_detail(c, ""); /* outputs the error message */ else process_stats_detail(c, tokens[2].value); /* Output already generated */ return ; } else if (strcmp(subcommand, "settings") == 0) { process_stat_settings(&append_stats, c); } else if (strcmp(subcommand, "cachedump") == 0) { char *buf; unsigned int bytes, id, limit = 0; if (!settings.dump_enabled) { out_string(c, "CLIENT_ERROR stats cachedump not allowed"); return; } if (ntokens < 5) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (!safe_strtoul(tokens[2].value, &id) || !safe_strtoul(tokens[3].value, &limit)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (id >= MAX_NUMBER_OF_SLAB_CLASSES) { out_string(c, "CLIENT_ERROR Illegal slab id"); return; } buf = item_cachedump(id, limit, &bytes); write_and_free(c, buf, bytes); return ; } else if (strcmp(subcommand, "conns") == 0) { process_stats_conns(&append_stats, c); #ifdef EXTSTORE } else if (strcmp(subcommand, "extstore") == 0) { process_extstore_stats(&append_stats, c); #endif } else { /* getting here means that the subcommand is either engine specific or is invalid. query the engine and see. */ if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { out_string(c, "ERROR"); } return ; } /* append terminator and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } /* client flags == 0 means use no storage for client flags */ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) { char *p = suffix; *p = ' '; p++; if (FLAGS_SIZE(it) == 0) { *p = '0'; p++; } else { p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p); } *p = ' '; p = itoa_u32(nbytes-2, p+1); if (return_cas) { *p = ' '; p = itoa_u64(ITEM_get_cas(it), p+1); } *p = '\r'; *(p+1) = '\n'; *(p+2) = '\0'; return (p - suffix) + 2; } #define IT_REFCOUNT_LIMIT 60000 static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) { item *it; if (should_touch) { it = item_touch(key, nkey, exptime, c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it && it->refcount > IT_REFCOUNT_LIMIT) { item_remove(it); it = NULL; } return it; } static inline int _ascii_get_expand_ilist(conn *c, int i) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } } return 0; } static inline char *_ascii_get_suffix_buf(conn *c, int i) { char *suffix; /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return NULL; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); return NULL; } *(c->suffixlist + i) = suffix; return suffix; } #ifdef EXTSTORE // FIXME: This runs in the IO thread. to get better IO performance this should // simply mark the io wrapper with the return value and decrement wrapleft, if // zero redispatching. Still a bit of work being done in the side thread but // minimized at least. static void _get_extstore_cb(void *e, obj_io *io, int ret) { // FIXME: assumes success io_wrap *wrap = (io_wrap *)io->data; conn *c = wrap->c; assert(wrap->active == true); item *read_it = (item *)io->buf; bool miss = false; // TODO: How to do counters for hit/misses? if (ret < 1) { miss = true; } else { uint32_t crc2; uint32_t crc = (uint32_t) read_it->exptime; int x; // item is chunked, crc the iov's if (io->iov != NULL) { // first iov is the header, which we don't use beyond crc crc2 = crc32c(0, (char *)io->iov[0].iov_base+STORE_OFFSET, io->iov[0].iov_len-STORE_OFFSET); // make sure it's not sent. hack :( io->iov[0].iov_len = 0; for (x = 1; x < io->iovcnt; x++) { crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len); } } else { crc2 = crc32c(0, (char *)read_it+STORE_OFFSET, io->len-STORE_OFFSET); } if (crc != crc2) { miss = true; wrap->badcrc = true; } } if (miss) { int i; struct iovec *v; // TODO: This should be movable to the worker thread. if (c->protocol == binary_prot) { protocol_binary_response_header *header = (protocol_binary_response_header *)c->wbuf; // this zeroes out the iovecs since binprot never stacks them. if (header->response.keylen) { write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey); } else { write_bin_miss_response(c, 0, 0); } } else { for (i = 0; i < wrap->iovec_count; i++) { v = &c->iov[wrap->iovec_start + i]; v->iov_len = 0; v->iov_base = NULL; } } wrap->miss = true; } else { assert(read_it->slabs_clsid != 0); // kill \r\n for binprot if (io->iov == NULL) { c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it); if (c->protocol == binary_prot) c->iov[wrap->iovec_data].iov_len -= 2; } else { // FIXME: Might need to go back and ensure chunked binprots don't // ever span two chunks for the final \r\n if (c->protocol == binary_prot) { if (io->iov[io->iovcnt-1].iov_len >= 2) { io->iov[io->iovcnt-1].iov_len -= 2; } else { io->iov[io->iovcnt-1].iov_len = 0; io->iov[io->iovcnt-2].iov_len -= 1; } } } wrap->miss = false; // iov_len is already set // TODO: Should do that here instead and cuddle in the wrap object } c->io_wrapleft--; wrap->active = false; //assert(c->io_wrapleft >= 0); // All IO's have returned, lets re-attach this connection to our original // thread. if (c->io_wrapleft == 0) { assert(c->io_queued == true); c->io_queued = false; redispatch_conn(c); } } // FIXME: This completely breaks UDP support. static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) { #ifdef NEED_ALIGN item_hdr hdr; memcpy(&hdr, ITEM_data(it), sizeof(hdr)); #else item_hdr *hdr = (item_hdr *)ITEM_data(it); #endif size_t ntotal = ITEM_ntotal(it); unsigned int clsid = slabs_clsid(ntotal); item *new_it; bool chunked = false; if (ntotal > settings.slab_chunk_size_max) { // Pull a chunked item header. uint32_t flags; FLAGS_CONV(it, flags); new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes); assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED)); chunked = true; } else { new_it = do_item_alloc_pull(ntotal, clsid); } if (new_it == NULL) return -1; assert(!c->io_queued); // FIXME: debugging. // so we can free the chunk on a miss new_it->slabs_clsid = clsid; io_wrap *io = do_cache_alloc(c->thread->io_cache); io->active = true; io->miss = false; io->badcrc = false; // io_wrap owns the reference for this object now. io->hdr_it = it; // FIXME: error handling. // The offsets we'll wipe on a miss. io->iovec_start = iovst; io->iovec_count = iovcnt; // This is probably super dangerous. keep it at 0 and fill into wrap // object? if (chunked) { unsigned int ciovcnt = 1; size_t remain = new_it->nbytes; item_chunk *chunk = (item_chunk *) ITEM_schunk(new_it); io->io.iov = &c->iov[c->iovused]; // fill the header so we can get the full data + crc back. add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes); while (remain > 0) { chunk = do_item_alloc_chunk(chunk, remain); if (chunk == NULL) { item_remove(new_it); do_cache_free(c->thread->io_cache, io); return -1; } add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size); chunk->used = (remain < chunk->size) ? remain : chunk->size; remain -= chunk->size; ciovcnt++; } io->io.iovcnt = ciovcnt; // header object was already accounted for, remove one from total io->iovec_count += ciovcnt-1; } else { io->io.iov = NULL; io->iovec_data = c->iovused; add_iov(c, "", it->nbytes); } io->io.buf = (void *)new_it; // The offset we'll fill in on a hit. io->c = c; // We need to stack the sub-struct IO's together as well. if (c->io_wraplist) { io->io.next = &c->io_wraplist->io; } else { io->io.next = NULL; } // IO queue for this connection. io->next = c->io_wraplist; c->io_wraplist = io; assert(c->io_wrapleft >= 0); c->io_wrapleft++; // reference ourselves for the callback. io->io.data = (void *)io; // Now, fill in io->io based on what was in our header. #ifdef NEED_ALIGN io->io.page_version = hdr.page_version; io->io.page_id = hdr.page_id; io->io.offset = hdr.offset; #else io->io.page_version = hdr->page_version; io->io.page_id = hdr->page_id; io->io.offset = hdr->offset; #endif io->io.len = ntotal; io->io.mode = OBJ_IO_READ; io->io.cb = _get_extstore_cb; //fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data); // FIXME: This stat needs to move to reflect # of flash hits vs misses // for now it's a good gauge on how often we request out to flash at // least. pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); return 0; } #endif /* ntokens is overwritten here... shrug.. */ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) { char *key; size_t nkey; int i = 0; int si = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; int32_t exptime_int = 0; rel_time_t exptime = 0; bool fail_length = false; assert(c != NULL); if (should_touch) { // For get and touch commands, use first token as exptime if (!safe_strtol(tokens[1].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } key_token++; exptime = realtime(exptime_int); } do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if (nkey > KEY_MAX_LENGTH) { fail_length = true; goto stop; } it = limited_get(key, nkey, c, exptime, should_touch); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (_ascii_get_expand_ilist(c, i) != 0) { item_remove(it); goto stop; } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); int nbytes; suffix = _ascii_get_suffix_buf(c, si); if (suffix == NULL) { item_remove(it); goto stop; } si++; nbytes = it->nbytes; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); goto stop; } #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { if (_get_extstore(c, it, c->iovused-3, 4) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); item_remove(it); goto stop; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { #else if ((it->it_flags & ITEM_CHUNKED) == 0) { #endif add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); goto stop; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.lru_hits[it->slabs_clsid]++; c->thread->stats.get_cmds++; } pthread_mutex_unlock(&c->thread->stats.mutex); #ifdef EXTSTORE /* If ITEM_HDR, an io_wrap owns the reference. */ if ((it->it_flags & ITEM_HDR) == 0) { *(c->ilist + i) = it; i++; } #else *(c->ilist + i) = it; i++; #endif } else { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_misses++; c->thread->stats.get_cmds++; } MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); pthread_mutex_unlock(&c->thread->stats.mutex); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); stop: c->icurr = c->ilist; c->ileft = i; c->suffixcurr = c->suffixlist; c->suffixleft = si; if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { if (fail_length) { out_string(c, "CLIENT_ERROR bad command line format"); } else { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } conn_release_items(c); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { char *key; size_t nkey; unsigned int flags; int32_t exptime_int = 0; time_t exptime; int vlen; uint64_t req_cas_id=0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags) && safe_strtol(tokens[3].value, &exptime_int) && safe_strtol(tokens[4].value, (int32_t *)&vlen))) { out_string(c, "CLIENT_ERROR bad command line format"); return; } /* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */ exptime = exptime_int; /* Negative exptimes can underflow and end up immortal. realtime() will immediately expire values that are greater than REALTIME_MAXDELTA, but less than process_started, so lets aim for that. */ if (exptime < 0) exptime = REALTIME_MAXDELTA + 1; // does cas value exist? if (handle_cas) { if (!safe_strtoull(tokens[5].value, &req_cas_id)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } if (vlen < 0 || vlen > (INT_MAX - 2)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } vlen += 2; if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, flags, realtime(exptime), vlen); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, flags, vlen)) { out_string(c, "SERVER_ERROR object too large for cache"); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR out of memory storing object"); status = NO_MEMORY; } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, comm, key, nkey, 0, 0, c->sfd); /* swallow the data line */ c->write_and_go = conn_swallow; c->sbytes = vlen; /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (comm == NREAD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } return; } ITEM_set_cas(it, req_cas_id); c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = it->nbytes; c->cmd = comm; conn_set_state(c, conn_nread); } static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; int32_t exptime_int = 0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtol(tokens[2].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } it = item_touch(key, nkey, realtime(exptime_int), c); if (it) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "TOUCHED"); item_remove(it); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) { char temp[INCR_MAX_STORAGE_LEN]; uint64_t delta; char *key; size_t nkey; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtoull(tokens[2].value, &delta)) { out_string(c, "CLIENT_ERROR invalid numeric delta argument"); return; } switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) { case OK: out_string(c, temp); break; case NON_NUMERIC: out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value"); break; case EOM: out_of_memory(c, "SERVER_ERROR out of memory"); break; case DELTA_ITEM_NOT_FOUND: pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); break; case DELTA_ITEM_CAS_MISMATCH: break; /* Should never get here */ } } /* * adds a delta value to a numeric item. * * c connection requesting the operation * it item to adjust * incr true to increment value, false to decrement * delta amount to adjust value by * buf buffer for response string * * returns a response string to send back to the client. */ enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, const bool incr, const int64_t delta, char *buf, uint64_t *cas, const uint32_t hv) { char *ptr; uint64_t value; int res; item *it; it = do_item_get(key, nkey, hv, c, DONT_UPDATE); if (!it) { return DELTA_ITEM_NOT_FOUND; } /* Can't delta zero byte values. 2-byte are the "\r\n" */ /* Also can't delta for chunked items. Too large to be a number */ #ifdef EXTSTORE if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) { #else if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) { #endif do_item_remove(it); return NON_NUMERIC; } if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { do_item_remove(it); return DELTA_ITEM_CAS_MISMATCH; } ptr = ITEM_data(it); if (!safe_strtoull(ptr, &value)) { do_item_remove(it); return NON_NUMERIC; } if (incr) { value += delta; MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); } else { if(delta > value) { value = 0; } else { value -= delta; } MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); } pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; } else { c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); itoa_u64(value, buf); res = strlen(buf); /* refcount == 2 means we are the only ones holding the item, and it is * linked. We hold the item's lock in this function, so refcount cannot * increase. */ if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ /* When changing the value without replacing the item, we need to update the CAS on the existing item. */ /* We also need to fiddle it in the sizes tracker in case the tracking * was enabled at runtime, since it relies on the CAS value to know * whether to remove an item or not. */ item_stats_sizes_remove(it); ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); item_stats_sizes_add(it); memcpy(ITEM_data(it), buf, res); memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); do_item_update(it); } else if (it->refcount > 1) { item *new_it; uint32_t flags; FLAGS_CONV(it, flags); new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); if (new_it == 0) { do_item_remove(it); return EOM; } memcpy(ITEM_data(new_it), buf, res); memcpy(ITEM_data(new_it) + res, "\r\n", 2); item_replace(it, new_it, hv); // Overwrite the older item's CAS with our new CAS since we're // returning the CAS of the old item below. ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); do_item_remove(new_it); /* release our reference */ } else { /* Should never get here. This means we somehow fetched an unlinked * item. TODO: Add a counter? */ if (settings.verbose) { fprintf(stderr, "Tried to do incr/decr on invalid item\n"); } if (it->refcount == 1) do_item_remove(it); return DELTA_ITEM_NOT_FOUND; } if (cas) { *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ } do_item_remove(it); /* release our reference */ return OK; } static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; item *it; uint32_t hv; assert(c != NULL); if (ntokens > 3) { bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0; bool sets_noreply = set_noreply_maybe(c, tokens, ntokens); bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply)) || (ntokens == 5 && hold_is_zero && sets_noreply); if (!valid) { out_string(c, "CLIENT_ERROR bad command line format. " "Usage: delete <key> [noreply]"); return; } } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); do_item_remove(it); /* release our reference */ out_string(c, "DELETED"); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } item_unlock(hv); } static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[1].value, NULL, 10); settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level; out_string(c, "OK"); return; } #ifdef MEMCACHED_DEBUG static void process_misbehave_command(conn *c) { int allowed = 0; // try opening new TCP socket int i = socket(AF_INET, SOCK_STREAM, 0); if (i != -1) { allowed++; close(i); } // try executing new commands i = system("sleep 0"); if (i != -1) { allowed++; } if (allowed) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; double ratio; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[2].value, "ratio") == 0) { if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) { out_string(c, "ERROR"); return; } settings.slab_automove_ratio = ratio; } else { level = strtoul(tokens[2].value, NULL, 10); if (level == 0) { settings.slab_automove = 0; } else if (level == 1 || level == 2) { settings.slab_automove = level; } else { out_string(c, "ERROR"); return; } } out_string(c, "OK"); return; } /* TODO: decide on syntax for sampling? */ static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) { uint16_t f = 0; int x; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (ntokens > 2) { for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) { if ((strcmp(tokens[x].value, "rawcmds") == 0)) { f |= LOG_RAWCMDS; } else if ((strcmp(tokens[x].value, "evictions") == 0)) { f |= LOG_EVICTIONS; } else if ((strcmp(tokens[x].value, "fetchers") == 0)) { f |= LOG_FETCHERS; } else if ((strcmp(tokens[x].value, "mutations") == 0)) { f |= LOG_MUTATIONS; } else if ((strcmp(tokens[x].value, "sysevents") == 0)) { f |= LOG_SYSEVENTS; } else { out_string(c, "ERROR"); return; } } } else { f |= LOG_FETCHERS; } switch(logger_add_watcher(c, c->sfd, f)) { case LOGGER_ADD_WATCHER_TOO_MANY: out_string(c, "WATCHER_TOO_MANY log watcher limit reached"); break; case LOGGER_ADD_WATCHER_FAILED: out_string(c, "WATCHER_FAILED failed to add log watcher"); break; case LOGGER_ADD_WATCHER_OK: conn_set_state(c, conn_watch); event_del(&c->event); break; } } static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t memlimit; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (!safe_strtoul(tokens[1].value, &memlimit)) { out_string(c, "ERROR"); } else { if (memlimit < 8) { out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m"); } else { if (memlimit > 1000000000) { out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes"); } else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) { if (settings.verbose > 0) { fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit); } out_string(c, "OK"); } else { out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust"); } } } } static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; double hot_factor; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtod(tokens[4].value, &hot_factor) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0 || hot_factor <= 0) { out_string(c, "ERROR hot/warm age factors must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_factor = hot_factor; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } #ifdef EXTSTORE static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) { set_noreply_maybe(c, tokens, ntokens); bool ok = true; if (ntokens < 4) { ok = false; } else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) { /* per-slab-class free chunk setting. */ unsigned int clsid = 0; unsigned int limit = 0; if (!safe_strtoul(tokens[2].value, &clsid) || !safe_strtoul(tokens[3].value, &limit)) { ok = false; } else { if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) { settings.ext_free_memchunks[clsid] = limit; } else { ok = false; } } } else if (strcmp(tokens[1].value, "item_size") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_size)) ok = false; } else if (strcmp(tokens[1].value, "item_age") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_age)) ok = false; } else if (strcmp(tokens[1].value, "low_ttl") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl)) ok = false; } else if (strcmp(tokens[1].value, "recache_rate") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate)) ok = false; } else if (strcmp(tokens[1].value, "compact_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under)) ok = false; } else if (strcmp(tokens[1].value, "drop_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under)) ok = false; } else if (strcmp(tokens[1].value, "max_frag") == 0) { if (!safe_strtod(tokens[2].value, &settings.ext_max_frag)) ok = false; } else if (strcmp(tokens[1].value, "drop_unread") == 0) { unsigned int v; if (!safe_strtoul(tokens[2].value, &v)) { ok = false; } else { settings.ext_drop_unread = v == 0 ? false : true; } } else { ok = false; } if (!ok) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_command(conn *c, char *command) { token_t tokens[MAX_TOKENS]; size_t ntokens; int comm; assert(c != NULL); MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); if (settings.verbose > 1) fprintf(stderr, "<%d %s\n", c->sfd, command); /* * for commands set/add/replace, we build an item and read the data * directly into it, then continue in nread_complete(). */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR out of memory preparing response"); return; } ntokens = tokenize_command(command, tokens, MAX_TOKENS); if (ntokens >= 3 && ((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) || (strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) { process_get_command(c, tokens, ntokens, false, false); } else if ((ntokens == 6 || ntokens == 7) && ((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) || (strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) || (strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) || (strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) || (strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) { process_update_command(c, tokens, ntokens, comm, false); } else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) { process_update_command(c, tokens, ntokens, comm, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 1); } else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) { process_get_command(c, tokens, ntokens, true, false); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 0); } else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) { process_delete_command(c, tokens, ntokens); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) { process_touch_command(c, tokens, ntokens); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) { process_get_command(c, tokens, ntokens, false, true); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) { process_get_command(c, tokens, ntokens, true, true); } else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) { process_stat(c, tokens, ntokens); } else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) { time_t exptime = 0; rel_time_t new_oldest = 0; set_noreply_maybe(c, tokens, ntokens); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats out_string(c, "CLIENT_ERROR flush_all not allowed"); return; } if (ntokens != (c->noreply ? 3 : 2)) { exptime = strtol(tokens[1].value, NULL, 10); if(errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } /* If exptime is zero realtime() would return zero too, and realtime(exptime) - 1 would overflow to the max unsigned value. So we process exptime == 0 the same way we do when no delay is given at all. */ if (exptime > 0) { new_oldest = realtime(exptime); } else { /* exptime == 0 */ new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } out_string(c, "OK"); return; } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) { out_string(c, "VERSION " VERSION); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) { conn_set_state(c, conn_closing); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) { if (settings.shutdown_command) { conn_set_state(c, conn_closing); raise(SIGINT); } else { out_string(c, "ERROR: shutdown not enabled"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) { if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) { int src, dst, rv; if (settings.slab_reassign == false) { out_string(c, "CLIENT_ERROR slab reassignment disabled"); return; } src = strtol(tokens[2].value, NULL, 10); dst = strtol(tokens[3].value, NULL, 10); if (errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } rv = slabs_reassign(src, dst); switch (rv) { case REASSIGN_OK: out_string(c, "OK"); break; case REASSIGN_RUNNING: out_string(c, "BUSY currently processing reassign request"); break; case REASSIGN_BADCLASS: out_string(c, "BADCLASS invalid src or dst class id"); break; case REASSIGN_NOSPARE: out_string(c, "NOSPARE source class has no spare pages"); break; case REASSIGN_SRC_DST_SAME: out_string(c, "SAME src and dst class are identical"); break; } return; } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) { process_slabs_automove_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) { if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) { int rv; if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0, settings.lru_crawler_tocrawl); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) { if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } if (!settings.dump_enabled) { out_string(c, "ERROR metadump not allowed"); return; } int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP, c, c->sfd, LRU_CRAWLER_CAP_REMAINING); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); // TODO: Don't reuse conn_watch here. conn_set_state(c, conn_watch); event_del(&c->event); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) { uint32_t tocrawl; if (!safe_strtoul(tokens[2].value, &tocrawl)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } settings.lru_crawler_tocrawl = tocrawl; out_string(c, "OK"); return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) { uint32_t tosleep; if (!safe_strtoul(tokens[2].value, &tosleep)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (tosleep > 1000000) { out_string(c, "CLIENT_ERROR sleep must be one second or less"); return; } settings.lru_crawler_sleep = tosleep; out_string(c, "OK"); return; } else if (ntokens == 3) { if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) { if (start_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to start lru crawler thread"); } } else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) { if (stop_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to stop lru crawler thread"); } } else { out_string(c, "ERROR"); } return; } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) { process_watch_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) { process_memlimit_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) { process_verbosity_command(c, tokens, ntokens); } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) { process_lru_command(c, tokens, ntokens); #ifdef MEMCACHED_DEBUG // commands which exist only for testing the memcached's security protection } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) { process_misbehave_command(c); #endif #ifdef EXTSTORE } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) { process_extstore_command(c, tokens, ntokens); #endif #ifdef TLS } else if (ntokens == 2 && strcmp(tokens[COMMAND_TOKEN].value, "refresh_certs") == 0) { set_noreply_maybe(c, tokens, ntokens); char *errmsg = NULL; if (refresh_certs(&errmsg)) { out_string(c, "OK"); } else { write_and_free(c, errmsg, strlen(errmsg)); } return; #endif } else { if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) { conn_set_state(c, conn_closing); } else { out_string(c, "ERROR"); } } return; } static int try_read_command_negotiate(conn *c) { assert(c->protocol == negotiating_prot); assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; c->try_read_command = try_read_command_binary; } else { // authentication doesn't work with negotiated protocol. c->protocol = ascii_prot; c->try_read_command = try_read_command_ascii; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } return c->try_read_command(c); } static int try_read_command_udp(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; return try_read_command_binary(c); } else { c->protocol = ascii_prot; return try_read_command_ascii(c); } } static int try_read_command_binary(conn *c) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR Out of memory allocating headers"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; c->last_cmd_time = current_time; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } return 1; } static int try_read_command_asciiauth(conn *c) { token_t tokens[MAX_TOKENS]; size_t ntokens; char *cont = NULL; // TODO: move to another function. if (!c->sasl_started) { char *el; uint32_t size = 0; // impossible for the auth command to be this short. if (c->rbytes < 2) return 0; el = memchr(c->rcurr, '\n', c->rbytes); // If no newline after 1k, getting junk data, close out. if (!el) { if (c->rbytes > 1024) { conn_set_state(c, conn_closing); return 1; } return 0; } // Looking for: "set foo 0 0 N\r\nuser pass\r\n" // key, flags, and ttl are ignored. N is used to see if we have the rest. // so tokenize doesn't walk past into the value. // it's fine to leave the \r in, as strtoul will stop at it. *el = '\0'; ntokens = tokenize_command(c->rcurr, tokens, MAX_TOKENS); // ensure the buffer is consumed. c->rbytes -= (el - c->rcurr) + 1; c->rcurr += (el - c->rcurr) + 1; // final token is a NULL ender, so we have one more than expected. if (ntokens < 6 || strcmp(tokens[0].value, "set") != 0 || !safe_strtoul(tokens[4].value, &size)) { out_string(c, "CLIENT_ERROR unauthenticated"); return 1; } // we don't actually care about the key at all; it can be anything. // we do care about the size of the remaining read. c->rlbytes = size + 2; c->sasl_started = true; // reuse from binprot sasl, but not sasl :) } if (c->rbytes < c->rlbytes) { // need more bytes. return 0; } cont = c->rcurr; // advance buffer. no matter what we're stopping. c->rbytes -= c->rlbytes; c->rcurr += c->rlbytes; c->sasl_started = false; // must end with \r\n // NB: I thought ASCII sets also worked with just \n, but according to // complete_nread_ascii only \r\n is valid. if (strncmp(cont + c->rlbytes - 2, "\r\n", 2) != 0) { out_string(c, "CLIENT_ERROR bad command line termination"); return 1; } // payload should be "user pass", so we can use the tokenizer. cont[c->rlbytes - 2] = '\0'; ntokens = tokenize_command(cont, tokens, MAX_TOKENS); if (ntokens < 3) { out_string(c, "CLIENT_ERROR bad authentication token format"); return 1; } if (authfile_check(tokens[0].value, tokens[1].value) == 1) { out_string(c, "STORED"); c->authenticated = true; c->try_read_command = try_read_command_ascii; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); } else { out_string(c, "CLIENT_ERROR authentication failure"); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } return 1; } static int try_read_command_ascii(conn *c) { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (ptr - c->rcurr > 100 || (strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); c->last_cmd_time = current_time; process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); return 1; } /* * read a UDP request. */ static enum try_read_result try_read_udp(conn *c) { int res; assert(c != NULL); c->request_addr_size = sizeof(c->request_addr); res = recvfrom(c->sfd, c->rbuf, c->rsize, 0, (struct sockaddr *)&c->request_addr, &c->request_addr_size); if (res > 8) { unsigned char *buf = (unsigned char *)c->rbuf; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* Beginning of UDP packet is the request ID; save it. */ c->request_id = buf[0] * 256 + buf[1]; /* If this is a multi-packet request, drop it. */ if (buf[4] != 0 || buf[5] != 1) { out_string(c, "SERVER_ERROR multi-packet request not supported"); return READ_NO_DATA_RECEIVED; } /* Don't care about any of the rest of the header. */ res -= 8; memmove(c->rbuf, c->rbuf + 8, res); c->rbytes = res; c->rcurr = c->rbuf; return READ_DATA_RECEIVED; } return READ_NO_DATA_RECEIVED; } /* * read from network as much as we can, handle buffer overflow and connection * close. * before reading, move the remaining incomplete fragment of a command * (if any) to the beginning of the buffer. * * To protect us from someone flooding a connection with bogus data causing * the connection to eat up all available memory, break out and start looking * at the data I've got after a number of reallocs... * * @return enum try_read_result */ static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose > 0) { fprintf(stderr, "Couldn't realloc input buffer\n"); } c->rbytes = 0; /* ignore what we read */ out_of_memory(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = c->read(c, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } static bool update_event(conn *c, const int new_flags) { assert(c != NULL); struct event_base *base = c->event.ev_base; if (c->ev_flags == new_flags) return true; if (event_del(&c->event) == -1) return false; event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = new_flags; if (event_add(&c->event, 0) == -1) return false; return true; } /* * Sets whether we are listening for new connections or not. */ void do_accept_new_conns(const bool do_accept) { conn *next; for (next = listen_conn; next; next = next->next) { if (do_accept) { update_event(next, EV_READ | EV_PERSIST); if (listen(next->sfd, settings.backlog) != 0) { perror("listen"); } } else { update_event(next, 0); if (listen(next->sfd, 0) != 0) { perror("listen"); } } } if (do_accept) { struct timeval maxconns_exited; uint64_t elapsed_us; gettimeofday(&maxconns_exited,NULL); STATS_LOCK(); elapsed_us = (maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000 + (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec); stats.time_in_listen_disabled_us += elapsed_us; stats_state.accepting_conns = true; STATS_UNLOCK(); } else { STATS_LOCK(); stats_state.accepting_conns = false; gettimeofday(&stats.maxconns_entered,NULL); stats.listen_disabled_num++; STATS_UNLOCK(); allow_new_conns = false; maxconns_handler(-42, 0, 0); } } /* * Transmit the next chunk of data from our list of msgbuf structures. * * Returns: * TRANSMIT_COMPLETE All done writing. * TRANSMIT_INCOMPLETE More data remaining to write. * TRANSMIT_SOFT_ERROR Can't write any more right now. * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing) */ static enum transmit_result transmit(conn *c) { assert(c != NULL); if (c->msgcurr < c->msgused && c->msglist[c->msgcurr].msg_iovlen == 0) { /* Finished writing the current msg; advance to the next. */ c->msgcurr++; } if (c->msgcurr < c->msgused) { ssize_t res; struct msghdr *m = &c->msglist[c->msgcurr]; res = c->sendmsg(c, m, 0); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_written += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* We've written some of the data. Remove the completed iovec entries from the list of pending writes. */ while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) { res -= m->msg_iov->iov_len; m->msg_iovlen--; m->msg_iov++; } /* Might have written just part of the last iovec entry; adjust it so the next write will do the rest. */ if (res > 0) { m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res; m->msg_iov->iov_len -= res; } return TRANSMIT_INCOMPLETE; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } return TRANSMIT_SOFT_ERROR; } /* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK, we have a real error, on which we close the connection */ if (settings.verbose > 0) perror("Failed to write, and not due to blocking"); if (IS_UDP(c->transport)) conn_set_state(c, conn_read); else conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } else { return TRANSMIT_COMPLETE; } } /* Does a looped read to fill data chunks */ /* TODO: restrict number of times this can loop. * Also, benchmark using readv's. */ static int read_into_chunked_item(conn *c) { int total = 0; int res; assert(c->rcurr != c->ritem); while (c->rlbytes > 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size == ch->used) { // FIXME: ch->next is currently always 0. remove this? if (ch->next) { c->ritem = (char *) ch->next; } else { /* Allocate next chunk. Binary protocol needs 2b for \r\n */ c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes + ((c->protocol == binary_prot) ? 2 : 0)); if (!c->ritem) { // We failed an allocation. Let caller handle cleanup. total = -2; break; } // ritem has new chunk, restart the loop. continue; //assert(c->rlbytes == 0); } } int unused = ch->size - ch->used; /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { total = 0; int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; tocopy = tocopy > unused ? unused : tocopy; if (c->ritem != c->rcurr) { memmove(ch->data + ch->used, c->rcurr, tocopy); } total += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; ch->used += tocopy; if (c->rlbytes == 0) { break; } } else { /* now try reading from the socket */ res = c->read(c, ch->data + ch->used, (unused > c->rlbytes ? c->rlbytes : unused)); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); ch->used += res; total += res; c->rlbytes -= res; } else { /* Reset total to the latest result so caller can handle it */ total = res; break; } } } /* At some point I will be able to ditch the \r\n from item storage and remove all of these kludges. The above binprot check ensures inline space for \r\n, but if we do exactly enough allocs there will be no additional chunk for \r\n. */ if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size - ch->used < 2) { c->ritem = (char *) do_item_alloc_chunk(ch, 2); if (!c->ritem) { total = -2; } } } return total; } static void drive_machine(conn *c) { bool stop = false; int sfd; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; #ifdef HAVE_ACCEPT4 static int use_accept4 = 1; #else static int use_accept4 = 0; #endif assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); #ifdef HAVE_ACCEPT4 if (use_accept4) { sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); } else { sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); } #else sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); #endif if (sfd == -1) { if (use_accept4 && errno == ENOSYS) { use_accept4 = 0; continue; } perror(use_accept4 ? "accept4()" : "accept()"); if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if (!use_accept4) { if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } } if (settings.maxconns_fast && stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { void *ssl_v = NULL; #ifdef TLS SSL *ssl = NULL; if (c->ssl_enabled) { assert(IS_TCP(c->transport) && settings.ssl_enabled); if (settings.ssl_ctx == NULL) { if (settings.verbose) { fprintf(stderr, "SSL context is not initialized\n"); } close(sfd); break; } SSL_LOCK(); ssl = SSL_new(settings.ssl_ctx); SSL_UNLOCK(); if (ssl == NULL) { if (settings.verbose) { fprintf(stderr, "Failed to created the SSL object\n"); } close(sfd); break; } SSL_set_fd(ssl, sfd); int ret = SSL_accept(ssl); if (ret < 0) { int err = SSL_get_error(ssl, ret); if (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) { if (settings.verbose) { fprintf(stderr, "SSL connection failed with error code : %d : %s\n", err, strerror(errno)); } close(sfd); break; } } } ssl_v = (void*) ssl; #endif dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, c->transport, ssl_v); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (c->try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* Check if rbytes < 0, to prevent crash */ if (c->rlbytes < 0) { if (settings.verbose) { fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes); } conn_set_state(c, conn_closing); break; } if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) { /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = c->read(c, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } } else { res = read_into_chunked_item(c); if (res > 0) break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* Memory allocation failure */ if (res == -2) { out_of_memory(c, "SERVER_ERROR Out of memory during read"); c->sbytes = c->rlbytes; c->write_and_go = conn_swallow; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes <= 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = c->read(c, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: #ifdef EXTSTORE /* have side IO's that must process before transmit() can run. * remove the connection from the worker thread and dispatch the * IO queue */ if (c->io_wrapleft) { assert(c->io_queued == false); assert(c->io_wraplist != NULL); // TODO: create proper state for this condition conn_set_state(c, conn_watch); event_del(&c->event); c->io_queued = true; extstore_submit(c->thread->storage, &c->io_wraplist->io); stop = true; break; } #endif if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { conn_release_items(c); /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_closed: /* This only happens if dormando is an idiot. */ abort(); break; case conn_watch: /* We handed off our connection to the logger thread. */ stop = true; break; case conn_max_state: assert(false); break; } } return; } void event_handler(const int fd, const short which, void *arg) { conn *c; c = (conn *)arg; assert(c != NULL); c->which = which; /* sanity */ if (fd != c->sfd) { if (settings.verbose > 0) fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n"); conn_close(c); return; } drive_machine(c); /* wait for next event */ return; } static int new_socket(struct addrinfo *ai) { int sfd; int flags; if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } /* * Sets a socket's send buffer size to the maximum allowed by the system. */ static void maximize_sndbuf(const int sfd) { socklen_t intsize = sizeof(int); int last_good = 0; int min, max, avg; int old_size; /* Start with the default size. */ if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) { if (settings.verbose > 0) perror("getsockopt(SO_SNDBUF)"); return; } /* Binary-search for the real maximum. */ min = old_size; max = MAX_SENDBUF_SIZE; while (min <= max) { avg = ((unsigned int)(min + max)) / 2; if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) { last_good = avg; min = avg + 1; } else { max = avg - 1; } } if (settings.verbose > 1) fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good); } /** * Create a socket and bind it to a specific port number * @param interface the interface to bind to * @param port the port number to bind to * @param transport the transport protocol (TCP / UDP) * @param portnumber_file A filepointer to write the port numbers to * when they are successfully added to the list of ports we * listen on. */ static int server_socket(const char *interface, int port, enum network_transport transport, FILE *portnumber_file, bool ssl_enabled) { int sfd; struct linger ling = {0, 0}; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; char port_buf[NI_MAXSERV]; int error; int success = 0; int flags =1; hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; if (port == -1) { port = 0; } snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { conn *listen_conn_add; if ((sfd = new_socket(next)) == -1) { /* getaddrinfo can return "junk" addresses, * we make sure at least one works before erroring. */ if (errno == EMFILE) { /* ...unless we're out of fds */ perror("server_socket"); exit(EX_OSERR); } continue; } #ifdef IPV6_V6ONLY if (next->ai_family == AF_INET6) { error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); if (error != 0) { perror("setsockopt"); close(sfd); continue; } } #endif setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (IS_UDP(transport)) { maximize_sndbuf(sfd); } else { error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); } if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } else { success++; if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); freeaddrinfo(ai); return 1; } if (portnumber_file != NULL && (next->ai_addr->sa_family == AF_INET || next->ai_addr->sa_family == AF_INET6)) { union { struct sockaddr_in in; struct sockaddr_in6 in6; } my_sockaddr; socklen_t len = sizeof(my_sockaddr); if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { if (next->ai_addr->sa_family == AF_INET) { fprintf(portnumber_file, "%s INET: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in.sin_port)); } else { fprintf(portnumber_file, "%s INET6: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in6.sin6_port)); } } } } if (IS_UDP(transport)) { int c; for (c = 0; c < settings.num_threads_per_udp; c++) { /* Allocate one UDP file descriptor per worker thread; * this allows "stats conns" to separately list multiple * parallel UDP requests in progress. * * The dispatch code round-robins new connection requests * among threads, so this is guaranteed to assign one * FD to each thread. */ int per_thread_fd; if (c == 0) { per_thread_fd = sfd; } else { per_thread_fd = dup(sfd); if (per_thread_fd < 0) { perror("Failed to duplicate file descriptor"); exit(EXIT_FAILURE); } } dispatch_conn_new(per_thread_fd, conn_read, EV_READ | EV_PERSIST, UDP_READ_BUFFER_SIZE, transport, NULL); } } else { if (!(listen_conn_add = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } #ifdef TLS listen_conn_add->ssl_enabled = ssl_enabled; #else assert(ssl_enabled == false); #endif listen_conn_add->next = listen_conn; listen_conn = listen_conn_add; } } freeaddrinfo(ai); /* Return zero iff we detected no errors in starting up connections */ return success == 0; } static int server_sockets(int port, enum network_transport transport, FILE *portnumber_file) { bool ssl_enabled = false; #ifdef TLS const char *notls = "notls"; ssl_enabled = settings.ssl_enabled; #endif if (settings.inter == NULL) { return server_socket(settings.inter, port, transport, portnumber_file, ssl_enabled); } else { // tokenize them and bind to each one of them.. char *b; int ret = 0; char *list = strdup(settings.inter); if (list == NULL) { fprintf(stderr, "Failed to allocate memory for parsing server interface string\n"); return 1; } for (char *p = strtok_r(list, ";,", &b); p != NULL; p = strtok_r(NULL, ";,", &b)) { int the_port = port; #ifdef TLS ssl_enabled = settings.ssl_enabled; // "notls" option is valid only when memcached is run with SSL enabled. if (strncmp(p, notls, strlen(notls)) == 0) { if (!settings.ssl_enabled) { fprintf(stderr, "'notls' option is valid only when SSL is enabled\n"); return 1; } ssl_enabled = false; p += strlen(notls) + 1; } #endif char *h = NULL; if (*p == '[') { // expecting it to be an IPv6 address enclosed in [] // i.e. RFC3986 style recommended by RFC5952 char *e = strchr(p, ']'); if (e == NULL) { fprintf(stderr, "Invalid IPV6 address: \"%s\"", p); free(list); return 1; } h = ++p; // skip the opening '[' *e = '\0'; p = ++e; // skip the closing ']' } char *s = strchr(p, ':'); if (s != NULL) { // If no more semicolons - attempt to treat as port number. // Otherwise the only valid option is an unenclosed IPv6 without port, until // of course there was an RFC3986 IPv6 address previously specified - // in such a case there is no good option, will just send it to fail as port number. if (strchr(s + 1, ':') == NULL || h != NULL) { *s = '\0'; ++s; if (!safe_strtol(s, &the_port)) { fprintf(stderr, "Invalid port number: \"%s\"", s); free(list); return 1; } } } if (h != NULL) p = h; if (strcmp(p, "*") == 0) { p = NULL; } ret |= server_socket(p, the_port, transport, portnumber_file, ssl_enabled); } free(list); return ret; } } static int new_socket_unix(void) { int sfd; int flags; if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } static int server_socket_unix(const char *path, int access_mask) { int sfd; struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags =1; int old_umask; if (!path) { return 1; } if ((sfd = new_socket_unix()) == -1) { return 1; } /* * Clean up a previous socket file if we left it around */ if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) unlink(path); } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); /* * the memset call clears nonstandard fields in some implementations * that otherwise mess things up. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask( ~(access_mask&0777)); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind()"); close(sfd); umask(old_umask); return 1; } umask(old_umask); if (listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); return 1; } if (!(listen_conn = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, local_transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } return 0; } /* * We keep the current time of day in a global variable that's updated by a * timer event. This saves us a bunch of time() system calls (we really only * need to get the time once a second, whereas there can be tens of thousands * of requests a second) and allows us to use server-start-relative timestamps * rather than absolute UNIX timestamps, a space savings on systems where * sizeof(time_t) > sizeof(unsigned int). */ volatile rel_time_t current_time; static struct event clockevent; /* libevent uses a monotonic clock when available for event scheduling. Aside * from jitter, simply ticking our internal timer here is accurate enough. * Note that users who are setting explicit dates for expiration times *must* * ensure their clocks are correct before starting memcached. */ static void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; static bool initialized = false; #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) static bool monotonic = false; static time_t monotonic_start; #endif if (initialized) { /* only delete the event if it's actually there. */ evtimer_del(&clockevent); } else { initialized = true; /* process_started is initialized to time() - 2. We initialize to 1 so * flush_all won't underflow during tests. */ #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { monotonic = true; monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2; } #endif } // While we're here, check for hash table expansion. // This function should be quick to avoid delaying the timer. assoc_start_expand(stats_state.curr_items); // also, if HUP'ed we need to do some maintenance. // for now that's just the authfile reload. if (settings.sig_hup) { settings.sig_hup = false; authfile_load(settings.auth_file); } evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) if (monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return; current_time = (rel_time_t) (ts.tv_sec - monotonic_start); return; } #endif { struct timeval tv; gettimeofday(&tv, NULL); current_time = (rel_time_t) (tv.tv_sec - process_started); } } static void usage(void) { printf(PACKAGE " " VERSION "\n"); printf("-p, --port=<num> TCP port to listen on (default: 11211)\n" "-U, --udp-port=<num> UDP port to listen on (default: 0, off)\n" "-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n" "-A, --enable-shutdown enable ascii \"shutdown\" command\n" "-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n" "-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n" #ifdef TLS " if TLS/SSL is enabled, 'notls' prefix can be used to\n" " disable for specific listeners (-l notls:<ip>:<port>) \n" #endif "-d, --daemon run as a daemon\n" "-r, --enable-coredumps maximize core file limit\n" "-u, --user=<user> assume identity of <username> (only when run as root)\n" "-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n" "-M, --disable-evictions return error on memory exhausted instead of evicting\n" "-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n" "-k, --lock-memory lock down all paged memory\n" "-v, --verbose verbose (print errors/warnings while in event loop)\n" "-vv very verbose (also print client commands/responses)\n" "-vvv extremely verbose (internal state transitions)\n" "-h, --help print this help and exit\n" "-i, --license print memcached and libevent license\n" "-V, --version print version and exit\n" "-P, --pidfile=<file> save PID in <file>, only used with -d option\n" "-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n" "-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n"); printf("-L, --enable-largepages try to use large memory pages (if available)\n"); printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n" " This is used for per-prefix stats reporting. The default is\n" " \":\" (colon). If this option is specified, stats collection\n" " is turned on automatically; if not, then it may be turned on\n" " by sending the \"stats detail on\" command to the server.\n"); printf("-t, --threads=<num> number of threads to use (default: 4)\n"); printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n" " requests processed per connection to prevent \n" " starvation (default: 20)\n"); printf("-C, --disable-cas disable use of CAS\n"); printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n"); printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n"); printf("-I, --max-item-size=<num> adjusts max item size\n" " (default: 1mb, min: 1k, max: 1024m)\n"); #ifdef ENABLE_SASL printf("-S, --enable-sasl turn on Sasl authentication\n"); #endif printf("-F, --disable-flush-all disable flush_all command\n"); printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n"); printf("-Y, --auth-file=<file> (EXPERIMENTAL) enable ASCII protocol authentication. format:\n" " user:pass\\nuser2:pass2\\n\n"); #ifdef TLS printf("-Z, --enable-ssl enable TLS/SSL\n"); #endif printf("-o, --extended comma separated list of extended options\n" " most options have a 'no_' prefix to disable\n" " - maxconns_fast: immediately close new connections after limit\n" " - hashpower: an integer multiplier for how large the hash\n" " table should be. normally grows at runtime.\n" " set based on \"STAT hash_power_level\"\n" " - tail_repair_time: time in seconds for how long to wait before\n" " forcefully killing LRU tail item.\n" " disabled by default; very dangerous option.\n" " - hash_algorithm: the hash table algorithm\n" " default is murmur3 hash. options: jenkins, murmur3\n" " - lru_crawler: enable LRU Crawler background thread\n" " - lru_crawler_sleep: microseconds to sleep between items\n" " default is 100.\n" " - lru_crawler_tocrawl: max items to crawl per slab per run\n" " default is 0 (unlimited)\n" " - lru_maintainer: enable new LRU system + background thread\n" " - hot_lru_pct: pct of slab memory to reserve for hot lru.\n" " (requires lru_maintainer)\n" " - warm_lru_pct: pct of slab memory to reserve for warm lru.\n" " (requires lru_maintainer)\n" " - hot_max_factor: items idle > cold lru age * drop from hot lru.\n" " - warm_max_factor: items idle > cold lru age * this drop from warm.\n" " - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n" " (requires lru_maintainer)\n" " - idle_timeout: timeout for idle connections\n" " - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n" " - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n" " - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n" " read by background thread, then written to watchers.\n" " - track_sizes: enable dynamic reports for 'stats sizes' command.\n" " - no_hashexpand: disables hash table expansion (dangerous)\n" " - modern: enables options which will be default in future.\n" " currently: nothing\n" " - no_modern: uses defaults of previous major version (1.4.x)\n" #ifdef HAVE_DROP_PRIVILEGES " - drop_privileges: enable dropping extra syscall privileges\n" " - no_drop_privileges: disable drop_privileges in case it causes issues with\n" " some customisation.\n" #ifdef MEMCACHED_DEBUG " - relaxed_privileges: Running tests requires extra privileges.\n" #endif #endif #ifdef EXTSTORE " - ext_path: file to write to for external storage.\n" " ie: ext_path=/mnt/d1/extstore:1G\n" " - ext_page_size: size in megabytes of storage pages.\n" " - ext_wbuf_size: size in megabytes of page write buffers.\n" " - ext_threads: number of IO threads to run.\n" " - ext_item_size: store items larger than this (bytes)\n" " - ext_item_age: store items idle at least this long\n" " - ext_low_ttl: consider TTLs lower than this specially\n" " - ext_drop_unread: don't re-write unread values during compaction\n" " - ext_recache_rate: recache an item every N accesses\n" " - ext_compact_under: compact when fewer than this many free pages\n" " - ext_drop_under: drop COLD items when fewer than this many free pages\n" " - ext_max_frag: max page fragmentation to tolerage\n" " - slab_automove_freeratio: ratio of memory to hold free as buffer.\n" " (see doc/storage.txt for more info)\n" #endif #ifdef TLS " - ssl_chain_cert: certificate chain file in PEM format\n" " - ssl_key: private key, if not part of the -ssl_chain_cert\n" " - ssl_keyformat: private key format (PEM, DER or ENGINE) PEM default\n" " - ssl_verify_mode: peer certificate verification mode, default is 0(None).\n" " valid values are 0(None), 1(Request), 2(Require)\n" " or 3(Once)\n" " - ssl_ciphers: specify cipher list to be used\n" " - ssl_ca_cert: PEM format file of acceptable client CA's\n" " - ssl_wbuf_size: size in kilobytes of per-connection SSL output buffer\n" #endif ); return; } static void usage_license(void) { printf(PACKAGE " " VERSION "\n\n"); printf( "Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are\n" "met:\n" "\n" " * Redistributions of source code must retain the above copyright\n" "notice, this list of conditions and the following disclaimer.\n" "\n" " * Redistributions in binary form must reproduce the above\n" "copyright notice, this list of conditions and the following disclaimer\n" "in the documentation and/or other materials provided with the\n" "distribution.\n" "\n" " * Neither the name of the Danga Interactive nor the names of its\n" "contributors may be used to endorse or promote products derived from\n" "this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" "\n" "\n" "This product includes software developed by Niels Provos.\n" "\n" "[ libevent ]\n" "\n" "Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions\n" "are met:\n" "1. Redistributions of source code must retain the above copyright\n" " notice, this list of conditions and the following disclaimer.\n" "2. Redistributions in binary form must reproduce the above copyright\n" " notice, this list of conditions and the following disclaimer in the\n" " documentation and/or other materials provided with the distribution.\n" "3. All advertising materials mentioning features or use of this software\n" " must display the following acknowledgement:\n" " This product includes software developed by Niels Provos.\n" "4. The name of the author may not be used to endorse or promote products\n" " derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ); return; } static void save_pid(const char *pid_file) { FILE *fp; if (access(pid_file, F_OK) == 0) { if ((fp = fopen(pid_file, "r")) != NULL) { char buffer[1024]; if (fgets(buffer, sizeof(buffer), fp) != NULL) { unsigned int pid; if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) { fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid); } } fclose(fp); } } /* Create the pid file first with a temporary name, then * atomically move the file to the real name to avoid a race with * another process opening the file to read the pid, but finding * it empty. */ char tmp_pid_file[1024]; snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file); if ((fp = fopen(tmp_pid_file, "w")) == NULL) { vperror("Could not open the pid file %s for writing", tmp_pid_file); return; } fprintf(fp,"%ld\n", (long)getpid()); if (fclose(fp) == -1) { vperror("Could not close the pid file %s", tmp_pid_file); } if (rename(tmp_pid_file, pid_file) != 0) { vperror("Could not rename the pid file from %s to %s", tmp_pid_file, pid_file); } } static void remove_pidfile(const char *pid_file) { if (pid_file == NULL) return; if (unlink(pid_file) != 0) { vperror("Could not remove the pid file %s", pid_file); } } static void sig_handler(const int sig) { printf("Signal handled: %s.\n", strsignal(sig)); exit(EXIT_SUCCESS); } static void sighup_handler(const int sig) { settings.sig_hup = true; } #ifndef HAVE_SIGIGNORE static int sigignore(int sig) { struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 }; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } #endif /* * On systems that supports multiple page sizes we may reduce the * number of TLB-misses by using the biggest available page size */ static int enable_large_pages(void) { #if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL) int ret = -1; size_t sizes[32]; int avail = getpagesizes(sizes, 32); if (avail != -1) { size_t max = sizes[0]; struct memcntl_mha arg = {0}; int ii; for (ii = 1; ii < avail; ++ii) { if (max < sizes[ii]) { max = sizes[ii]; } } arg.mha_flags = 0; arg.mha_pagesize = max; arg.mha_cmd = MHA_MAPSIZE_BSSBRK; if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) { fprintf(stderr, "Failed to set large pages: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } else { ret = 0; } } else { fprintf(stderr, "Failed to get supported pagesizes: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } return ret; #elif defined(__linux__) && defined(MADV_HUGEPAGE) /* check if transparent hugepages is compiled into the kernel */ struct stat st; int ret = stat("/sys/kernel/mm/transparent_hugepage/enabled", &st); if (ret || !(st.st_mode & S_IFREG)) { fprintf(stderr, "Transparent huge pages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #elif defined(__FreeBSD__) int spages; size_t spagesl = sizeof(spages); if (sysctlbyname("vm.pmap.pg_ps_enabled", &spages, &spagesl, NULL, 0) != 0) { fprintf(stderr, "Could not evaluate the presence of superpages features."); return -1; } if (spages != 1) { fprintf(stderr, "Superpages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #else return -1; #endif } /** * Do basic sanity check of the runtime environment * @return true if no errors found, false if we can't use this env */ static bool sanitycheck(void) { /* One of our biggest problems is old and bogus libevents */ const char *ever = event_get_version(); if (ever != NULL) { if (strncmp(ever, "1.", 2) == 0) { /* Require at least 1.3 (that's still a couple of years old) */ if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) { fprintf(stderr, "You are using libevent %s.\nPlease upgrade to" " a more recent version (1.3 or newer)\n", event_get_version()); return false; } } } return true; } static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) { char *b = NULL; uint32_t size = 0; int i = 0; uint32_t last_size = 0; if (strlen(s) < 1) return false; for (char *p = strtok_r(s, "-", &b); p != NULL; p = strtok_r(NULL, "-", &b)) { if (!safe_strtoul(p, &size) || size < settings.chunk_size || size > settings.slab_chunk_size_max) { fprintf(stderr, "slab size %u is out of valid range\n", size); return false; } if (last_size >= size) { fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size); return false; } if (size <= last_size + CHUNK_ALIGN_BYTES) { fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n", size, CHUNK_ALIGN_BYTES); return false; } slab_sizes[i++] = size; last_size = size; if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) { fprintf(stderr, "too many slab classes specified\n"); return false; } } slab_sizes[i] = 0; return true; } int main (int argc, char **argv) { int c; bool lock_memory = false; bool do_daemonize = false; bool preallocate = false; int maxcore = 0; char *username = NULL; char *pid_file = NULL; struct passwd *pw; struct rlimit rlim; char *buf; char unit = '\0'; int size_max = 0; int retval = EXIT_SUCCESS; bool protocol_specified = false; bool tcp_specified = false; bool udp_specified = false; bool start_lru_maintainer = true; bool start_lru_crawler = true; bool start_assoc_maint = true; enum hashfunc_type hash_type = MURMUR3_HASH; uint32_t tocrawl; uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES]; bool use_slab_sizes = false; char *slab_sizes_unparsed = NULL; bool slab_chunk_size_changed = false; #ifdef EXTSTORE void *storage = NULL; struct extstore_conf_file *storage_file = NULL; struct extstore_conf ext_cf; #endif char *subopts, *subopts_orig; char *subopts_value; enum { MAXCONNS_FAST = 0, HASHPOWER_INIT, NO_HASHEXPAND, SLAB_REASSIGN, SLAB_AUTOMOVE, SLAB_AUTOMOVE_RATIO, SLAB_AUTOMOVE_WINDOW, TAIL_REPAIR_TIME, HASH_ALGORITHM, LRU_CRAWLER, LRU_CRAWLER_SLEEP, LRU_CRAWLER_TOCRAWL, LRU_MAINTAINER, HOT_LRU_PCT, WARM_LRU_PCT, HOT_MAX_FACTOR, WARM_MAX_FACTOR, TEMPORARY_TTL, IDLE_TIMEOUT, WATCHER_LOGBUF_SIZE, WORKER_LOGBUF_SIZE, SLAB_SIZES, SLAB_CHUNK_MAX, TRACK_SIZES, NO_INLINE_ASCII_RESP, MODERN, NO_MODERN, NO_CHUNKED_ITEMS, NO_SLAB_REASSIGN, NO_SLAB_AUTOMOVE, NO_MAXCONNS_FAST, INLINE_ASCII_RESP, NO_LRU_CRAWLER, NO_LRU_MAINTAINER, NO_DROP_PRIVILEGES, DROP_PRIVILEGES, #ifdef TLS SSL_CERT, SSL_KEY, SSL_VERIFY_MODE, SSL_KEYFORM, SSL_CIPHERS, SSL_CA_CERT, SSL_WBUF_SIZE, #endif #ifdef MEMCACHED_DEBUG RELAXED_PRIVILEGES, #endif #ifdef EXTSTORE EXT_PAGE_SIZE, EXT_WBUF_SIZE, EXT_THREADS, EXT_IO_DEPTH, EXT_PATH, EXT_ITEM_SIZE, EXT_ITEM_AGE, EXT_LOW_TTL, EXT_RECACHE_RATE, EXT_COMPACT_UNDER, EXT_DROP_UNDER, EXT_MAX_FRAG, EXT_DROP_UNREAD, SLAB_AUTOMOVE_FREERATIO, #endif }; char *const subopts_tokens[] = { [MAXCONNS_FAST] = "maxconns_fast", [HASHPOWER_INIT] = "hashpower", [NO_HASHEXPAND] = "no_hashexpand", [SLAB_REASSIGN] = "slab_reassign", [SLAB_AUTOMOVE] = "slab_automove", [SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio", [SLAB_AUTOMOVE_WINDOW] = "slab_automove_window", [TAIL_REPAIR_TIME] = "tail_repair_time", [HASH_ALGORITHM] = "hash_algorithm", [LRU_CRAWLER] = "lru_crawler", [LRU_CRAWLER_SLEEP] = "lru_crawler_sleep", [LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl", [LRU_MAINTAINER] = "lru_maintainer", [HOT_LRU_PCT] = "hot_lru_pct", [WARM_LRU_PCT] = "warm_lru_pct", [HOT_MAX_FACTOR] = "hot_max_factor", [WARM_MAX_FACTOR] = "warm_max_factor", [TEMPORARY_TTL] = "temporary_ttl", [IDLE_TIMEOUT] = "idle_timeout", [WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size", [WORKER_LOGBUF_SIZE] = "worker_logbuf_size", [SLAB_SIZES] = "slab_sizes", [SLAB_CHUNK_MAX] = "slab_chunk_max", [TRACK_SIZES] = "track_sizes", [NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp", [MODERN] = "modern", [NO_MODERN] = "no_modern", [NO_CHUNKED_ITEMS] = "no_chunked_items", [NO_SLAB_REASSIGN] = "no_slab_reassign", [NO_SLAB_AUTOMOVE] = "no_slab_automove", [NO_MAXCONNS_FAST] = "no_maxconns_fast", [INLINE_ASCII_RESP] = "inline_ascii_resp", [NO_LRU_CRAWLER] = "no_lru_crawler", [NO_LRU_MAINTAINER] = "no_lru_maintainer", [NO_DROP_PRIVILEGES] = "no_drop_privileges", [DROP_PRIVILEGES] = "drop_privileges", #ifdef TLS [SSL_CERT] = "ssl_chain_cert", [SSL_KEY] = "ssl_key", [SSL_VERIFY_MODE] = "ssl_verify_mode", [SSL_KEYFORM] = "ssl_keyformat", [SSL_CIPHERS] = "ssl_ciphers", [SSL_CA_CERT] = "ssl_ca_cert", [SSL_WBUF_SIZE] = "ssl_wbuf_size", #endif #ifdef MEMCACHED_DEBUG [RELAXED_PRIVILEGES] = "relaxed_privileges", #endif #ifdef EXTSTORE [EXT_PAGE_SIZE] = "ext_page_size", [EXT_WBUF_SIZE] = "ext_wbuf_size", [EXT_THREADS] = "ext_threads", [EXT_IO_DEPTH] = "ext_io_depth", [EXT_PATH] = "ext_path", [EXT_ITEM_SIZE] = "ext_item_size", [EXT_ITEM_AGE] = "ext_item_age", [EXT_LOW_TTL] = "ext_low_ttl", [EXT_RECACHE_RATE] = "ext_recache_rate", [EXT_COMPACT_UNDER] = "ext_compact_under", [EXT_DROP_UNDER] = "ext_drop_under", [EXT_MAX_FRAG] = "ext_max_frag", [EXT_DROP_UNREAD] = "ext_drop_unread", [SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio", #endif NULL }; if (!sanitycheck()) { return EX_OSERR; } /* handle SIGINT, SIGTERM */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sighup_handler); /* init settings */ settings_init(); #ifdef EXTSTORE settings.ext_item_size = 512; settings.ext_item_age = UINT_MAX; settings.ext_low_ttl = 0; settings.ext_recache_rate = 2000; settings.ext_max_frag = 0.8; settings.ext_drop_unread = false; settings.ext_wbuf_size = 1024 * 1024 * 4; settings.ext_compact_under = 0; settings.ext_drop_under = 0; settings.slab_automove_freeratio = 0.01; ext_cf.page_size = 1024 * 1024 * 64; ext_cf.wbuf_size = settings.ext_wbuf_size; ext_cf.io_threadcount = 1; ext_cf.io_depth = 1; ext_cf.page_buckets = 4; ext_cf.wbuf_count = ext_cf.page_buckets; #endif /* Run regardless of initializing it later */ init_lru_maintainer(); /* set stderr non-buffering (for running under, say, daemontools) */ setbuf(stderr, NULL); char *shortopts = "a:" /* access mask for unix socket */ "A" /* enable admin shutdown command */ "Z" /* enable SSL */ "p:" /* TCP port number to listen on */ "s:" /* unix socket path to listen on */ "U:" /* UDP port number to listen on */ "m:" /* max memory to use for items in megabytes */ "M" /* return error on memory exhausted */ "c:" /* max simultaneous connections */ "k" /* lock down all paged memory */ "hiV" /* help, licence info, version */ "r" /* maximize core file limit */ "v" /* verbose */ "d" /* daemon mode */ "l:" /* interface to listen on */ "u:" /* user identity to run as */ "P:" /* save PID in file */ "f:" /* factor? */ "n:" /* minimum space allocated for key+value+flags */ "t:" /* threads */ "D:" /* prefix delimiter? */ "L" /* Large memory pages */ "R:" /* max requests per event */ "C" /* Disable use of CAS */ "b:" /* backlog queue limit */ "B:" /* Binding protocol */ "I:" /* Max item size */ "S" /* Sasl ON */ "F" /* Disable flush_all */ "X" /* Disable dump commands */ "Y:" /* Enable token auth */ "o:" /* Extended generic options */ ; /* process arguments */ #ifdef HAVE_GETOPT_LONG const struct option longopts[] = { {"unix-mask", required_argument, 0, 'a'}, {"enable-shutdown", no_argument, 0, 'A'}, {"enable-ssl", no_argument, 0, 'Z'}, {"port", required_argument, 0, 'p'}, {"unix-socket", required_argument, 0, 's'}, {"udp-port", required_argument, 0, 'U'}, {"memory-limit", required_argument, 0, 'm'}, {"disable-evictions", no_argument, 0, 'M'}, {"conn-limit", required_argument, 0, 'c'}, {"lock-memory", no_argument, 0, 'k'}, {"help", no_argument, 0, 'h'}, {"license", no_argument, 0, 'i'}, {"version", no_argument, 0, 'V'}, {"enable-coredumps", no_argument, 0, 'r'}, {"verbose", optional_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"listen", required_argument, 0, 'l'}, {"user", required_argument, 0, 'u'}, {"pidfile", required_argument, 0, 'P'}, {"slab-growth-factor", required_argument, 0, 'f'}, {"slab-min-size", required_argument, 0, 'n'}, {"threads", required_argument, 0, 't'}, {"enable-largepages", no_argument, 0, 'L'}, {"max-reqs-per-event", required_argument, 0, 'R'}, {"disable-cas", no_argument, 0, 'C'}, {"listen-backlog", required_argument, 0, 'b'}, {"protocol", required_argument, 0, 'B'}, {"max-item-size", required_argument, 0, 'I'}, {"enable-sasl", no_argument, 0, 'S'}, {"disable-flush-all", no_argument, 0, 'F'}, {"disable-dumping", no_argument, 0, 'X'}, {"auth-file", required_argument, 0, 'Y'}, {"extended", required_argument, 0, 'o'}, {0, 0, 0, 0} }; int optindex; while (-1 != (c = getopt_long(argc, argv, shortopts, longopts, &optindex))) { #else while (-1 != (c = getopt(argc, argv, shortopts))) { #endif switch (c) { case 'A': /* enables "shutdown" command */ settings.shutdown_command = true; break; case 'Z': /* enable secure communication*/ #ifdef TLS settings.ssl_enabled = true; #else fprintf(stderr, "This server is not built with TLS support.\n"); exit(EX_USAGE); #endif break; case 'a': /* access for unix domain socket, as octal mask (like chmod)*/ settings.access= strtol(optarg,NULL,8); break; case 'U': settings.udpport = atoi(optarg); udp_specified = true; break; case 'p': settings.port = atoi(optarg); tcp_specified = true; break; case 's': settings.socketpath = optarg; break; case 'm': settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024; break; case 'M': settings.evict_to_free = 0; break; case 'c': settings.maxconns = atoi(optarg); if (settings.maxconns <= 0) { fprintf(stderr, "Maximum connections must be greater than 0\n"); return 1; } break; case 'h': usage(); exit(EXIT_SUCCESS); case 'i': usage_license(); exit(EXIT_SUCCESS); case 'V': printf(PACKAGE " " VERSION "\n"); exit(EXIT_SUCCESS); case 'k': lock_memory = true; break; case 'v': settings.verbose++; break; case 'l': if (settings.inter != NULL) { if (strstr(settings.inter, optarg) != NULL) { break; } size_t len = strlen(settings.inter) + strlen(optarg) + 2; char *p = malloc(len); if (p == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } snprintf(p, len, "%s,%s", settings.inter, optarg); free(settings.inter); settings.inter = p; } else { settings.inter= strdup(optarg); } break; case 'd': do_daemonize = true; break; case 'r': maxcore = 1; break; case 'R': settings.reqs_per_event = atoi(optarg); if (settings.reqs_per_event == 0) { fprintf(stderr, "Number of requests per event must be greater than 0\n"); return 1; } break; case 'u': username = optarg; break; case 'P': pid_file = optarg; break; case 'f': settings.factor = atof(optarg); if (settings.factor <= 1.0) { fprintf(stderr, "Factor must be greater than 1\n"); return 1; } break; case 'n': settings.chunk_size = atoi(optarg); if (settings.chunk_size == 0) { fprintf(stderr, "Chunk size must be greater than 0\n"); return 1; } break; case 't': settings.num_threads = atoi(optarg); if (settings.num_threads <= 0) { fprintf(stderr, "Number of threads must be greater than 0\n"); return 1; } /* There're other problems when you get above 64 threads. * In the future we should portably detect # of cores for the * default. */ if (settings.num_threads > 64) { fprintf(stderr, "WARNING: Setting a high number of worker" "threads is not recommended.\n" " Set this value to the number of cores in" " your machine or less.\n"); } break; case 'D': if (! optarg || ! optarg[0]) { fprintf(stderr, "No delimiter specified\n"); return 1; } settings.prefix_delimiter = optarg[0]; settings.detail_enabled = 1; break; case 'L' : if (enable_large_pages() == 0) { preallocate = true; } else { fprintf(stderr, "Cannot enable large pages on this system\n" "(There is no support as of this version)\n"); return 1; } break; case 'C' : settings.use_cas = false; break; case 'b' : settings.backlog = atoi(optarg); break; case 'B': protocol_specified = true; if (strcmp(optarg, "auto") == 0) { settings.binding_protocol = negotiating_prot; } else if (strcmp(optarg, "binary") == 0) { settings.binding_protocol = binary_prot; } else if (strcmp(optarg, "ascii") == 0) { settings.binding_protocol = ascii_prot; } else { fprintf(stderr, "Invalid value for binding protocol: %s\n" " -- should be one of auto, binary, or ascii\n", optarg); exit(EX_USAGE); } break; case 'I': buf = strdup(optarg); unit = buf[strlen(buf)-1]; if (unit == 'k' || unit == 'm' || unit == 'K' || unit == 'M') { buf[strlen(buf)-1] = '\0'; size_max = atoi(buf); if (unit == 'k' || unit == 'K') size_max *= 1024; if (unit == 'm' || unit == 'M') size_max *= 1024 * 1024; settings.item_size_max = size_max; } else { settings.item_size_max = atoi(buf); } free(buf); break; case 'S': /* set Sasl authentication to true. Default is false */ #ifndef ENABLE_SASL fprintf(stderr, "This server is not built with SASL support.\n"); exit(EX_USAGE); #endif settings.sasl = true; break; case 'F' : settings.flush_enabled = false; break; case 'X' : settings.dump_enabled = false; break; case 'Y' : // dupe the file path now just in case the options get mangled. settings.auth_file = strdup(optarg); break; case 'o': /* It's sub-opts time! */ subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */ while (*subopts != '\0') { switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) { case MAXCONNS_FAST: settings.maxconns_fast = true; break; case HASHPOWER_INIT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for hashpower\n"); return 1; } settings.hashpower_init = atoi(subopts_value); if (settings.hashpower_init < 12) { fprintf(stderr, "Initial hashtable multiplier of %d is too low\n", settings.hashpower_init); return 1; } else if (settings.hashpower_init > 32) { fprintf(stderr, "Initial hashtable multiplier of %d is too high\n" "Choose a value based on \"STAT hash_power_level\" from a running instance\n", settings.hashpower_init); return 1; } break; case NO_HASHEXPAND: start_assoc_maint = false; break; case SLAB_REASSIGN: settings.slab_reassign = true; break; case SLAB_AUTOMOVE: if (subopts_value == NULL) { settings.slab_automove = 1; break; } settings.slab_automove = atoi(subopts_value); if (settings.slab_automove < 0 || settings.slab_automove > 2) { fprintf(stderr, "slab_automove must be between 0 and 2\n"); return 1; } break; case SLAB_AUTOMOVE_RATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_ratio argument\n"); return 1; } settings.slab_automove_ratio = atof(subopts_value); if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) { fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n"); return 1; } break; case SLAB_AUTOMOVE_WINDOW: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_window argument\n"); return 1; } settings.slab_automove_window = atoi(subopts_value); if (settings.slab_automove_window < 3) { fprintf(stderr, "slab_automove_window must be > 2\n"); return 1; } break; case TAIL_REPAIR_TIME: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for tail_repair_time\n"); return 1; } settings.tail_repair_time = atoi(subopts_value); if (settings.tail_repair_time < 10) { fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n"); return 1; } break; case HASH_ALGORITHM: if (subopts_value == NULL) { fprintf(stderr, "Missing hash_algorithm argument\n"); return 1; }; if (strcmp(subopts_value, "jenkins") == 0) { hash_type = JENKINS_HASH; } else if (strcmp(subopts_value, "murmur3") == 0) { hash_type = MURMUR3_HASH; } else { fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n"); return 1; } break; case LRU_CRAWLER: start_lru_crawler = true; break; case LRU_CRAWLER_SLEEP: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_sleep value\n"); return 1; } settings.lru_crawler_sleep = atoi(subopts_value); if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) { fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n"); return 1; } break; case LRU_CRAWLER_TOCRAWL: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_tocrawl value\n"); return 1; } if (!safe_strtoul(subopts_value, &tocrawl)) { fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n"); return 1; } settings.lru_crawler_tocrawl = tocrawl; break; case LRU_MAINTAINER: start_lru_maintainer = true; settings.lru_segmented = true; break; case HOT_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_lru_pct argument\n"); return 1; } settings.hot_lru_pct = atoi(subopts_value); if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) { fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n"); return 1; } break; case WARM_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_lru_pct argument\n"); return 1; } settings.warm_lru_pct = atoi(subopts_value); if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) { fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n"); return 1; } break; case HOT_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_max_factor argument\n"); return 1; } settings.hot_max_factor = atof(subopts_value); if (settings.hot_max_factor <= 0) { fprintf(stderr, "hot_max_factor must be > 0\n"); return 1; } break; case WARM_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_max_factor argument\n"); return 1; } settings.warm_max_factor = atof(subopts_value); if (settings.warm_max_factor <= 0) { fprintf(stderr, "warm_max_factor must be > 0\n"); return 1; } break; case TEMPORARY_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing temporary_ttl argument\n"); return 1; } settings.temp_lru = true; settings.temporary_ttl = atoi(subopts_value); break; case IDLE_TIMEOUT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for idle_timeout\n"); return 1; } settings.idle_timeout = atoi(subopts_value); break; case WATCHER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing watcher_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) { fprintf(stderr, "could not parse argument to watcher_logbuf_size\n"); return 1; } settings.logger_watcher_buf_size *= 1024; /* kilobytes */ break; case WORKER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing worker_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) { fprintf(stderr, "could not parse argument to worker_logbuf_size\n"); return 1; } settings.logger_buf_size *= 1024; /* kilobytes */ case SLAB_SIZES: slab_sizes_unparsed = strdup(subopts_value); break; case SLAB_CHUNK_MAX: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_chunk_max argument\n"); } if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) { fprintf(stderr, "could not parse argument to slab_chunk_max\n"); } slab_chunk_size_changed = true; break; case TRACK_SIZES: item_stats_sizes_init(); break; case NO_INLINE_ASCII_RESP: break; case INLINE_ASCII_RESP: break; case NO_CHUNKED_ITEMS: settings.slab_chunk_size_max = settings.slab_page_size; break; case NO_SLAB_REASSIGN: settings.slab_reassign = false; break; case NO_SLAB_AUTOMOVE: settings.slab_automove = 0; break; case NO_MAXCONNS_FAST: settings.maxconns_fast = false; break; case NO_LRU_CRAWLER: settings.lru_crawler = false; start_lru_crawler = false; break; case NO_LRU_MAINTAINER: start_lru_maintainer = false; settings.lru_segmented = false; break; #ifdef TLS case SSL_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_chain_cert argument\n"); return 1; } settings.ssl_chain_cert = strdup(subopts_value); break; case SSL_KEY: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_key argument\n"); return 1; } settings.ssl_key = strdup(subopts_value); break; case SSL_VERIFY_MODE: { if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_verify_mode argument\n"); return 1; } int verify = 0; if (!safe_strtol(subopts_value, &verify)) { fprintf(stderr, "could not parse argument to ssl_verify_mode\n"); return 1; } switch(verify) { case 0: settings.ssl_verify_mode = SSL_VERIFY_NONE; break; case 1: settings.ssl_verify_mode = SSL_VERIFY_PEER; break; case 2: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; break; case 3: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; break; default: fprintf(stderr, "Invalid ssl_verify_mode. Use help to see valid options.\n"); return 1; } break; } case SSL_KEYFORM: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_keyformat argument\n"); return 1; } if (!safe_strtol(subopts_value, &settings.ssl_keyformat)) { fprintf(stderr, "could not parse argument to ssl_keyformat\n"); return 1; } break; case SSL_CIPHERS: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ciphers argument\n"); return 1; } settings.ssl_ciphers = strdup(subopts_value); break; case SSL_CA_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ca_cert argument\n"); return 1; } settings.ssl_ca_cert = strdup(subopts_value); break; case SSL_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ssl_wbuf_size)) { fprintf(stderr, "could not parse argument to ssl_wbuf_size\n"); return 1; } settings.ssl_wbuf_size *= 1024; /* kilobytes */ break; #endif #ifdef EXTSTORE case EXT_PAGE_SIZE: if (storage_file) { fprintf(stderr, "Must specify ext_page_size before any ext_path arguments\n"); return 1; } if (subopts_value == NULL) { fprintf(stderr, "Missing ext_page_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.page_size)) { fprintf(stderr, "could not parse argument to ext_page_size\n"); return 1; } ext_cf.page_size *= 1024 * 1024; /* megabytes */ break; case EXT_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) { fprintf(stderr, "could not parse argument to ext_wbuf_size\n"); return 1; } ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */ settings.ext_wbuf_size = ext_cf.wbuf_size; break; case EXT_THREADS: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_threads argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) { fprintf(stderr, "could not parse argument to ext_threads\n"); return 1; } break; case EXT_IO_DEPTH: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_io_depth argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) { fprintf(stderr, "could not parse argument to ext_io_depth\n"); return 1; } break; case EXT_ITEM_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_size)) { fprintf(stderr, "could not parse argument to ext_item_size\n"); return 1; } break; case EXT_ITEM_AGE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_age argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_age)) { fprintf(stderr, "could not parse argument to ext_item_age\n"); return 1; } break; case EXT_LOW_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_low_ttl argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) { fprintf(stderr, "could not parse argument to ext_low_ttl\n"); return 1; } break; case EXT_RECACHE_RATE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_recache_rate argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) { fprintf(stderr, "could not parse argument to ext_recache_rate\n"); return 1; } break; case EXT_COMPACT_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_compact_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) { fprintf(stderr, "could not parse argument to ext_compact_under\n"); return 1; } break; case EXT_DROP_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_drop_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) { fprintf(stderr, "could not parse argument to ext_drop_under\n"); return 1; } break; case EXT_MAX_FRAG: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_max_frag argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.ext_max_frag)) { fprintf(stderr, "could not parse argument to ext_max_frag\n"); return 1; } break; case SLAB_AUTOMOVE_FREERATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_freeratio argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) { fprintf(stderr, "could not parse argument to slab_automove_freeratio\n"); return 1; } break; case EXT_DROP_UNREAD: settings.ext_drop_unread = true; break; case EXT_PATH: if (subopts_value) { struct extstore_conf_file *tmp = storage_conf_parse(subopts_value, ext_cf.page_size); if (tmp == NULL) { fprintf(stderr, "failed to parse ext_path argument\n"); return 1; } if (storage_file != NULL) { tmp->next = storage_file; } storage_file = tmp; } else { fprintf(stderr, "missing argument to ext_path, ie: ext_path=/d/file:5G\n"); return 1; } break; #endif case MODERN: /* currently no new defaults */ break; case NO_MODERN: if (!slab_chunk_size_changed) { settings.slab_chunk_size_max = settings.slab_page_size; } settings.slab_reassign = false; settings.slab_automove = 0; settings.maxconns_fast = false; settings.lru_segmented = false; hash_type = JENKINS_HASH; start_lru_crawler = false; start_lru_maintainer = false; break; case NO_DROP_PRIVILEGES: settings.drop_privileges = false; break; case DROP_PRIVILEGES: settings.drop_privileges = true; break; #ifdef MEMCACHED_DEBUG case RELAXED_PRIVILEGES: settings.relaxed_privileges = true; break; #endif default: printf("Illegal suboption \"%s\"\n", subopts_value); return 1; } } free(subopts_orig); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings.item_size_max < 1024) { fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n"); exit(EX_USAGE); } if (settings.item_size_max > (settings.maxbytes / 2)) { fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n"); exit(EX_USAGE); } if (settings.item_size_max > (1024 * 1024 * 1024)) { fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n"); exit(EX_USAGE); } if (settings.item_size_max > 1024 * 1024) { if (!slab_chunk_size_changed) { // Ideal new default is 16k, but needs stitching. settings.slab_chunk_size_max = settings.slab_page_size / 2; } } if (settings.slab_chunk_size_max > settings.item_size_max) { fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n", settings.slab_chunk_size_max, settings.item_size_max); exit(EX_USAGE); } if (settings.item_size_max % settings.slab_chunk_size_max != 0) { fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n", settings.item_size_max, settings.slab_chunk_size_max); exit(EX_USAGE); } if (settings.slab_page_size % settings.slab_chunk_size_max != 0) { fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n", settings.slab_chunk_size_max, settings.slab_page_size); exit(EX_USAGE); } #ifdef EXTSTORE if (storage_file) { if (settings.item_size_max > ext_cf.wbuf_size) { fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n", settings.item_size_max, ext_cf.wbuf_size); exit(EX_USAGE); } if (settings.udpport) { fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n"); exit(EX_USAGE); } } #endif // Reserve this for the new default. If factor size hasn't changed, use // new default. /*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) { settings.factor = 1.08; }*/ if (slab_sizes_unparsed != NULL) { if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) { use_slab_sizes = true; } else { exit(EX_USAGE); } } if (settings.hot_lru_pct + settings.warm_lru_pct > 80) { fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n"); exit(EX_USAGE); } if (settings.temp_lru && !start_lru_maintainer) { fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n"); exit(EX_USAGE); } if (hash_init(hash_type) != 0) { fprintf(stderr, "Failed to initialize hash_algorithm!\n"); exit(EX_USAGE); } /* * Use one workerthread to serve each UDP port if the user specified * multiple ports */ if (settings.inter != NULL && strchr(settings.inter, ',')) { settings.num_threads_per_udp = 1; } else { settings.num_threads_per_udp = settings.num_threads; } if (settings.sasl) { if (!protocol_specified) { settings.binding_protocol = binary_prot; } else { if (settings.binding_protocol != binary_prot) { fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n"); exit(EX_USAGE); } } } if (settings.auth_file) { if (!protocol_specified) { settings.binding_protocol = ascii_prot; } else { if (settings.binding_protocol != ascii_prot) { fprintf(stderr, "ERROR: You cannot allow the BINARY protocol while using ascii authentication tokens.\n"); exit(EX_USAGE); } } } if (udp_specified && settings.udpport != 0 && !tcp_specified) { settings.port = settings.udpport; } #ifdef TLS /* * Setup SSL if enabled */ if (settings.ssl_enabled) { if (!settings.port) { fprintf(stderr, "ERROR: You cannot enable SSL without a TCP port.\n"); exit(EX_USAGE); } // openssl init methods. SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); // Initiate the SSL context. ssl_init(); } #endif if (maxcore != 0) { struct rlimit rlim_new; /* * First try raising to infinity; if that fails, try bringing * the soft limit to the hard. */ if (getrlimit(RLIMIT_CORE, &rlim) == 0) { rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) { /* failed. try raising just to the old max */ rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max; (void)setrlimit(RLIMIT_CORE, &rlim_new); } } /* * getrlimit again to see what we ended up with. Only fail if * the soft limit ends up 0, because then no core files will be * created at all. */ if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) { fprintf(stderr, "failed to ensure corefile creation\n"); exit(EX_OSERR); } } /* * If needed, increase rlimits to allow as many connections * as needed. */ if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to getrlimit number of files\n"); exit(EX_OSERR); } else { rlim.rlim_cur = settings.maxconns; rlim.rlim_max = settings.maxconns; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n"); exit(EX_OSERR); } } /* lose root privileges if we have them */ if (getuid() == 0 || geteuid() == 0) { if (username == 0 || *username == '\0') { fprintf(stderr, "can't run as root without the -u switch\n"); exit(EX_USAGE); } if ((pw = getpwnam(username)) == 0) { fprintf(stderr, "can't find the user %s to switch to\n", username); exit(EX_NOUSER); } if (setgroups(0, NULL) < 0) { fprintf(stderr, "failed to drop supplementary groups\n"); exit(EX_OSERR); } if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { fprintf(stderr, "failed to assume identity of user %s\n", username); exit(EX_OSERR); } } /* Initialize Sasl if -S was specified */ if (settings.sasl) { init_sasl(); } /* daemonize if requested */ /* if we want to ensure our ability to dump core, don't chdir to / */ if (do_daemonize) { if (sigignore(SIGHUP) == -1) { perror("Failed to ignore SIGHUP"); } if (daemonize(maxcore, settings.verbose) == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } /* lock paged memory if needed */ if (lock_memory) { #ifdef HAVE_MLOCKALL int res = mlockall(MCL_CURRENT | MCL_FUTURE); if (res != 0) { fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n", strerror(errno)); } #else fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n"); #endif } /* initialize main thread libevent instance */ #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101 /* If libevent version is larger/equal to 2.0.2-alpha, use newer version */ struct event_config *ev_config; ev_config = event_config_new(); event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK); main_base = event_base_new_with_config(ev_config); event_config_free(ev_config); #else /* Otherwise, use older API */ main_base = event_init(); #endif /* Load initial auth file if required */ if (settings.auth_file) { if (settings.udpport) { fprintf(stderr, "Cannot use UDP with ascii authentication enabled (-U 0 to disable)\n"); exit(EX_USAGE); } switch (authfile_load(settings.auth_file)) { case AUTHFILE_MISSING: // fall through. case AUTHFILE_OPENFAIL: vperror("Could not open authfile [%s] for reading", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OOM: fprintf(stderr, "Out of memory reading password file: %s", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_MALFORMED: fprintf(stderr, "Authfile [%s] has a malformed entry. Should be 'user:password'", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OK: break; } } /* initialize other stuff */ logger_init(); stats_init(); assoc_init(settings.hashpower_init); conn_init(); slabs_init(settings.maxbytes, settings.factor, preallocate, use_slab_sizes ? slab_sizes : NULL); #ifdef EXTSTORE if (storage_file) { enum extstore_res eres; if (settings.ext_compact_under == 0) { settings.ext_compact_under = storage_file->page_count / 4; /* Only rescues non-COLD items if below this threshold */ settings.ext_drop_under = storage_file->page_count / 4; } crc32c_init(); /* Init free chunks to zero. */ for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) { settings.ext_free_memchunks[x] = 0; } storage = extstore_init(storage_file, &ext_cf, &eres); if (storage == NULL) { fprintf(stderr, "Failed to initialize external storage: %s\n", extstore_err(eres)); if (eres == EXTSTORE_INIT_OPEN_FAIL) { perror("extstore open"); } exit(EXIT_FAILURE); } ext_storage = storage; /* page mover algorithm for extstore needs memory prefilled */ slabs_prefill_global(); } #endif if (settings.drop_privileges) { setup_privilege_violations_handler(); } /* * ignore SIGPIPE signals; we can use errno == EPIPE if we * need that information */ if (sigignore(SIGPIPE) == -1) { perror("failed to ignore SIGPIPE; sigaction"); exit(EX_OSERR); } /* start up worker threads if MT mode */ #ifdef EXTSTORE slabs_set_storage(storage); memcached_thread_init(settings.num_threads, storage); init_lru_crawler(storage); #else memcached_thread_init(settings.num_threads, NULL); init_lru_crawler(NULL); #endif if (start_assoc_maint && start_assoc_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (start_lru_crawler && start_item_crawler_thread() != 0) { fprintf(stderr, "Failed to enable LRU crawler thread\n"); exit(EXIT_FAILURE); } #ifdef EXTSTORE if (storage && start_storage_compact_thread(storage) != 0) { fprintf(stderr, "Failed to start storage compaction thread\n"); exit(EXIT_FAILURE); } if (storage && start_storage_write_thread(storage) != 0) { fprintf(stderr, "Failed to start storage writer thread\n"); exit(EXIT_FAILURE); } if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) { #else if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) { #endif fprintf(stderr, "Failed to enable LRU maintainer thread\n"); return 1; } if (settings.slab_reassign && start_slab_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (settings.idle_timeout && start_conn_timeout_thread() == -1) { exit(EXIT_FAILURE); } /* initialise clock event */ clock_handler(0, 0, 0); /* create unix mode sockets after dropping privileges */ if (settings.socketpath != NULL) { errno = 0; if (server_socket_unix(settings.socketpath,settings.access)) { vperror("failed to listen on UNIX socket: %s", settings.socketpath); exit(EX_OSERR); } } /* create the listening socket, bind it, and init */ if (settings.socketpath == NULL) { const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME"); char *temp_portnumber_filename = NULL; size_t len; FILE *portnumber_file = NULL; if (portnumber_filename != NULL) { len = strlen(portnumber_filename)+4+1; temp_portnumber_filename = malloc(len); snprintf(temp_portnumber_filename, len, "%s.lck", portnumber_filename); portnumber_file = fopen(temp_portnumber_filename, "a"); if (portnumber_file == NULL) { fprintf(stderr, "Failed to open \"%s\": %s\n", temp_portnumber_filename, strerror(errno)); } } errno = 0; if (settings.port && server_sockets(settings.port, tcp_transport, portnumber_file)) { vperror("failed to listen on TCP port %d", settings.port); exit(EX_OSERR); } /* * initialization order: first create the listening sockets * (may need root on low ports), then drop root if needed, * then daemonize if needed, then init libevent (in some cases * descriptors created by libevent wouldn't survive forking). */ /* create the UDP listening socket and bind it */ errno = 0; if (settings.udpport && server_sockets(settings.udpport, udp_transport, portnumber_file)) { vperror("failed to listen on UDP port %d", settings.udpport); exit(EX_OSERR); } if (portnumber_file) { fclose(portnumber_file); rename(temp_portnumber_filename, portnumber_filename); } if (temp_portnumber_filename) free(temp_portnumber_filename); } /* Give the sockets a moment to open. I know this is dumb, but the error * is only an advisory. */ usleep(1000); if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n"); exit(EXIT_FAILURE); } if (pid_file != NULL) { save_pid(pid_file); } /* Drop privileges no longer needed */ if (settings.drop_privileges) { drop_privileges(); } /* Initialize the uriencode lookup table. */ uriencode_init(); /* enter the event loop */ if (event_base_loop(main_base, 0) != 0) { retval = EXIT_FAILURE; } stop_assoc_maintenance_thread(); /* remove the PID file if we're a daemon */ if (do_daemonize) remove_pidfile(pid_file); /* Clean up strdup() call for bind() address */ if (settings.inter) free(settings.inter); /* cleanup base */ event_base_free(main_base); return retval; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1011_0
crossvul-cpp_data_bad_580_0
#ifndef IGNOREALL /* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.476 $ $Date: 2015/05/25 02:29:14 $ */ /*@out DEFINES #ifndef USE_JPEG #define NO_JPEG #endif #ifndef USE_JASPER #define NO_JASPER #endif @end DEFINES */ #define NO_LCMS #define DCRAW_VERBOSE //@out DEFINES #define DCRAW_VERSION "9.26" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _USE_MATH_DEFINES #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> //@end DEFINES #if defined(DJGPP) || defined(__MINGW32__) #define fseeko fseek #define ftello ftell #else #define fgetc getc_unlocked #endif //@out DEFINES #ifdef __CYGWIN__ #include <io.h> #endif #if defined WIN32 || defined (__MINGW32__) #include <sys/utime.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define snprintf _snprintf #define strcasecmp stricmp #define strncasecmp strnicmp //@end DEFINES typedef __int64 INT64; typedef unsigned __int64 UINT64; //@out DEFINES #else #include <unistd.h> #include <utime.h> #include <netinet/in.h> typedef long long INT64; typedef unsigned long long UINT64; #endif #ifdef NODEPS #define NO_JASPER #define NO_JPEG #define NO_LCMS #endif #ifndef NO_JASPER #include <jasper/jasper.h> /* Decode Red camera movies */ #endif #ifndef NO_JPEG #include <jpeglib.h> /* Decode compressed Kodak DC120 photos */ #endif /* and Adobe Lossy DNGs */ #ifndef NO_LCMS #ifdef USE_LCMS #include <lcms.h> /* Support color profiles */ #else #include <lcms2.h> /* Support color profiles */ #endif #endif #ifdef LOCALEDIR #include <libintl.h> #define _(String) gettext(String) #else #define _(String) (String) #endif #ifdef LJPEG_DECODE #error Please compile dcraw.c by itself. #error Do not link it with ljpeg_decode. #endif #ifndef LONG_BIT #define LONG_BIT (8 * sizeof (long)) #endif //@end DEFINES #if !defined(uchar) #define uchar unsigned char #endif #if !defined(ushort) #define ushort unsigned short #endif /* All global variables are defined here, and all functions that access them are prefixed with "CLASS". Note that a thread-safe C++ class cannot have non-const static local variables. */ FILE *ifp, *ofp; short order; const char *ifname; char *meta_data, xtrans[6][6], xtrans_abs[6][6]; char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64],software[64]; float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len; time_t timestamp; off_t strip_offset, data_offset; off_t thumb_offset, meta_offset, profile_offset; unsigned shot_order, kodak_cbpp, exif_cfa, unique_id; unsigned thumb_length, meta_length, profile_length; unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0; unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress; unsigned black, maximum, mix_green, raw_color, zero_is_bad; unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error; unsigned tile_width, tile_length, gpsdata[32], load_flags; unsigned flip, tiff_flip, filters, colors; ushort raw_height, raw_width, height, width, top_margin, left_margin; ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height; ushort *raw_image, (*image)[4], cblack[4102]; ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4]; double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 }; float bright=1, user_mul[4]={0,0,0,0}, threshold=0; int mask[8][4]; int half_size=0, four_color_rgb=0, document_mode=0, highlight=0; int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=1; int output_color=1, output_bps=8, output_tiff=0, med_passes=0; int no_auto_bright=0; unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX }; float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4]; const double xyz_rgb[3][3] = { /* XYZ from RGB */ { 0.412453, 0.357580, 0.180423 }, { 0.212671, 0.715160, 0.072169 }, { 0.019334, 0.119193, 0.950227 } }; const float d65_white[3] = { 0.950456, 1, 1.088754 }; int histogram[4][0x2000]; void (*write_thumb)(), (*write_fun)(); void (*load_raw)(), (*thumb_load_raw)(); jmp_buf failure; struct decode { struct decode *branch[2]; int leaf; } first_decode[2048], *second_decode, *free_decode; struct tiff_ifd { int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes; int t_tile_width, t_tile_length,sample_format,predictor; float t_shutter; } tiff_ifd[10]; struct ph1 { int format, key_off, tag_21a; int t_black, split_col, black_col, split_row, black_row; float tag_210; } ph1; #define CLASS //@out DEFINES #define FORC(cnt) for (c=0; c < cnt; c++) #define FORC3 FORC(3) #define FORC4 FORC(4) #define FORCC for (c=0; c < colors && c < 4; c++) #define SQR(x) ((x)*(x)) #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31)) #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y)) #define CLIP(x) LIM((int)(x),0,65535) #define SWAP(a,b) { a=a+b; b=a-b; a=a-b; } #define my_swap(type, i, j) {type t = i; i = j; j = t;} static float fMAX(float a, float b) { return MAX(a,b); } /* In order to inline this calculation, I make the risky assumption that all filter patterns can be described by a repeating pattern of eight rows and two columns Do not use the FC or BAYER macros with the Leaf CatchLight, because its pattern is 16x16, not 2x8. Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2 PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1 0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M 1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C 2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y 3 C Y C Y C Y 3 G M G M G M 3 G M G M G M 4 C Y C Y C Y 4 Y C Y C Y C PowerShot A5 5 G M G M G M 5 G M G M G M 0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y 7 M G M G M G 7 M G M G M G 0 1 2 3 4 5 0 C Y C Y C Y 1 G M G M G M 2 C Y C Y C Y 3 M G M G M G All RGB cameras use one of these Bayer grids: 0x16161616: 0x61616161: 0x49494949: 0x94949494: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G 1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B 2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G 3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B */ #define RAW(row,col) \ raw_image[(row)*raw_width+(col)] //@end DEFINES #define FC(row,col) \ (filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3) //@out DEFINES #define BAYER(row,col) \ image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)] #define BAYER2(row,col) \ image[((row) >> shrink)*iwidth + ((col) >> shrink)][fcol(row,col)] //@end DEFINES /* @out COMMON #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end COMMON */ //@out COMMON int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) //@end COMMON void CLASS merror (void *ptr, const char *where) { if (ptr) return; fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where); longjmp (failure, 1); } void CLASS derror() { if (!data_error) { fprintf (stderr, "%s: ", ifname); if (feof(ifp)) fprintf (stderr,_("Unexpected end of file\n")); else fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp)); } data_error++; } //@out COMMON ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, unsigned count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } //@end COMMON struct jhead { int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6]; ushort quant[64], idct[64], *huff[20], *free[20], *row; }; //@out COMMON int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width*3*tiff_bps/8; if(tiff_bps <= 8) gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } //@end COMMON void CLASS jpeg_thumb(); //@out COMMON void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten=0, isix, i, buffer=0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i=0; i < 16; i+=2) raw_image[todo[i]] = (todo[i+1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD else if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if(width>768 || raw_width>768 || height > 512 || raw_height>512 ) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* extra room for data stored w/o predictor */ int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c=0; c < 16; c+=2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) + (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } //@end COMMON /* RESTRICTED code starts here */ void CLASS foveon_decoder (unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i=0; i < size; i++) huff[i] = get4(); memset (first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode+2048) { fprintf (stderr,_("%s: decoder table overflow\n"), ifname); longjmp (failure, 2); } if (code) for (i=0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len+1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder (size, code); cur->branch[1] = free_decode; foveon_decoder (size, code+1); } void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf=0, bit=1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width*3) return; buf = (char *) malloc (bwide); merror (buf, "foveon_thumb()"); for (row=0; row < thumb_height; row++) { fread (buf, 1, bwide, ifp); fwrite (buf, 3, thumb_width, ofp); } free (buf); return; } foveon_decoder (256, 0); for (row=0; row < thumb_height; row++) { memset (pred, 0, sizeof pred); if (!bit) get4(); for (bit=col=0; col < thumb_width; col++) FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc (pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct decode *dindex; short diff[1024]; unsigned bitbuf=0; int pred[3], row, col, bit=-1, c, i; read_shorts ((ushort *) diff, 1024); if (!load_flags) foveon_decoder (1024, 0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model+2) < 14) get4(); for (col=bit=0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff]; } else FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row*width+col][c] = pred[c]; } } } void CLASS foveon_huff (ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i=0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j=0; j < 256 >> clen; ) huff[code+ ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek (ifp, 8, SEEK_CUR); foveon_huff (huff); roff[0] = 48; FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek (ifp, data_offset+roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row*width+col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } #ifdef DCRAW_VERBOSE else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); #endif } const char * CLASS foveon_camf_param (const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp (block, pos+sget4(pos+12))) continue; cp = pos + sget4(pos+16); num = sget4(cp); dp = pos + sget4(cp+4); while (num--) { cp += 8; if (!strcmp (param, dp+sget4(cp))) return dp+sget4(cp+4); } } return 0; } void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp (name, pos+sget4(pos+12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos+16); type = sget4(cp); if ((ndim = sget4(cp+4)) > 3) break; dp = pos + sget4(cp+8); for (i=ndim; i--; ) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break; mat = (unsigned *) malloc ((size = dsize) * 4); merror (mat, "foveon_camf_matrix()"); for (i=0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i*4); else mat[i] = sget4(dp + i*2) & 0xffff; return mat; } #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name); #endif return 0; } int CLASS foveon_fixed (void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix (dim, name); if (!dp) return 0; memcpy (ptr, dp, size*4); free (dp); return 1; } float CLASS foveon_avg (short *pix, int range[2], float cfilt) { int i; float val, min=FLT_MAX, max=-FLT_MAX, sum=0; for (i=range[0]; i <= range[1]; i++) { sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum/2; return (sum - min - max) / (range[1] - range[0] - 1); } short * CLASS foveon_make_curve (double max, double mul, double filt) { short *curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4*M_PI*max / filt; if (size == UINT_MAX) size--; curve = (short *) calloc (size+1, sizeof *curve); merror (curve, "foveon_make_curve()"); curve[0] = size; for (i=0; i < size; i++) { x = i*filt/max/4; curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5; } return curve; } void CLASS foveon_make_curves (short **curvep, float dq[3], float div[3], float filt) { double mul[3], max=0; int c; FORC3 mul[c] = dq[c]/div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt); } int CLASS foveon_apply_curve (short *curve, int i) { if (abs(i) >= curve[0]) return 0; return i < 0 ? -curve[1-i] : curve[1+i]; } #define image ((short (*)[4]) image) void CLASS foveon_interpolate() { static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 }; short *pix, prev[3], *curve[8], (*shrink)[3]; float cfilt=0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float (*black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p=0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum=0, trsum[3]; char str[128]; const char* cp; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Foveon interpolation...\n")); #endif foveon_load_camf(); foveon_fixed (dscr, 4, "DarkShieldColRange"); foveon_fixed (ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed (satlev, 3, "SaturationLevel"); foveon_fixed (keep, 4, "KeepImageArea"); foveon_fixed (active, 4, "ActiveImageArea"); foveon_fixed (chroma_dq, 3, "ChromaDQ"); foveon_fixed (color_dq, 3, foveon_camf_param ("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param ("IncludeBlocks", "ColumnFilter")) foveon_fixed (&cfilt, 1, "ColumnFilter"); memset (ddft, 0, sizeof ddft); if (!foveon_camf_param ("IncludeBlocks", "DarkDrift") || !foveon_fixed (ddft[1][0], 12, "DarkDrift")) for (i=0; i < 2; i++) { foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c]; FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1); } if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2))) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2); #endif return; } foveon_fixed (cam_xyz, 9, cp); foveon_fixed (correct, 9, foveon_camf_param ("WhiteBalanceCorrections", model2)); memset (last, 0, sizeof last); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x,y) last[(i+x)%3][(c+y)%3] for (i=0; i < 3; i++) FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1); #undef LAST FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583; sprintf (str, "%sRGBNeutral", model2); if (foveon_camf_param ("IncludeBlocks", str)) foveon_fixed (div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20; for (i=0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30; foveon_make_curves (curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves (curve+3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; curve[6] = foveon_make_curve (dsum, dsum, cfilt); curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt); sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain"); if (!sgain) return; sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow); sgx = (width + dim[1]-2) / (dim[1]-1); black = (float (*)[3]) calloc (height, sizeof *black); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); FORC3 black[row][c] = ( foveon_avg (image[row*width]+c, dscr[0], cfilt) + foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3 - ddft[0][c][0] ) / 4 - ddft[0][c][1]; } memcpy (black, black+8, sizeof *black*8); memcpy (black+height-11, black+height-22, 11*sizeof *black); memcpy (last, black, sizeof last); for (row=1; row < height-1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c]; } else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c]; memmove (last, last+1, 2*sizeof last[0]); memcpy (last[2], black[row+1], sizeof last[2]); } FORC3 black[row][c] = (last[0][c] + last[1][c])/2; FORC3 black[0][c] = (black[1][c] + black[3][c])/2; val = 1 - exp(-1/24.0); memcpy (fsum, black, sizeof fsum); for (row=1; row < height; row++) FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row-1][c])*val + black[row-1][c]; memcpy (last[0], black[height-1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--; ) FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c])*val + last[0][c]; memset (total, 0, sizeof total); for (row=2; row < height; row+=4) for (col=2; col < width; col+=4) { FORC3 total[c] += (short) image[row*width+col][c]; total[3]++; } for (row=0; row < height; row++) FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); pix = image[row*width]; memcpy (prev, pix, sizeof prev); frow = row / (height-1.0) * (dim[2]-1); if ((irow = frow) == dim[2]-1) irow--; frow -= irow; for (i=0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[ irow *dim[1]+i][c] * (1-frow) + sgain[(irow+1)*dim[1]+i][c] * frow; for (col=0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5) - black[row][c] ); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14; } FORC3 { for (val=i=0; i < 3; i++) for ( j=0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor ((ipix[c] + floor(val)) * ( sgrow[col/sgx ][c] * (sgx - col%sgx) + sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free (black); free (sgrow); free (sgain); if ((badpix = (unsigned *) foveon_camf_matrix (dim, "BadPixels"))) { for (i=0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20 ) - keep[1]; if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3) continue; memset (fsum, 0, sizeof fsum); for (sum=j=0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short) image[(row+hood[j*2])*width+col+hood[j*2+1]][c]; sum++; } if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum; } free (badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow); merror (smrow[6], "foveon_interpolate()"); for (i=0; i < 5; i++) smrow[i] = smrow[6] + i*width; /* Sharpen the reds against these Gaussian averages */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { smrow[4][col][0] = (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { smred = ( 6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix=image[0]; pix < image[height*width]; pix+=4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c=1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit*2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i*i >> 14); i = i*i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] - ((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { for (total[3]=375, sum=60, c=0; c < 3; c++) { for (total[c]=i=0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve (curve[6], ((j*total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix=image[0]; pix < image[height*width]; pix+=4) { FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]); sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum); FORC3 { for (dsum=i=0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ shrink = (short (*)[3]) calloc ((height/4), (width/4)*sizeof *shrink); merror (shrink, "foveon_interpolate()"); for (row = height/4; row--; ) for (col=0; col < width/4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i=0; i < 4; i++) for (j=0; j < 4; j++) FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c]; FORC3 if (row+2 > height/4) shrink[row*(width/4)+col][c] = ipix[c] >> 4; else shrink[row*(width/4)+col][c] = (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row=0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3 ; col--; ) FORC3 smrow[0][col][c] = ipix[c] = (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col=0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy (smrow[2], smrow[1], sizeof **smrow * width); else for (col=0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col=0; col < (width & ~3); col++) { for (i=j=30, c=0; c < 3; c++) { i += smrow[2][col][c]; j += image[row*width+col][c]; } j = (j << 16) / i; for (sum=c=0; c < 3; c++) { ipix[c] = foveon_apply_curve (curve[c+3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row*width+col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row*width+col][c] = i; } } } free (shrink); free (smrow[6]); for (i=0; i < 8; i++) free (curve[i]); /* Trim off the black border */ active[1] -= keep[1]; active[3] -= 2; i = active[2] - active[0]; for (row=0; row < active[3]-active[1]; row++) memcpy (image[row*i], image[(row+active[1])*width+active[0]], i * sizeof *image); width = i; height = row; } #undef image /* RESTRICTED code ends here */ //@out COMMON void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } //@end COMMON /* @out FILEIO #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end FILEIO */ // @out FILEIO /* Seach from the current directory up to the root looking for a ".badpixels" file, and fix those pixels now. */ void CLASS bad_pixels (const char *cfname) { FILE *fp=NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed=0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2); #endif if (cfname) fp = fopen (cfname, "r"); // @end FILEIO else { for (len=32 ; ; len *= 2) { fname = (char *) malloc (len); if (!fname) return; if (getcwd (fname, len-16)) break; free (fname); if (errno != ERANGE) return; } #if defined(WIN32) || defined(DJGPP) if (fname[1] == ':') memmove (fname, fname+2, len-2); for (cp=fname; *cp; cp++) if (*cp == '\\') *cp = '/'; #endif cp = fname + strlen(fname); if (cp[-1] == '/') cp--; while (*fname == '/') { strcpy (cp, "/.badpixels"); if ((fp = fopen (fname, "r"))) break; if (cp == fname) break; while (*--cp != '/'); } free (fname); } // @out FILEIO if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets (line, 128, fp)) { cp = strchr (line, '#'); if (cp) *cp = 0; if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned) col >= width || (unsigned) row >= height) continue; if (time > timestamp) continue; for (tot=n=0, rad=1; rad < 3 && n==0; rad++) for (r = row-rad; r <= row+rad; r++) for (c = col-rad; c <= col+rad; c++) if ((unsigned) r < height && (unsigned) c < width && (r != row || c != col) && fcol(r,c) == fcol(row,col)) { tot += BAYER2(r,c); n++; } BAYER2(row,col) = tot/n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf (stderr,_("Fixed dead pixels at:")); fprintf (stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc ('\n', stderr); #endif fclose (fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2); #endif } void CLASS subtract (const char *fname) { FILE *fp; int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col; ushort *pixel; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,0,2); #endif if (!(fp = fopen (fname, "rb"))) { #ifdef DCRAW_VERBOSE perror (fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE; #endif return; } if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1; while (!error && nd < 3 && (c = fgetc(fp)) != EOF) { if (c == '#') comment = 1; if (c == '\n') comment = 0; if (comment) continue; if (isdigit(c)) number = 1; if (number) { if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0'; else if (isspace(c)) { number = 0; nd++; } else error = 1; } } if (error || nd < 3) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s is not a valid PGM file!\n"), fname); #endif fclose (fp); return; } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s has the wrong dimensions!\n"), fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM; #endif fclose (fp); return; } pixel = (ushort *) calloc (width, sizeof *pixel); merror (pixel, "subtract()"); for (row=0; row < height; row++) { fread (pixel, 2, width, fp); for (col=0; col < width; col++) BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0); } free (pixel); fclose (fp); memset (cblack, 0, sizeof cblack); black = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,1,2); #endif } //@end FILEIO //@out COMMON static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } //@end COMMON int CLASS parse_tiff_ifd (int base); //@out COMMON static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float libraw_powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * libraw_powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char* pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos+7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos+7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy (ccms, pos, l); ccms[l] = '\0'; pos = strtok (ccms, ","); for (l=0; l<4; l++) { num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok (NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif //@end COMMON void CLASS parse_minolta (int base); int CLASS parse_tiff (int base); //@out COMMON int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64(2.0f, -int_to_float((get4(),get4()))); aperture = libraw_powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = libraw_powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } //@end COMMON char * CLASS foveon_gets (int offset, char *str, int len) { int i; fseek (ifp, offset, SEEK_SET); for (i=0; i < len-1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek (ifp, 36, SEEK_SET); flip = get4(); fseek (ifp, -4, SEEK_END); fseek (ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(),get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek (ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek (ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off+28; is_foveon = 1; } fseek (ifp, off+28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len-28) { thumb_offset = off+28; thumb_length = len-28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off+24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off+8; meta_length = len-28; break; case 0x504f5250: /* PROP */ pent = (get4(),get4()); fseek (ifp, 12, SEEK_CUR); off += pent*8 + 24; if ((unsigned) pent > 256) pent=256; for (i=0; i < pent*2; i++) ((int *)poff)[i] = off + get4()*2; for (i=0; i < pent; i++) { foveon_gets (poff[i][0], name, 64); foveon_gets (poff[i][1], value, 64); if (!strcmp (name, "ISO")) iso_speed = atoi(value); if (!strcmp (name, "CAMMANUF")) strcpy (make, value); if (!strcmp (name, "CAMMODEL")) strcpy (model, value); if (!strcmp (name, "WB_DESC")) strcpy (model2, value); if (!strcmp (name, "TIME")) timestamp = atoi(value); if (!strcmp (name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp (name, "APERTURE")) aperture = atof(value); if (!strcmp (name, "FLENGTH")) focal_len = atof(value); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp (name, "CAMSERIAL")) strcpy (imgdata.shootinginfo.BodySerial, value); if (!strcmp (name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp (name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr (value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap (float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp (name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr (value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap (float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp (name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol (value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } #endif } #ifdef LOCALTIME timestamp = mktime (gmtime (&timestamp)); #endif } fseek (ifp, save, SEEK_SET); } } //@out COMMON /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[]={0,0}; FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if(len<1) return; // not needed, b/c sizeof of make/model is 64 string[len-1]=0; if(len<3) return; // also not needed len = strnlen(string,len-1); for(int i=len-1; i>=0; i--) { if(isspace(string[i])) string[i]=0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // data length should be in range w*h..w*h*2 if(width*height < (LIBRAW_MAX_ALLOC_MB*1024*512L) && width*height>1 && i >= width * height && i <= width*height*2) { #endif switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD } else is_raw = 0; #endif } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ( (int)width + (int)left_margin > 65535) || ( (int)height + (int)top_margin > 65535) ) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } //@end COMMON //@out FILEIO #ifndef NO_LCMS void CLASS apply_profile (const char *input, const char *output) { char *prof; cmsHPROFILE hInProfile=0, hOutProfile=0; cmsHTRANSFORM hTransform; FILE *fp; unsigned size; if (strcmp (input, "embed")) hInProfile = cmsOpenProfileFromFile (input, "r"); else if (profile_length) { #ifndef LIBRAW_LIBRARY_BUILD prof = (char *) malloc (profile_length); merror (prof, "apply_profile()"); fseek (ifp, profile_offset, SEEK_SET); fread (prof, 1, profile_length, ifp); hInProfile = cmsOpenProfileFromMem (prof, profile_length); free (prof); #else hInProfile = cmsOpenProfileFromMem (imgdata.color.profile, profile_length); #endif } else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s has no embedded profile.\n"), ifname); #endif } if (!hInProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE; #endif return; } if (!output) hOutProfile = cmsCreate_sRGBProfile(); else if ((fp = fopen (output, "rb"))) { fread (&size, 4, 1, fp); fseek (fp, 0, SEEK_SET); oprof = (unsigned *) malloc (size = ntohl(size)); merror (oprof, "apply_profile()"); fread (oprof, 1, size, fp); fclose (fp); if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) { free (oprof); oprof = 0; } } #ifdef DCRAW_VERBOSE else fprintf (stderr,_("Cannot open file %s!\n"), output); #endif if (!hOutProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE; #endif goto quit; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Applying color profile...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,0,2); #endif hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0); cmsDoTransform (hTransform, image, image, width*height); raw_color = 1; /* Don't use rgb_cam with a profile */ cmsDeleteTransform (hTransform); cmsCloseProfile (hOutProfile); quit: cmsCloseProfile (hInProfile); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,1,2); #endif } #endif //@end FILEIO //@out COMMON void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } //@end COMMON struct tiff_tag { ushort tag, type; int count; union { char c[4]; short s[2]; int i; } val; }; struct tiff_hdr { ushort t_order, magic; int ifd; ushort pad, ntag; struct tiff_tag tag[23]; int nextifd; ushort pad2, nexif; struct tiff_tag exif[4]; ushort pad3, ngps; struct tiff_tag gpst[10]; short bps[4]; int rat[10]; unsigned gps[26]; char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64]; }; //@out COMMON void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); } //@end COMMON int CLASS main (int argc, const char **argv) { int arg, status=0, quality, i, c; int timestamp_only=0, thumbnail_only=0, identify_only=0; int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1; int use_fuji_rotate=1, write_to_stdout=0, read_from_stdin=0; const char *sp, *bpfile=0, *dark_frame=0, *write_ext; char opm, opt, *ofname, *cp; struct utimbuf ut; #ifndef NO_LCMS const char *cam_profile=0, *out_profile=0; #endif #ifndef LOCALTIME putenv ((char *) "TZ=UTC"); #endif #ifdef LOCALEDIR setlocale (LC_CTYPE, ""); setlocale (LC_MESSAGES, ""); bindtextdomain ("dcraw", LOCALEDIR); textdomain ("dcraw"); #endif if (argc == 1) { printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION); printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n")); printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]); puts(_("-v Print verbose messages")); puts(_("-c Write image data to standard output")); puts(_("-e Extract embedded thumbnail image")); puts(_("-i Identify files without decoding them")); puts(_("-i -v Identify files and show metadata")); puts(_("-z Change file dates to camera timestamp")); puts(_("-w Use camera white balance, if possible")); puts(_("-a Average the whole image for white balance")); puts(_("-A <x y w h> Average a grey box for white balance")); puts(_("-r <r g b g> Set custom white balance")); puts(_("+M/-M Use/don't use an embedded color matrix")); puts(_("-C <r b> Correct chromatic aberration")); puts(_("-P <file> Fix the dead pixels listed in this file")); puts(_("-K <file> Subtract dark frame (16-bit raw PGM)")); puts(_("-k <num> Set the darkness level")); puts(_("-S <num> Set the saturation level")); puts(_("-n <num> Set threshold for wavelet denoising")); puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)")); puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)")); puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)")); #ifndef NO_LCMS puts(_("-o <file> Apply output ICC profile from file")); puts(_("-p <file> Apply camera ICC profile from file or \"embed\"")); #endif puts(_("-d Document mode (no color, no interpolation)")); puts(_("-D Document mode without scaling (totally raw)")); puts(_("-j Don't stretch or rotate raw pixels")); puts(_("-W Don't automatically brighten the image")); puts(_("-b <num> Adjust brightness (default = 1.0)")); puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)")); puts(_("-q [0-3] Set the interpolation quality")); puts(_("-h Half-size color image (twice as fast as \"-q 0\")")); puts(_("-f Interpolate RGGB as four colors")); puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G")); puts(_("-s [0..N-1] Select one raw image or \"all\" from each file")); puts(_("-6 Write 16-bit instead of 8-bit")); puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\"")); puts(_("-T Write TIFF instead of PPM")); puts(""); return 1; } argv[argc] = ""; for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) { opt = argv[arg++][1]; if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt))) for (i=0; i < "114111111422"[cp-sp]-'0'; i++) if (!isdigit(argv[arg+i][0])) { fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt); return 1; } switch (opt) { case 'n': threshold = atof(argv[arg++]); break; case 'b': bright = atof(argv[arg++]); break; case 'r': FORC4 user_mul[c] = atof(argv[arg++]); break; case 'C': aber[0] = 1 / atof(argv[arg++]); aber[2] = 1 / atof(argv[arg++]); break; case 'g': gamm[0] = atof(argv[arg++]); gamm[1] = atof(argv[arg++]); if (gamm[0]) gamm[0] = 1/gamm[0]; break; case 'k': user_black = atoi(argv[arg++]); break; case 'S': user_sat = atoi(argv[arg++]); break; case 't': user_flip = atoi(argv[arg++]); break; case 'q': user_qual = atoi(argv[arg++]); break; case 'm': med_passes = atoi(argv[arg++]); break; case 'H': highlight = atoi(argv[arg++]); break; case 's': shot_select = abs(atoi(argv[arg])); multi_out = !strcmp(argv[arg++],"all"); break; case 'o': if (isdigit(argv[arg][0]) && !argv[arg][1]) output_color = atoi(argv[arg++]); #ifndef NO_LCMS else out_profile = argv[arg++]; break; case 'p': cam_profile = argv[arg++]; #endif break; case 'P': bpfile = argv[arg++]; break; case 'K': dark_frame = argv[arg++]; break; case 'z': timestamp_only = 1; break; case 'e': thumbnail_only = 1; break; case 'i': identify_only = 1; break; case 'c': write_to_stdout = 1; break; case 'v': verbose = 1; break; case 'h': half_size = 1; break; case 'f': four_color_rgb = 1; break; case 'A': FORC4 greybox[c] = atoi(argv[arg++]); case 'a': use_auto_wb = 1; break; case 'w': use_camera_wb = 1; break; case 'M': use_camera_matrix = 3 * (opm == '+'); break; case 'I': read_from_stdin = 1; break; case 'E': document_mode++; case 'D': document_mode++; case 'd': document_mode++; case 'j': use_fuji_rotate = 0; break; case 'W': no_auto_bright = 1; break; case 'T': output_tiff = 1; break; case '4': gamm[0] = gamm[1] = no_auto_bright = 1; case '6': output_bps = 16; break; default: fprintf (stderr,_("Unknown option \"-%c\".\n"), opt); return 1; } } if (arg == argc) { fprintf (stderr,_("No files to process.\n")); return 1; } if (write_to_stdout) { if (isatty(1)) { fprintf (stderr,_("Will not write an image to the terminal!\n")); return 1; } #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) if (setmode(1,O_BINARY) < 0) { perror ("setmode()"); return 1; } #endif } for ( ; arg < argc; arg++) { status = 1; raw_image = 0; image = 0; oprof = 0; meta_data = ofname = 0; ofp = stdout; if (setjmp (failure)) { if (fileno(ifp) > 2) fclose(ifp); if (fileno(ofp) > 2) fclose(ofp); status = 1; goto cleanup; } ifname = argv[arg]; if (!(ifp = fopen (ifname, "rb"))) { perror (ifname); continue; } status = (identify(),!is_raw); if (user_flip >= 0) flip = user_flip; switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; } if (timestamp_only) { if ((status = !timestamp)) fprintf (stderr,_("%s has no timestamp.\n"), ifname); else if (identify_only) printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname); else { if (verbose) fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp); ut.actime = ut.modtime = timestamp; utime (ifname, &ut); } goto next; } write_fun = &CLASS write_ppm_tiff; if (thumbnail_only) { if ((status = !thumb_offset)) { fprintf (stderr,_("%s has no thumbnail.\n"), ifname); goto next; } else if (thumb_load_raw) { load_raw = thumb_load_raw; data_offset = thumb_offset; height = thumb_height; width = thumb_width; filters = 0; colors = 3; } else { fseek (ifp, thumb_offset, SEEK_SET); write_fun = write_thumb; goto thumbnail; } } if (load_raw == &CLASS kodak_ycbcr_load_raw) { height += height & 1; width += width & 1; } if (identify_only && verbose && make[0]) { printf (_("\nFilename: %s\n"), ifname); printf (_("Timestamp: %s"), ctime(&timestamp)); printf (_("Camera: %s %s\n"), make, model); if (artist[0]) printf (_("Owner: %s\n"), artist); if (dng_version) { printf (_("DNG Version: ")); for (i=24; i >= 0; i -= 8) printf ("%d%c", dng_version >> i & 255, i ? '.':'\n'); } printf (_("ISO speed: %d\n"), (int) iso_speed); printf (_("Shutter: ")); if (shutter > 0 && shutter < 1) shutter = (printf ("1/"), 1 / shutter); printf (_("%0.1f sec\n"), shutter); printf (_("Aperture: f/%0.1f\n"), aperture); printf (_("Focal length: %0.1f mm\n"), focal_len); printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no")); printf (_("Number of raw images: %d\n"), is_raw); if (pixel_aspect != 1) printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect); if (thumb_offset) printf (_("Thumb size: %4d x %d\n"), thumb_width, thumb_height); printf (_("Full size: %4d x %d\n"), raw_width, raw_height); } else if (!is_raw) fprintf (stderr,_("Cannot decode file %s\n"), ifname); if (!is_raw) goto next; shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1))); iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (identify_only) { if (verbose) { if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (use_fuji_rotate) { if (fuji_width) { fuji_width = (fuji_width - 1 + shrink) >> shrink; iwidth = fuji_width / sqrt(0.5); iheight = (iheight - fuji_width) / sqrt(0.5); } else { if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5; if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5; } } if (flip & 4) SWAP(iheight,iwidth); printf (_("Image size: %4d x %d\n"), width, height); printf (_("Output size: %4d x %d\n"), iwidth, iheight); printf (_("Raw colors: %d"), colors); if (filters) { int fhigh = 2, fwide = 2; if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4; if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8; if (filters == 1) fhigh = fwide = 16; if (filters == 9) fhigh = fwide = 6; printf (_("\nFilter pattern: ")); for (i=0; i < fhigh; i++) for (c = i && putchar('/') && 0; c < fwide; c++) putchar (cdesc[fcol(i,c)]); } printf (_("\nDaylight multipliers:")); FORCC printf (" %f", pre_mul[c]); if (cam_mul[0] > 0) { printf (_("\nCamera multipliers:")); FORC4 printf (" %f", cam_mul[c]); } putchar ('\n'); } else printf (_("%s is a %s %s image.\n"), ifname, make, model); next: fclose(ifp); continue; } if (meta_length) { meta_data = (char *) malloc (meta_length); merror (meta_data, "main()"); } if (filters || colors == 1) { raw_image = (ushort *) calloc ((raw_height+7), raw_width*2); merror (raw_image, "main()"); } else { image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image); merror (image, "main()"); } if (verbose) fprintf (stderr,_("Loading %s %s image from %s ...\n"), make, model, ifname); if (shot_select >= is_raw) fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select); fseeko (ifp, data_offset, SEEK_SET); if (raw_image && read_from_stdin) fread (raw_image, 2, raw_height*raw_width, stdin); else (*load_raw)(); if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (raw_image) { image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image); merror (image, "main()"); crop_masked_pixels(); free (raw_image); } if (zero_is_bad) remove_zeroes(); bad_pixels (bpfile); if (dark_frame) subtract (dark_frame); quality = 2 + !fuji_width; if (user_qual >= 0) quality = user_qual; i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; i = cblack[6]; FORC (cblack[4] * cblack[5]) if (i > cblack[6+c]) i = cblack[6+c]; FORC (cblack[4] * cblack[5]) cblack[6+c] -= i; black += i; if (user_black >= 0) black = user_black; FORC4 cblack[c] += black; if (user_sat > 0) maximum = user_sat; #ifdef COLORCHECK colorcheck(); #endif if (is_foveon) { if (document_mode || load_raw == &CLASS foveon_dp_load_raw) { for (i=0; i < height*width*4; i++) if ((short) image[0][i] < 0) image[0][i] = 0; } else foveon_interpolate(); } else if (document_mode < 2) scale_colors(); pre_interpolate(); if (filters && !document_mode) { if (quality == 0) lin_interpolate(); else if (quality == 1 || colors > 3) vng_interpolate(); else if (quality == 2 && filters > 1000) ppg_interpolate(); else if (filters == 9) xtrans_interpolate (quality*2-3); else ahd_interpolate(); } if (mix_green) for (colors=3, i=0; i < height*width; i++) image[i][1] = (image[i][1] + image[i][3]) >> 1; if (!is_foveon && colors == 3) median_filter(); if (!is_foveon && highlight == 2) blend_highlights(); if (!is_foveon && highlight > 2) recover_highlights(); if (use_fuji_rotate) fuji_rotate(); #ifndef NO_LCMS if (cam_profile) apply_profile (cam_profile, out_profile); #endif convert_to_rgb(); if (use_fuji_rotate) stretch(); thumbnail: if (write_fun == &CLASS jpeg_thumb) write_ext = ".jpg"; else if (output_tiff && write_fun == &CLASS write_ppm_tiff) write_ext = ".tiff"; else write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5; ofname = (char *) malloc (strlen(ifname) + 64); merror (ofname, "main()"); if (write_to_stdout) strcpy (ofname,_("standard output")); else { strcpy (ofname, ifname); if ((cp = strrchr (ofname, '.'))) *cp = 0; if (multi_out) sprintf (ofname+strlen(ofname), "_%0*d", snprintf(0,0,"%d",is_raw-1), shot_select); if (thumbnail_only) strcat (ofname, ".thumb"); strcat (ofname, write_ext); ofp = fopen (ofname, "wb"); if (!ofp) { status = 1; perror (ofname); goto cleanup; } } if (verbose) fprintf (stderr,_("Writing data to %s ...\n"), ofname); (*write_fun)(); fclose(ifp); if (ofp != stdout) fclose(ofp); cleanup: if (meta_data) free (meta_data); if (ofname) free (ofname); if (oprof) free (oprof); if (image) free (image); if (multi_out) { if (++shot_select < is_raw) arg--; else shot_select = 0; } } return status; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_580_0
crossvul-cpp_data_good_5215_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % 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 "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriatally. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; register ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1 << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if( SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if( (IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); (void) InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClutImage) #endif proceed=SetImageProgress(image,ClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorDecisionListImageChannel) #endif proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastImage) #endif proceed=SetImageProgress(image,ContrastImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black)); white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); 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 == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastStretchImage) #endif proceed=SetImageProgress(image,ContrastStretchImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(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 *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ 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); enhance_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(enhance_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); continue; } GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); SetPixelViaPixelInfo(image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EnhanceImage) #endif proceed=SetImageProgress(image,EnhanceImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(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 MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); 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 == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaCorrectImageTag "GammaCorrect/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) ResetMagickMemory(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,1.0/gamma))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ #if !defined(MAGICKCORE_HDRI_SUPPORT) if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; #else if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].red,1.0/gamma); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].green,1.0/gamma); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].blue,1.0/gamma); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].alpha,1.0/gamma); #endif } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; #if !defined(MAGICKCORE_HDRI_SUPPORT) q[j]=gamma_map[ScaleQuantumToMap(q[j])]; #else q[j]=QuantumRange*gamma_pow(QuantumScale*q[j],1.0/gamma); #endif } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GammaImage) #endif proceed=SetImageProgress(image,GammaCorrectImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GrayscaleImage) #endif proceed=SetImageProgress(image,GrayscaleImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); pixel2=zero; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); pixel3=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel3); offset+=cube_size; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel4); pixel=zero; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, point.z,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_HaldClutImage) #endif proceed=SetImageProgress(image,HaldClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; if (fabs(white_point-black_point) < MagickEpsilon) return(pixel); scale=1.0/(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), 1.0/gamma); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelImage) #endif proceed=SetImageProgress(image,LevelImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelizeImage) #endif proceed=SetImageProgress(image,LevelizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) ResetMagickMemory(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ModulateImage) #endif proceed=SetImageProgress(image,ModulateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if( grayscale != MagickFalse ) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if ((GetPixelReadMask(image,q) == 0) || IsPixelGray(image,q) != MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImage) #endif proceed=SetImageProgress(image,NegateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImage) #endif proceed=SetImageProgress(image,NegateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(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 MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { register ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SigmoidalContrastImage) #endif proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5215_1
crossvul-cpp_data_bad_3412_1
/********************************************************************* * * Linux multisound pinnacle/fiji driver for ALSA. * * 2002/06/30 Karsten Wiese: * for now this is only used to build a pinnacle / fiji driver. * the OSS parent of this code is designed to also support * the multisound classic via the file msnd_classic.c. * to make it easier for some brave heart to implemt classic * support in alsa, i left all the MSND_CLASSIC tokens in this file. * but for now this untested & undone. * * * ripped from linux kernel 2.4.18 by Karsten Wiese. * * the following is a copy of the 2.4.18 OSS FREE file-heading comment: * * Turtle Beach MultiSound Sound Card Driver for Linux * msnd_pinnacle.c / msnd_classic.c * * -- If MSND_CLASSIC is defined: * * -> driver for Turtle Beach Classic/Monterey/Tahiti * * -- Else * * -> driver for Turtle Beach Pinnacle/Fiji * * 12-3-2000 Modified IO port validation Steve Sycamore * * Copyright (C) 1998 Andrew Veliath * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * ********************************************************************/ #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/firmware.h> #include <linux/isa.h> #include <linux/isapnp.h> #include <linux/irq.h> #include <linux/io.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/asound.h> #include <sound/pcm.h> #include <sound/mpu401.h> #ifdef MSND_CLASSIC # ifndef __alpha__ # define SLOWIO # endif #endif #include "msnd.h" #ifdef MSND_CLASSIC # include "msnd_classic.h" # define LOGNAME "msnd_classic" # define DEV_NAME "msnd-classic" #else # include "msnd_pinnacle.h" # define LOGNAME "snd_msnd_pinnacle" # define DEV_NAME "msnd-pinnacle" #endif static void set_default_audio_parameters(struct snd_msnd *chip) { chip->play_sample_size = DEFSAMPLESIZE; chip->play_sample_rate = DEFSAMPLERATE; chip->play_channels = DEFCHANNELS; chip->capture_sample_size = DEFSAMPLESIZE; chip->capture_sample_rate = DEFSAMPLERATE; chip->capture_channels = DEFCHANNELS; } static void snd_msnd_eval_dsp_msg(struct snd_msnd *chip, u16 wMessage) { switch (HIBYTE(wMessage)) { case HIMT_PLAY_DONE: { if (chip->banksPlayed < 3) snd_printdd("%08X: HIMT_PLAY_DONE: %i\n", (unsigned)jiffies, LOBYTE(wMessage)); if (chip->last_playbank == LOBYTE(wMessage)) { snd_printdd("chip.last_playbank == LOBYTE(wMessage)\n"); break; } chip->banksPlayed++; if (test_bit(F_WRITING, &chip->flags)) snd_msnd_DAPQ(chip, 0); chip->last_playbank = LOBYTE(wMessage); chip->playDMAPos += chip->play_period_bytes; if (chip->playDMAPos > chip->playLimit) chip->playDMAPos = 0; snd_pcm_period_elapsed(chip->playback_substream); break; } case HIMT_RECORD_DONE: if (chip->last_recbank == LOBYTE(wMessage)) break; chip->last_recbank = LOBYTE(wMessage); chip->captureDMAPos += chip->capturePeriodBytes; if (chip->captureDMAPos > (chip->captureLimit)) chip->captureDMAPos = 0; if (test_bit(F_READING, &chip->flags)) snd_msnd_DARQ(chip, chip->last_recbank); snd_pcm_period_elapsed(chip->capture_substream); break; case HIMT_DSP: switch (LOBYTE(wMessage)) { #ifndef MSND_CLASSIC case HIDSP_PLAY_UNDER: #endif case HIDSP_INT_PLAY_UNDER: snd_printd(KERN_WARNING LOGNAME ": Play underflow %i\n", chip->banksPlayed); if (chip->banksPlayed > 2) clear_bit(F_WRITING, &chip->flags); break; case HIDSP_INT_RECORD_OVER: snd_printd(KERN_WARNING LOGNAME ": Record overflow\n"); clear_bit(F_READING, &chip->flags); break; default: snd_printd(KERN_WARNING LOGNAME ": DSP message %d 0x%02x\n", LOBYTE(wMessage), LOBYTE(wMessage)); break; } break; case HIMT_MIDI_IN_UCHAR: if (chip->msndmidi_mpu) snd_msndmidi_input_read(chip->msndmidi_mpu); break; default: snd_printd(KERN_WARNING LOGNAME ": HIMT message %d 0x%02x\n", HIBYTE(wMessage), HIBYTE(wMessage)); break; } } static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ while (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) { u16 wTmp; snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead))); wTmp = readw(chip->DSPQ + JQS_wHead) + 1; if (wTmp > readw(chip->DSPQ + JQS_wSize)) writew(0, chip->DSPQ + JQS_wHead); else writew(wTmp, chip->DSPQ + JQS_wHead); } /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; } static int snd_msnd_reset_dsp(long io, unsigned char *info) { int timeout = 100; outb(HPDSPRESET_ON, io + HP_DSPR); msleep(1); #ifndef MSND_CLASSIC if (info) *info = inb(io + HP_INFO); #endif outb(HPDSPRESET_OFF, io + HP_DSPR); msleep(1); while (timeout-- > 0) { if (inb(io + HP_CVR) == HP_CVR_DEF) return 0; msleep(1); } snd_printk(KERN_ERR LOGNAME ": Cannot reset DSP\n"); return -EIO; } static int snd_msnd_probe(struct snd_card *card) { struct snd_msnd *chip = card->private_data; unsigned char info; #ifndef MSND_CLASSIC char *xv, *rev = NULL; char *pin = "TB Pinnacle", *fiji = "TB Fiji"; char *pinfiji = "TB Pinnacle/Fiji"; #endif if (!request_region(chip->io, DSP_NUMIO, "probing")) { snd_printk(KERN_ERR LOGNAME ": I/O port conflict\n"); return -ENODEV; } if (snd_msnd_reset_dsp(chip->io, &info) < 0) { release_region(chip->io, DSP_NUMIO); return -ENODEV; } #ifdef MSND_CLASSIC strcpy(card->shortname, "Classic/Tahiti/Monterey"); strcpy(card->longname, "Turtle Beach Multisound"); printk(KERN_INFO LOGNAME ": %s, " "I/O 0x%lx-0x%lx, IRQ %d, memory mapped to 0x%lX-0x%lX\n", card->shortname, chip->io, chip->io + DSP_NUMIO - 1, chip->irq, chip->base, chip->base + 0x7fff); #else switch (info >> 4) { case 0xf: xv = "<= 1.15"; break; case 0x1: xv = "1.18/1.2"; break; case 0x2: xv = "1.3"; break; case 0x3: xv = "1.4"; break; default: xv = "unknown"; break; } switch (info & 0x7) { case 0x0: rev = "I"; strcpy(card->shortname, pin); break; case 0x1: rev = "F"; strcpy(card->shortname, pin); break; case 0x2: rev = "G"; strcpy(card->shortname, pin); break; case 0x3: rev = "H"; strcpy(card->shortname, pin); break; case 0x4: rev = "E"; strcpy(card->shortname, fiji); break; case 0x5: rev = "C"; strcpy(card->shortname, fiji); break; case 0x6: rev = "D"; strcpy(card->shortname, fiji); break; case 0x7: rev = "A-B (Fiji) or A-E (Pinnacle)"; strcpy(card->shortname, pinfiji); break; } strcpy(card->longname, "Turtle Beach Multisound Pinnacle"); printk(KERN_INFO LOGNAME ": %s revision %s, Xilinx version %s, " "I/O 0x%lx-0x%lx, IRQ %d, memory mapped to 0x%lX-0x%lX\n", card->shortname, rev, xv, chip->io, chip->io + DSP_NUMIO - 1, chip->irq, chip->base, chip->base + 0x7fff); #endif release_region(chip->io, DSP_NUMIO); return 0; } static int snd_msnd_init_sma(struct snd_msnd *chip) { static int initted; u16 mastVolLeft, mastVolRight; unsigned long flags; #ifdef MSND_CLASSIC outb(chip->memid, chip->io + HP_MEMM); #endif outb(HPBLKSEL_0, chip->io + HP_BLKS); /* Motorola 56k shared memory base */ chip->SMA = chip->mappedbase + SMA_STRUCT_START; if (initted) { mastVolLeft = readw(chip->SMA + SMA_wCurrMastVolLeft); mastVolRight = readw(chip->SMA + SMA_wCurrMastVolRight); } else mastVolLeft = mastVolRight = 0; memset_io(chip->mappedbase, 0, 0x8000); /* Critical section: bank 1 access */ spin_lock_irqsave(&chip->lock, flags); outb(HPBLKSEL_1, chip->io + HP_BLKS); memset_io(chip->mappedbase, 0, 0x8000); outb(HPBLKSEL_0, chip->io + HP_BLKS); spin_unlock_irqrestore(&chip->lock, flags); /* Digital audio play queue */ chip->DAPQ = chip->mappedbase + DAPQ_OFFSET; snd_msnd_init_queue(chip->DAPQ, DAPQ_DATA_BUFF, DAPQ_BUFF_SIZE); /* Digital audio record queue */ chip->DARQ = chip->mappedbase + DARQ_OFFSET; snd_msnd_init_queue(chip->DARQ, DARQ_DATA_BUFF, DARQ_BUFF_SIZE); /* MIDI out queue */ chip->MODQ = chip->mappedbase + MODQ_OFFSET; snd_msnd_init_queue(chip->MODQ, MODQ_DATA_BUFF, MODQ_BUFF_SIZE); /* MIDI in queue */ chip->MIDQ = chip->mappedbase + MIDQ_OFFSET; snd_msnd_init_queue(chip->MIDQ, MIDQ_DATA_BUFF, MIDQ_BUFF_SIZE); /* DSP -> host message queue */ chip->DSPQ = chip->mappedbase + DSPQ_OFFSET; snd_msnd_init_queue(chip->DSPQ, DSPQ_DATA_BUFF, DSPQ_BUFF_SIZE); /* Setup some DSP values */ #ifndef MSND_CLASSIC writew(1, chip->SMA + SMA_wCurrPlayFormat); writew(chip->play_sample_size, chip->SMA + SMA_wCurrPlaySampleSize); writew(chip->play_channels, chip->SMA + SMA_wCurrPlayChannels); writew(chip->play_sample_rate, chip->SMA + SMA_wCurrPlaySampleRate); #endif writew(chip->play_sample_rate, chip->SMA + SMA_wCalFreqAtoD); writew(mastVolLeft, chip->SMA + SMA_wCurrMastVolLeft); writew(mastVolRight, chip->SMA + SMA_wCurrMastVolRight); #ifndef MSND_CLASSIC writel(0x00010000, chip->SMA + SMA_dwCurrPlayPitch); writel(0x00000001, chip->SMA + SMA_dwCurrPlayRate); #endif writew(0x303, chip->SMA + SMA_wCurrInputTagBits); initted = 1; return 0; } static int upload_dsp_code(struct snd_card *card) { struct snd_msnd *chip = card->private_data; const struct firmware *init_fw = NULL, *perm_fw = NULL; int err; outb(HPBLKSEL_0, chip->io + HP_BLKS); err = request_firmware(&init_fw, INITCODEFILE, card->dev); if (err < 0) { printk(KERN_ERR LOGNAME ": Error loading " INITCODEFILE); goto cleanup1; } err = request_firmware(&perm_fw, PERMCODEFILE, card->dev); if (err < 0) { printk(KERN_ERR LOGNAME ": Error loading " PERMCODEFILE); goto cleanup; } memcpy_toio(chip->mappedbase, perm_fw->data, perm_fw->size); if (snd_msnd_upload_host(chip, init_fw->data, init_fw->size) < 0) { printk(KERN_WARNING LOGNAME ": Error uploading to DSP\n"); err = -ENODEV; goto cleanup; } printk(KERN_INFO LOGNAME ": DSP firmware uploaded\n"); err = 0; cleanup: release_firmware(perm_fw); cleanup1: release_firmware(init_fw); return err; } #ifdef MSND_CLASSIC static void reset_proteus(struct snd_msnd *chip) { outb(HPPRORESET_ON, chip->io + HP_PROR); msleep(TIME_PRO_RESET); outb(HPPRORESET_OFF, chip->io + HP_PROR); msleep(TIME_PRO_RESET_DONE); } #endif static int snd_msnd_initialize(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int err, timeout; #ifdef MSND_CLASSIC outb(HPWAITSTATE_0, chip->io + HP_WAIT); outb(HPBITMODE_16, chip->io + HP_BITM); reset_proteus(chip); #endif err = snd_msnd_init_sma(chip); if (err < 0) { printk(KERN_WARNING LOGNAME ": Cannot initialize SMA\n"); return err; } err = snd_msnd_reset_dsp(chip->io, NULL); if (err < 0) return err; err = upload_dsp_code(card); if (err < 0) { printk(KERN_WARNING LOGNAME ": Cannot upload DSP code\n"); return err; } timeout = 200; while (readw(chip->mappedbase)) { msleep(1); if (!timeout--) { snd_printd(KERN_ERR LOGNAME ": DSP reset timeout\n"); return -EIO; } } snd_msndmix_setup(chip); return 0; } static int snd_msnd_dsp_full_reset(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int rv; if (test_bit(F_RESETTING, &chip->flags) || ++chip->nresets > 10) return 0; set_bit(F_RESETTING, &chip->flags); snd_msnd_dsp_halt(chip, NULL); /* Unconditionally halt */ rv = snd_msnd_initialize(card); if (rv) printk(KERN_WARNING LOGNAME ": DSP reset failed\n"); snd_msndmix_force_recsrc(chip, 0); clear_bit(F_RESETTING, &chip->flags); return rv; } static int snd_msnd_dev_free(struct snd_device *device) { snd_printdd("snd_msnd_chip_free()\n"); return 0; } static int snd_msnd_send_dsp_cmd_chk(struct snd_msnd *chip, u8 cmd) { if (snd_msnd_send_dsp_cmd(chip, cmd) == 0) return 0; snd_msnd_dsp_full_reset(chip->card); return snd_msnd_send_dsp_cmd(chip, cmd); } static int snd_msnd_calibrate_adc(struct snd_msnd *chip, u16 srate) { snd_printdd("snd_msnd_calibrate_adc(%i)\n", srate); writew(srate, chip->SMA + SMA_wCalFreqAtoD); if (chip->calibrate_signal == 0) writew(readw(chip->SMA + SMA_wCurrHostStatusFlags) | 0x0001, chip->SMA + SMA_wCurrHostStatusFlags); else writew(readw(chip->SMA + SMA_wCurrHostStatusFlags) & ~0x0001, chip->SMA + SMA_wCurrHostStatusFlags); if (snd_msnd_send_word(chip, 0, 0, HDEXAR_CAL_A_TO_D) == 0 && snd_msnd_send_dsp_cmd_chk(chip, HDEX_AUX_REQ) == 0) { schedule_timeout_interruptible(msecs_to_jiffies(333)); return 0; } printk(KERN_WARNING LOGNAME ": ADC calibration failed\n"); return -EIO; } /* * ALSA callback function, called when attempting to open the MIDI device. */ static int snd_msnd_mpu401_open(struct snd_mpu401 *mpu) { snd_msnd_enable_irq(mpu->private_data); snd_msnd_send_dsp_cmd(mpu->private_data, HDEX_MIDI_IN_START); return 0; } static void snd_msnd_mpu401_close(struct snd_mpu401 *mpu) { snd_msnd_send_dsp_cmd(mpu->private_data, HDEX_MIDI_IN_STOP); snd_msnd_disable_irq(mpu->private_data); } static long mpu_io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static int snd_msnd_attach(struct snd_card *card) { struct snd_msnd *chip = card->private_data; int err; static struct snd_device_ops ops = { .dev_free = snd_msnd_dev_free, }; err = request_irq(chip->irq, snd_msnd_interrupt, 0, card->shortname, chip); if (err < 0) { printk(KERN_ERR LOGNAME ": Couldn't grab IRQ %d\n", chip->irq); return err; } if (request_region(chip->io, DSP_NUMIO, card->shortname) == NULL) { free_irq(chip->irq, chip); return -EBUSY; } if (!request_mem_region(chip->base, BUFFSIZE, card->shortname)) { printk(KERN_ERR LOGNAME ": unable to grab memory region 0x%lx-0x%lx\n", chip->base, chip->base + BUFFSIZE - 1); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); return -EBUSY; } chip->mappedbase = ioremap_nocache(chip->base, 0x8000); if (!chip->mappedbase) { printk(KERN_ERR LOGNAME ": unable to map memory region 0x%lx-0x%lx\n", chip->base, chip->base + BUFFSIZE - 1); err = -EIO; goto err_release_region; } err = snd_msnd_dsp_full_reset(card); if (err < 0) goto err_release_region; /* Register device */ err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops); if (err < 0) goto err_release_region; err = snd_msnd_pcm(card, 0); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new PCM device\n"); goto err_release_region; } err = snd_msndmix_new(card); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new Mixer device\n"); goto err_release_region; } if (mpu_io[0] != SNDRV_AUTO_PORT) { struct snd_mpu401 *mpu; err = snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, mpu_io[0], MPU401_MODE_INPUT | MPU401_MODE_OUTPUT, mpu_irq[0], &chip->rmidi); if (err < 0) { printk(KERN_ERR LOGNAME ": error creating new Midi device\n"); goto err_release_region; } mpu = chip->rmidi->private_data; mpu->open_input = snd_msnd_mpu401_open; mpu->close_input = snd_msnd_mpu401_close; mpu->private_data = chip; } disable_irq(chip->irq); snd_msnd_calibrate_adc(chip, chip->play_sample_rate); snd_msndmix_force_recsrc(chip, 0); err = snd_card_register(card); if (err < 0) goto err_release_region; return 0; err_release_region: iounmap(chip->mappedbase); release_mem_region(chip->base, BUFFSIZE); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); return err; } static void snd_msnd_unload(struct snd_card *card) { struct snd_msnd *chip = card->private_data; iounmap(chip->mappedbase); release_mem_region(chip->base, BUFFSIZE); release_region(chip->io, DSP_NUMIO); free_irq(chip->irq, chip); snd_card_free(card); } #ifndef MSND_CLASSIC /* Pinnacle/Fiji Logical Device Configuration */ static int snd_msnd_write_cfg(int cfg, int reg, int value) { outb(reg, cfg); outb(value, cfg + 1); if (value != inb(cfg + 1)) { printk(KERN_ERR LOGNAME ": snd_msnd_write_cfg: I/O error\n"); return -EIO; } return 0; } static int snd_msnd_write_cfg_io0(int cfg, int num, u16 io) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO0_BASEHI, HIBYTE(io))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO0_BASELO, LOBYTE(io))) return -EIO; return 0; } static int snd_msnd_write_cfg_io1(int cfg, int num, u16 io) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO1_BASEHI, HIBYTE(io))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IO1_BASELO, LOBYTE(io))) return -EIO; return 0; } static int snd_msnd_write_cfg_irq(int cfg, int num, u16 irq) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_NUMBER, LOBYTE(irq))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_TYPE, IRQTYPE_EDGE)) return -EIO; return 0; } static int snd_msnd_write_cfg_mem(int cfg, int num, int mem) { u16 wmem; mem >>= 8; wmem = (u16)(mem & 0xfff); if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_MEMBASEHI, HIBYTE(wmem))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_MEMBASELO, LOBYTE(wmem))) return -EIO; if (wmem && snd_msnd_write_cfg(cfg, IREG_MEMCONTROL, MEMTYPE_HIADDR | MEMTYPE_16BIT)) return -EIO; return 0; } static int snd_msnd_activate_logical(int cfg, int num) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_ACTIVATE, LD_ACTIVATE)) return -EIO; return 0; } static int snd_msnd_write_cfg_logical(int cfg, int num, u16 io0, u16 io1, u16 irq, int mem) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg_io0(cfg, num, io0)) return -EIO; if (snd_msnd_write_cfg_io1(cfg, num, io1)) return -EIO; if (snd_msnd_write_cfg_irq(cfg, num, irq)) return -EIO; if (snd_msnd_write_cfg_mem(cfg, num, mem)) return -EIO; if (snd_msnd_activate_logical(cfg, num)) return -EIO; return 0; } static int snd_msnd_pinnacle_cfg_reset(int cfg) { int i; /* Reset devices if told to */ printk(KERN_INFO LOGNAME ": Resetting all devices\n"); for (i = 0; i < 4; ++i) if (snd_msnd_write_cfg_logical(cfg, i, 0, 0, 0, 0)) return -EIO; return 0; } #endif static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ module_param_array(index, int, NULL, S_IRUGO); MODULE_PARM_DESC(index, "Index value for msnd_pinnacle soundcard."); module_param_array(id, charp, NULL, S_IRUGO); MODULE_PARM_DESC(id, "ID string for msnd_pinnacle soundcard."); static long io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static long mem[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; #ifndef MSND_CLASSIC static long cfg[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* Extra Peripheral Configuration (Default: Disable) */ static long ide_io0[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static long ide_io1[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; static int ide_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; static long joystick_io[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* If we have the digital daugherboard... */ static int digital[SNDRV_CARDS]; /* Extra Peripheral Configuration */ static int reset[SNDRV_CARDS]; #endif static int write_ndelay[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = 1 }; static int calibrate_signal; #ifdef CONFIG_PNP static bool isapnp[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(isapnp, bool, NULL, 0444); MODULE_PARM_DESC(isapnp, "ISA PnP detection for specified soundcard."); #define has_isapnp(x) isapnp[x] #else #define has_isapnp(x) 0 #endif MODULE_AUTHOR("Karsten Wiese <annabellesgarden@yahoo.de>"); MODULE_DESCRIPTION("Turtle Beach " LONGNAME " Linux Driver"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(INITCODEFILE); MODULE_FIRMWARE(PERMCODEFILE); module_param_hw_array(io, long, ioport, NULL, S_IRUGO); MODULE_PARM_DESC(io, "IO port #"); module_param_hw_array(irq, int, irq, NULL, S_IRUGO); module_param_hw_array(mem, long, iomem, NULL, S_IRUGO); module_param_array(write_ndelay, int, NULL, S_IRUGO); module_param(calibrate_signal, int, S_IRUGO); #ifndef MSND_CLASSIC module_param_array(digital, int, NULL, S_IRUGO); module_param_hw_array(cfg, long, ioport, NULL, S_IRUGO); module_param_array(reset, int, 0, S_IRUGO); module_param_hw_array(mpu_io, long, ioport, NULL, S_IRUGO); module_param_hw_array(mpu_irq, int, irq, NULL, S_IRUGO); module_param_hw_array(ide_io0, long, ioport, NULL, S_IRUGO); module_param_hw_array(ide_io1, long, ioport, NULL, S_IRUGO); module_param_hw_array(ide_irq, int, irq, NULL, S_IRUGO); module_param_hw_array(joystick_io, long, ioport, NULL, S_IRUGO); #endif static int snd_msnd_isa_match(struct device *pdev, unsigned int i) { if (io[i] == SNDRV_AUTO_PORT) return 0; if (irq[i] == SNDRV_AUTO_PORT || mem[i] == SNDRV_AUTO_PORT) { printk(KERN_WARNING LOGNAME ": io, irq and mem must be set\n"); return 0; } #ifdef MSND_CLASSIC if (!(io[i] == 0x290 || io[i] == 0x260 || io[i] == 0x250 || io[i] == 0x240 || io[i] == 0x230 || io[i] == 0x220 || io[i] == 0x210 || io[i] == 0x3e0)) { printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must be set " " to 0x210, 0x220, 0x230, 0x240, 0x250, 0x260, 0x290, " "or 0x3E0\n"); return 0; } #else if (io[i] < 0x100 || io[i] > 0x3e0 || (io[i] % 0x10) != 0) { printk(KERN_ERR LOGNAME ": \"io\" - DSP I/O base must within the range 0x100 " "to 0x3E0 and must be evenly divisible by 0x10\n"); return 0; } #endif /* MSND_CLASSIC */ if (!(irq[i] == 5 || irq[i] == 7 || irq[i] == 9 || irq[i] == 10 || irq[i] == 11 || irq[i] == 12)) { printk(KERN_ERR LOGNAME ": \"irq\" - must be set to 5, 7, 9, 10, 11 or 12\n"); return 0; } if (!(mem[i] == 0xb0000 || mem[i] == 0xc8000 || mem[i] == 0xd0000 || mem[i] == 0xd8000 || mem[i] == 0xe0000 || mem[i] == 0xe8000)) { printk(KERN_ERR LOGNAME ": \"mem\" - must be set to " "0xb0000, 0xc8000, 0xd0000, 0xd8000, 0xe0000 or " "0xe8000\n"); return 0; } #ifndef MSND_CLASSIC if (cfg[i] == SNDRV_AUTO_PORT) { printk(KERN_INFO LOGNAME ": Assuming PnP mode\n"); } else if (cfg[i] != 0x250 && cfg[i] != 0x260 && cfg[i] != 0x270) { printk(KERN_INFO LOGNAME ": Config port must be 0x250, 0x260 or 0x270 " "(or unspecified for PnP mode)\n"); return 0; } #endif /* MSND_CLASSIC */ return 1; } static int snd_msnd_isa_probe(struct device *pdev, unsigned int idx) { int err; struct snd_card *card; struct snd_msnd *chip; if (has_isapnp(idx) #ifndef MSND_CLASSIC || cfg[idx] == SNDRV_AUTO_PORT #endif ) { printk(KERN_INFO LOGNAME ": Assuming PnP mode\n"); return -ENODEV; } err = snd_card_new(pdev, index[idx], id[idx], THIS_MODULE, sizeof(struct snd_msnd), &card); if (err < 0) return err; chip = card->private_data; chip->card = card; #ifdef MSND_CLASSIC switch (irq[idx]) { case 5: chip->irqid = HPIRQ_5; break; case 7: chip->irqid = HPIRQ_7; break; case 9: chip->irqid = HPIRQ_9; break; case 10: chip->irqid = HPIRQ_10; break; case 11: chip->irqid = HPIRQ_11; break; case 12: chip->irqid = HPIRQ_12; break; } switch (mem[idx]) { case 0xb0000: chip->memid = HPMEM_B000; break; case 0xc8000: chip->memid = HPMEM_C800; break; case 0xd0000: chip->memid = HPMEM_D000; break; case 0xd8000: chip->memid = HPMEM_D800; break; case 0xe0000: chip->memid = HPMEM_E000; break; case 0xe8000: chip->memid = HPMEM_E800; break; } #else printk(KERN_INFO LOGNAME ": Non-PnP mode: configuring at port 0x%lx\n", cfg[idx]); if (!request_region(cfg[idx], 2, "Pinnacle/Fiji Config")) { printk(KERN_ERR LOGNAME ": Config port 0x%lx conflict\n", cfg[idx]); snd_card_free(card); return -EIO; } if (reset[idx]) if (snd_msnd_pinnacle_cfg_reset(cfg[idx])) { err = -EIO; goto cfg_error; } /* DSP */ err = snd_msnd_write_cfg_logical(cfg[idx], 0, io[idx], 0, irq[idx], mem[idx]); if (err) goto cfg_error; /* The following are Pinnacle specific */ /* MPU */ if (mpu_io[idx] != SNDRV_AUTO_PORT && mpu_irq[idx] != SNDRV_AUTO_IRQ) { printk(KERN_INFO LOGNAME ": Configuring MPU to I/O 0x%lx IRQ %d\n", mpu_io[idx], mpu_irq[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 1, mpu_io[idx], 0, mpu_irq[idx], 0); if (err) goto cfg_error; } /* IDE */ if (ide_io0[idx] != SNDRV_AUTO_PORT && ide_io1[idx] != SNDRV_AUTO_PORT && ide_irq[idx] != SNDRV_AUTO_IRQ) { printk(KERN_INFO LOGNAME ": Configuring IDE to I/O 0x%lx, 0x%lx IRQ %d\n", ide_io0[idx], ide_io1[idx], ide_irq[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 2, ide_io0[idx], ide_io1[idx], ide_irq[idx], 0); if (err) goto cfg_error; } /* Joystick */ if (joystick_io[idx] != SNDRV_AUTO_PORT) { printk(KERN_INFO LOGNAME ": Configuring joystick to I/O 0x%lx\n", joystick_io[idx]); err = snd_msnd_write_cfg_logical(cfg[idx], 3, joystick_io[idx], 0, 0, 0); if (err) goto cfg_error; } release_region(cfg[idx], 2); #endif /* MSND_CLASSIC */ set_default_audio_parameters(chip); #ifdef MSND_CLASSIC chip->type = msndClassic; #else chip->type = msndPinnacle; #endif chip->io = io[idx]; chip->irq = irq[idx]; chip->base = mem[idx]; chip->calibrate_signal = calibrate_signal ? 1 : 0; chip->recsrc = 0; chip->dspq_data_buff = DSPQ_DATA_BUFF; chip->dspq_buff_size = DSPQ_BUFF_SIZE; if (write_ndelay[idx]) clear_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); else set_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); #ifndef MSND_CLASSIC if (digital[idx]) set_bit(F_HAVEDIGITAL, &chip->flags); #endif spin_lock_init(&chip->lock); err = snd_msnd_probe(card); if (err < 0) { printk(KERN_ERR LOGNAME ": Probe failed\n"); snd_card_free(card); return err; } err = snd_msnd_attach(card); if (err < 0) { printk(KERN_ERR LOGNAME ": Attach failed\n"); snd_card_free(card); return err; } dev_set_drvdata(pdev, card); return 0; #ifndef MSND_CLASSIC cfg_error: release_region(cfg[idx], 2); snd_card_free(card); return err; #endif } static int snd_msnd_isa_remove(struct device *pdev, unsigned int dev) { snd_msnd_unload(dev_get_drvdata(pdev)); return 0; } static struct isa_driver snd_msnd_driver = { .match = snd_msnd_isa_match, .probe = snd_msnd_isa_probe, .remove = snd_msnd_isa_remove, /* FIXME: suspend, resume */ .driver = { .name = DEV_NAME }, }; #ifdef CONFIG_PNP static int snd_msnd_pnp_detect(struct pnp_card_link *pcard, const struct pnp_card_device_id *pid) { static int idx; struct pnp_dev *pnp_dev; struct pnp_dev *mpu_dev; struct snd_card *card; struct snd_msnd *chip; int ret; for ( ; idx < SNDRV_CARDS; idx++) { if (has_isapnp(idx)) break; } if (idx >= SNDRV_CARDS) return -ENODEV; /* * Check that we still have room for another sound card ... */ pnp_dev = pnp_request_card_device(pcard, pid->devs[0].id, NULL); if (!pnp_dev) return -ENODEV; mpu_dev = pnp_request_card_device(pcard, pid->devs[1].id, NULL); if (!mpu_dev) return -ENODEV; if (!pnp_is_active(pnp_dev) && pnp_activate_dev(pnp_dev) < 0) { printk(KERN_INFO "msnd_pinnacle: device is inactive\n"); return -EBUSY; } if (!pnp_is_active(mpu_dev) && pnp_activate_dev(mpu_dev) < 0) { printk(KERN_INFO "msnd_pinnacle: MPU device is inactive\n"); return -EBUSY; } /* * Create a new ALSA sound card entry, in anticipation * of detecting our hardware ... */ ret = snd_card_new(&pcard->card->dev, index[idx], id[idx], THIS_MODULE, sizeof(struct snd_msnd), &card); if (ret < 0) return ret; chip = card->private_data; chip->card = card; /* * Read the correct parameters off the ISA PnP bus ... */ io[idx] = pnp_port_start(pnp_dev, 0); irq[idx] = pnp_irq(pnp_dev, 0); mem[idx] = pnp_mem_start(pnp_dev, 0); mpu_io[idx] = pnp_port_start(mpu_dev, 0); mpu_irq[idx] = pnp_irq(mpu_dev, 0); set_default_audio_parameters(chip); #ifdef MSND_CLASSIC chip->type = msndClassic; #else chip->type = msndPinnacle; #endif chip->io = io[idx]; chip->irq = irq[idx]; chip->base = mem[idx]; chip->calibrate_signal = calibrate_signal ? 1 : 0; chip->recsrc = 0; chip->dspq_data_buff = DSPQ_DATA_BUFF; chip->dspq_buff_size = DSPQ_BUFF_SIZE; if (write_ndelay[idx]) clear_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); else set_bit(F_DISABLE_WRITE_NDELAY, &chip->flags); #ifndef MSND_CLASSIC if (digital[idx]) set_bit(F_HAVEDIGITAL, &chip->flags); #endif spin_lock_init(&chip->lock); ret = snd_msnd_probe(card); if (ret < 0) { printk(KERN_ERR LOGNAME ": Probe failed\n"); goto _release_card; } ret = snd_msnd_attach(card); if (ret < 0) { printk(KERN_ERR LOGNAME ": Attach failed\n"); goto _release_card; } pnp_set_card_drvdata(pcard, card); ++idx; return 0; _release_card: snd_card_free(card); return ret; } static void snd_msnd_pnp_remove(struct pnp_card_link *pcard) { snd_msnd_unload(pnp_get_card_drvdata(pcard)); pnp_set_card_drvdata(pcard, NULL); } static int isa_registered; static int pnp_registered; static struct pnp_card_device_id msnd_pnpids[] = { /* Pinnacle PnP */ { .id = "BVJ0440", .devs = { { "TBS0000" }, { "TBS0001" } } }, { .id = "" } /* end */ }; MODULE_DEVICE_TABLE(pnp_card, msnd_pnpids); static struct pnp_card_driver msnd_pnpc_driver = { .flags = PNP_DRIVER_RES_DO_NOT_CHANGE, .name = "msnd_pinnacle", .id_table = msnd_pnpids, .probe = snd_msnd_pnp_detect, .remove = snd_msnd_pnp_remove, }; #endif /* CONFIG_PNP */ static int __init snd_msnd_init(void) { int err; err = isa_register_driver(&snd_msnd_driver, SNDRV_CARDS); #ifdef CONFIG_PNP if (!err) isa_registered = 1; err = pnp_register_card_driver(&msnd_pnpc_driver); if (!err) pnp_registered = 1; if (isa_registered) err = 0; #endif return err; } static void __exit snd_msnd_exit(void) { #ifdef CONFIG_PNP if (pnp_registered) pnp_unregister_card_driver(&msnd_pnpc_driver); if (isa_registered) #endif isa_unregister_driver(&snd_msnd_driver); } module_init(snd_msnd_init); module_exit(snd_msnd_exit);
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3412_1
crossvul-cpp_data_bad_1282_2
#include "Python.h" #include "Python-ast.h" #include "compile.h" #include "node.h" #include "grammar.h" #include "token.h" #include "ast.h" #include "parsetok.h" #include "errcode.h" extern grammar _Ta3Parser_Grammar; /* from graminit.c */ // from Python/bltinmodule.c static const char * source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy) { const char *str; Py_ssize_t size; Py_buffer view; *cmd_copy = NULL; if (PyUnicode_Check(cmd)) { cf->cf_flags |= PyCF_IGNORE_COOKIE; str = PyUnicode_AsUTF8AndSize(cmd, &size); if (str == NULL) return NULL; } else if (PyBytes_Check(cmd)) { str = PyBytes_AS_STRING(cmd); size = PyBytes_GET_SIZE(cmd); } else if (PyByteArray_Check(cmd)) { str = PyByteArray_AS_STRING(cmd); size = PyByteArray_GET_SIZE(cmd); } else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) { /* Copy to NUL-terminated buffer. */ *cmd_copy = PyBytes_FromStringAndSize( (const char *)view.buf, view.len); PyBuffer_Release(&view); if (*cmd_copy == NULL) { return NULL; } str = PyBytes_AS_STRING(*cmd_copy); size = PyBytes_GET_SIZE(*cmd_copy); } else { PyErr_Format(PyExc_TypeError, "%s() arg 1 must be a %s object", funcname, what); return NULL; } if (strlen(str) != (size_t)size) { PyErr_SetString(PyExc_ValueError, "source code string cannot contain null bytes"); Py_CLEAR(*cmd_copy); return NULL; } return str; } // from Python/pythonrun.c /* compute parser flags based on compiler flags */ static int PARSER_FLAGS(PyCompilerFlags *flags) { int parser_flags = 0; if (!flags) return 0; if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; if (flags->cf_flags & PyCF_IGNORE_COOKIE) parser_flags |= PyPARSE_IGNORE_COOKIE; if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) parser_flags |= PyPARSE_BARRY_AS_BDFL; return parser_flags; } // from Python/pythonrun.c /* Set the error appropriate to the given input error code (see errcode.h) */ static void err_input(perrdetail *err) { PyObject *v, *w, *errtype, *errtext; PyObject *msg_obj = NULL; char *msg = NULL; int offset = err->offset; errtype = PyExc_SyntaxError; switch (err->error) { case E_ERROR: return; case E_SYNTAX: errtype = PyExc_IndentationError; if (err->expected == INDENT) msg = "expected an indented block"; else if (err->token == INDENT) msg = "unexpected indent"; else if (err->token == DEDENT) msg = "unexpected unindent"; else { errtype = PyExc_SyntaxError; if (err->token == TYPE_COMMENT) msg = "misplaced type annotation"; else msg = "invalid syntax"; } break; case E_TOKEN: msg = "invalid token"; break; case E_EOFS: msg = "EOF while scanning triple-quoted string literal"; break; case E_EOLS: msg = "EOL while scanning string literal"; break; case E_INTR: if (!PyErr_Occurred()) PyErr_SetNone(PyExc_KeyboardInterrupt); goto cleanup; case E_NOMEM: PyErr_NoMemory(); goto cleanup; case E_EOF: msg = "unexpected EOF while parsing"; break; case E_TABSPACE: errtype = PyExc_TabError; msg = "inconsistent use of tabs and spaces in indentation"; break; case E_OVERFLOW: msg = "expression too long"; break; case E_DEDENT: errtype = PyExc_IndentationError; msg = "unindent does not match any outer indentation level"; break; case E_TOODEEP: errtype = PyExc_IndentationError; msg = "too many levels of indentation"; break; case E_DECODE: { PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); msg = "unknown decode error"; if (value != NULL) msg_obj = PyObject_Str(value); Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); break; } case E_LINECONT: msg = "unexpected character after line continuation character"; break; case E_IDENTIFIER: msg = "invalid character in identifier"; break; case E_BADSINGLE: msg = "multiple statements found while compiling a single statement"; break; default: fprintf(stderr, "error=%d\n", err->error); msg = "unknown parsing error"; break; } /* err->text may not be UTF-8 in case of decoding errors. Explicitly convert to an object. */ if (!err->text) { errtext = Py_None; Py_INCREF(Py_None); } else { errtext = PyUnicode_DecodeUTF8(err->text, err->offset, "replace"); if (errtext != NULL) { Py_ssize_t len = strlen(err->text); offset = (int)PyUnicode_GET_LENGTH(errtext); if (len != err->offset) { Py_DECREF(errtext); errtext = PyUnicode_DecodeUTF8(err->text, len, "replace"); } } } v = Py_BuildValue("(OiiN)", err->filename, err->lineno, offset, errtext); if (v != NULL) { if (msg_obj) w = Py_BuildValue("(OO)", msg_obj, v); else w = Py_BuildValue("(sO)", msg, v); } else w = NULL; Py_XDECREF(v); PyErr_SetObject(errtype, w); Py_XDECREF(w); cleanup: Py_XDECREF(msg_obj); if (err->text != NULL) { PyObject_FREE(err->text); err->text = NULL; } } // from Python/pythonrun.c static void err_free(perrdetail *err) { Py_CLEAR(err->filename); } // copy of PyParser_ASTFromStringObject in Python/pythonrun.c /* Preferred access to parser is through AST. */ mod_ty string_object_to_c_ast(const char *s, PyObject *filename, int start, PyCompilerFlags *flags, int feature_version, PyArena *arena) { mod_ty mod; PyCompilerFlags localflags; perrdetail err; int iflags = PARSER_FLAGS(flags); node *n = Ta3Parser_ParseStringObject(s, filename, &_Ta3Parser_Grammar, start, &err, &iflags); if (flags == NULL) { localflags.cf_flags = 0; flags = &localflags; } if (n) { flags->cf_flags |= iflags & PyCF_MASK; mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena); Ta3Node_Free(n); } else { err_input(&err); mod = NULL; } err_free(&err); return mod; } // adapted from Py_CompileStringObject in Python/pythonrun.c static PyObject * string_object_to_py_ast(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int feature_version) { mod_ty mod; PyObject *result; PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; mod = string_object_to_c_ast(str, filename, start, flags, feature_version, arena); if (mod == NULL) { PyArena_Free(arena); return NULL; } result = Ta3AST_mod2obj(mod); PyArena_Free(arena); return result; } // adapted from builtin_compile_impl in Python/bltinmodule.c static PyObject * ast3_parse_impl(PyObject *source, PyObject *filename, const char *mode, int feature_version) { PyObject *source_copy; const char *str; int compile_mode = -1; PyCompilerFlags cf; int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input}; PyObject *result; cf.cf_flags = PyCF_ONLY_AST | PyCF_SOURCE_IS_UTF8; if (strcmp(mode, "exec") == 0) compile_mode = 0; else if (strcmp(mode, "eval") == 0) compile_mode = 1; else if (strcmp(mode, "single") == 0) compile_mode = 2; else if (strcmp(mode, "func_type") == 0) compile_mode = 3; else { PyErr_SetString(PyExc_ValueError, "parse() mode must be 'exec', 'eval', 'single', for 'func_type'"); goto error; } str = source_as_string(source, "parse", "string or bytes", &cf, &source_copy); if (str == NULL) goto error; result = string_object_to_py_ast(str, filename, start[compile_mode], &cf, feature_version); Py_XDECREF(source_copy); goto finally; error: result = NULL; finally: Py_DECREF(filename); return result; } // adapted from builtin_compile in Python/clinic/bltinmodule.c.h PyObject * ast3_parse(PyObject *self, PyObject *args) { PyObject *return_value = NULL; PyObject *source; PyObject *filename; const char *mode; int feature_version; if (PyArg_ParseTuple(args, "OO&si:parse", &source, PyUnicode_FSDecoder, &filename, &mode, &feature_version)) return_value = ast3_parse_impl(source, filename, mode, feature_version); return return_value; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1282_2
crossvul-cpp_data_bad_177_0
#include <mruby.h> #include <mruby/array.h> #include <mruby/class.h> #include <mruby/proc.h> #define fiber_ptr(o) ((struct RFiber*)mrb_ptr(o)) #define FIBER_STACK_INIT_SIZE 64 #define FIBER_CI_INIT_SIZE 8 #define CI_ACC_RESUMED -3 /* * call-seq: * Fiber.new{...} -> obj * * Creates a fiber, whose execution is suspend until it is explicitly * resumed using <code>Fiber#resume</code> method. * The code running inside the fiber can give up control by calling * <code>Fiber.yield</code> in which case it yields control back to caller * (the caller of the <code>Fiber#resume</code>). * * Upon yielding or termination the Fiber returns the value of the last * executed expression * * For instance: * * fiber = Fiber.new do * Fiber.yield 1 * 2 * end * * puts fiber.resume * puts fiber.resume * puts fiber.resume * * <em>produces</em> * * 1 * 2 * resuming dead fiber (FiberError) * * The <code>Fiber#resume</code> method accepts an arbitrary number of * parameters, if it is the first call to <code>resume</code> then they * will be passed as block arguments. Otherwise they will be the return * value of the call to <code>Fiber.yield</code> * * Example: * * fiber = Fiber.new do |first| * second = Fiber.yield first + 2 * end * * puts fiber.resume 10 * puts fiber.resume 14 * puts fiber.resume 18 * * <em>produces</em> * * 12 * 14 * resuming dead fiber (FiberError) * */ static mrb_value fiber_init(mrb_state *mrb, mrb_value self) { static const struct mrb_context mrb_context_zero = { 0 }; struct RFiber *f = fiber_ptr(self); struct mrb_context *c; struct RProc *p; mrb_callinfo *ci; mrb_value blk; size_t slen; mrb_get_args(mrb, "&", &blk); if (f->cxt) { mrb_raise(mrb, E_RUNTIME_ERROR, "cannot initialize twice"); } if (mrb_nil_p(blk)) { mrb_raise(mrb, E_ARGUMENT_ERROR, "tried to create Fiber object without a block"); } p = mrb_proc_ptr(blk); if (MRB_PROC_CFUNC_P(p)) { mrb_raise(mrb, E_FIBER_ERROR, "tried to create Fiber from C defined method"); } c = (struct mrb_context*)mrb_malloc(mrb, sizeof(struct mrb_context)); *c = mrb_context_zero; f->cxt = c; /* initialize VM stack */ slen = FIBER_STACK_INIT_SIZE; if (p->body.irep->nregs > slen) { slen += p->body.irep->nregs; } c->stbase = (mrb_value *)mrb_malloc(mrb, slen*sizeof(mrb_value)); c->stend = c->stbase + slen; c->stack = c->stbase; #ifdef MRB_NAN_BOXING { mrb_value *p = c->stbase; mrb_value *pend = c->stend; while (p < pend) { SET_NIL_VALUE(*p); p++; } } #else memset(c->stbase, 0, slen * sizeof(mrb_value)); #endif /* copy receiver from a block */ c->stack[0] = mrb->c->stack[0]; /* initialize callinfo stack */ c->cibase = (mrb_callinfo *)mrb_calloc(mrb, FIBER_CI_INIT_SIZE, sizeof(mrb_callinfo)); c->ciend = c->cibase + FIBER_CI_INIT_SIZE; c->ci = c->cibase; c->ci->stackent = c->stack; /* adjust return callinfo */ ci = c->ci; ci->target_class = MRB_PROC_TARGET_CLASS(p); ci->proc = p; mrb_field_write_barrier(mrb, (struct RBasic*)mrb_obj_ptr(self), (struct RBasic*)p); ci->pc = p->body.irep->iseq; ci->nregs = p->body.irep->nregs; ci[1] = ci[0]; c->ci++; /* push dummy callinfo */ c->fib = f; c->status = MRB_FIBER_CREATED; return self; } static struct mrb_context* fiber_check(mrb_state *mrb, mrb_value fib) { struct RFiber *f = fiber_ptr(fib); mrb_assert(f->tt == MRB_TT_FIBER); if (!f->cxt) { mrb_raise(mrb, E_FIBER_ERROR, "uninitialized Fiber"); } return f->cxt; } static mrb_value fiber_result(mrb_state *mrb, const mrb_value *a, mrb_int len) { if (len == 0) return mrb_nil_value(); if (len == 1) return a[0]; return mrb_ary_new_from_values(mrb, len, a); } /* mark return from context modifying method */ #define MARK_CONTEXT_MODIFY(c) (c)->ci->target_class = NULL static void fiber_check_cfunc(mrb_state *mrb, struct mrb_context *c) { mrb_callinfo *ci; for (ci = c->ci; ci >= c->cibase; ci--) { if (ci->acc < 0) { mrb_raise(mrb, E_FIBER_ERROR, "can't cross C function boundary"); } } } static void fiber_switch_context(mrb_state *mrb, struct mrb_context *c) { c->status = MRB_FIBER_RUNNING; mrb->c = c; } static mrb_value fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; mrb_value value; fiber_check_cfunc(mrb, c); if (resume && c->status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (c->status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); if (c->status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (len >= c->stend - c->stack) { mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber"); } b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } fiber_switch_context(mrb, c); if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; } /* * call-seq: * fiber.resume(args, ...) -> obj * * Resumes the fiber from the point at which the last <code>Fiber.yield</code> * was called, or starts running it if it is the first call to * <code>resume</code>. Arguments passed to resume will be the value of * the <code>Fiber.yield</code> expression or will be passed as block * parameters to the fiber's block if this is the first <code>resume</code>. * * Alternatively, when resume is called it evaluates to the arguments passed * to the next <code>Fiber.yield</code> statement inside the fiber's block * or to the block value if it runs to completion without any * <code>Fiber.yield</code> */ static mrb_value fiber_resume(mrb_state *mrb, mrb_value self) { mrb_value *a; mrb_int len; mrb_bool vmexec = FALSE; mrb_get_args(mrb, "*!", &a, &len); if (mrb->c->ci->acc < 0) { vmexec = TRUE; } return fiber_switch(mrb, self, len, a, TRUE, vmexec); } /* resume thread with given arguments */ MRB_API mrb_value mrb_fiber_resume(mrb_state *mrb, mrb_value fib, mrb_int len, const mrb_value *a) { return fiber_switch(mrb, fib, len, a, TRUE, TRUE); } /* * call-seq: * fiber.alive? -> true or false * * Returns true if the fiber can still be resumed. After finishing * execution of the fiber block this method will always return false. */ MRB_API mrb_value mrb_fiber_alive_p(mrb_state *mrb, mrb_value self) { struct mrb_context *c = fiber_check(mrb, self); return mrb_bool_value(c->status != MRB_FIBER_TERMINATED); } #define fiber_alive_p mrb_fiber_alive_p static mrb_value fiber_eq(mrb_state *mrb, mrb_value self) { mrb_value other; mrb_get_args(mrb, "o", &other); if (mrb_type(other) != MRB_TT_FIBER) { return mrb_false_value(); } return mrb_bool_value(fiber_ptr(self) == fiber_ptr(other)); } /* * call-seq: * fiber.transfer(args, ...) -> obj * * Transfers control to receiver fiber of the method call. * Unlike <code>resume</code> the receiver wouldn't be pushed to call * stack of fibers. Instead it will switch to the call stack of * transferring fiber. * When resuming a fiber that was transferred to another fiber it would * cause double resume error. Though when the fiber is re-transferred * and <code>Fiber.yield</code> is called, the fiber would be resumable. */ static mrb_value fiber_transfer(mrb_state *mrb, mrb_value self) { struct mrb_context *c = fiber_check(mrb, self); mrb_value* a; mrb_int len; fiber_check_cfunc(mrb, mrb->c); mrb_get_args(mrb, "*!", &a, &len); if (c == mrb->root_c) { mrb->c->status = MRB_FIBER_TRANSFERRED; fiber_switch_context(mrb, c); MARK_CONTEXT_MODIFY(c); return fiber_result(mrb, a, len); } if (c == mrb->c) { return fiber_result(mrb, a, len); } return fiber_switch(mrb, self, len, a, FALSE, FALSE); } /* yield values to the caller fiber */ /* mrb_fiber_yield() must be called as `return mrb_fiber_yield(...)` */ MRB_API mrb_value mrb_fiber_yield(mrb_state *mrb, mrb_int len, const mrb_value *a) { struct mrb_context *c = mrb->c; if (!c->prev) { mrb_raise(mrb, E_FIBER_ERROR, "can't yield from root fiber"); } fiber_check_cfunc(mrb, c); c->prev->status = MRB_FIBER_RUNNING; c->status = MRB_FIBER_SUSPENDED; fiber_switch_context(mrb, c->prev); c->prev = NULL; if (c->vmexec) { c->vmexec = FALSE; mrb->c->ci->acc = CI_ACC_RESUMED; } MARK_CONTEXT_MODIFY(mrb->c); return fiber_result(mrb, a, len); } /* * call-seq: * Fiber.yield(args, ...) -> obj * * Yields control back to the context that resumed the fiber, passing * along any arguments that were passed to it. The fiber will resume * processing at this point when <code>resume</code> is called next. * Any arguments passed to the next <code>resume</code> will be the * * mruby limitation: Fiber resume/yield cannot cross C function boundary. * thus you cannot yield from #initialize which is called by mrb_funcall(). */ static mrb_value fiber_yield(mrb_state *mrb, mrb_value self) { mrb_value *a; mrb_int len; mrb_get_args(mrb, "*!", &a, &len); return mrb_fiber_yield(mrb, len, a); } /* * call-seq: * Fiber.current() -> fiber * * Returns the current fiber. If you are not running in the context of * a fiber this method will return the root fiber. */ static mrb_value fiber_current(mrb_state *mrb, mrb_value self) { if (!mrb->c->fib) { struct RFiber *f = (struct RFiber*)mrb_obj_alloc(mrb, MRB_TT_FIBER, mrb_class_ptr(self)); f->cxt = mrb->c; mrb->c->fib = f; } return mrb_obj_value(mrb->c->fib); } void mrb_mruby_fiber_gem_init(mrb_state* mrb) { struct RClass *c; c = mrb_define_class(mrb, "Fiber", mrb->object_class); MRB_SET_INSTANCE_TT(c, MRB_TT_FIBER); mrb_define_method(mrb, c, "initialize", fiber_init, MRB_ARGS_NONE()); mrb_define_method(mrb, c, "resume", fiber_resume, MRB_ARGS_ANY()); mrb_define_method(mrb, c, "transfer", fiber_transfer, MRB_ARGS_ANY()); mrb_define_method(mrb, c, "alive?", fiber_alive_p, MRB_ARGS_NONE()); mrb_define_method(mrb, c, "==", fiber_eq, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, c, "yield", fiber_yield, MRB_ARGS_ANY()); mrb_define_class_method(mrb, c, "current", fiber_current, MRB_ARGS_NONE()); mrb_define_class(mrb, "FiberError", mrb->eStandardError_class); } void mrb_mruby_fiber_gem_final(mrb_state* mrb) { }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_177_0
crossvul-cpp_data_bad_4219_0
/* * oracle.c * * Copyright (C) 2013 Remy Mudingay <mudingay@ill.fr> * * This module is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This module 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. * If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_ORACLE #include "ndpi_api.h" static void ndpi_int_oracle_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_ORACLE, NDPI_PROTOCOL_UNKNOWN); } void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n"); if(packet->tcp != NULL) { sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest); NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n"); /* Oracle Database 9g,10g,11g */ if ((dport == 1521 || sport == 1521) && (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00)) || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) && (packet->payload[1] != 0x00) && (packet->payload[2] == 0x00) && (packet->payload[3] == 0x00)))) { NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); ndpi_int_oracle_add_connection(ndpi_struct, flow); } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 && packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 && packet->payload[3] == 0x00 ) { NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); ndpi_int_oracle_add_connection(ndpi_struct, flow); } } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); } } void init_oracle_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("Oracle", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_ORACLE, ndpi_search_oracle, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4219_0
crossvul-cpp_data_good_2728_0
/* * Copyright (c) 1998-2006 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: IEEE 802.1ag Connectivity Fault Management (CFM) protocols printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include "netdissect.h" #include "extract.h" #include "ether.h" #include "addrtoname.h" #include "oui.h" #include "af.h" struct cfm_common_header_t { uint8_t mdlevel_version; uint8_t opcode; uint8_t flags; uint8_t first_tlv_offset; }; #define CFM_VERSION 0 #define CFM_EXTRACT_VERSION(x) (((x)&0x1f)) #define CFM_EXTRACT_MD_LEVEL(x) (((x)&0xe0)>>5) #define CFM_OPCODE_CCM 1 #define CFM_OPCODE_LBR 2 #define CFM_OPCODE_LBM 3 #define CFM_OPCODE_LTR 4 #define CFM_OPCODE_LTM 5 static const struct tok cfm_opcode_values[] = { { CFM_OPCODE_CCM, "Continuity Check Message"}, { CFM_OPCODE_LBR, "Loopback Reply"}, { CFM_OPCODE_LBM, "Loopback Message"}, { CFM_OPCODE_LTR, "Linktrace Reply"}, { CFM_OPCODE_LTM, "Linktrace Message"}, { 0, NULL} }; /* * Message Formats. */ struct cfm_ccm_t { uint8_t sequence[4]; uint8_t ma_epi[2]; uint8_t names[48]; uint8_t itu_t_y_1731[16]; }; /* * Timer Bases for the CCM Interval field. * Expressed in units of seconds. */ static const float ccm_interval_base[8] = {0, 0.003333, 0.01, 0.1, 1, 10, 60, 600}; #define CCM_INTERVAL_MIN_MULTIPLIER 3.25 #define CCM_INTERVAL_MAX_MULTIPLIER 3.5 #define CFM_CCM_RDI_FLAG 0x80 #define CFM_EXTRACT_CCM_INTERVAL(x) (((x)&0x07)) #define CFM_CCM_MD_FORMAT_8021 0 #define CFM_CCM_MD_FORMAT_NONE 1 #define CFM_CCM_MD_FORMAT_DNS 2 #define CFM_CCM_MD_FORMAT_MAC 3 #define CFM_CCM_MD_FORMAT_CHAR 4 static const struct tok cfm_md_nameformat_values[] = { { CFM_CCM_MD_FORMAT_8021, "IEEE 802.1"}, { CFM_CCM_MD_FORMAT_NONE, "No MD Name present"}, { CFM_CCM_MD_FORMAT_DNS, "DNS string"}, { CFM_CCM_MD_FORMAT_MAC, "MAC + 16Bit Integer"}, { CFM_CCM_MD_FORMAT_CHAR, "Character string"}, { 0, NULL} }; #define CFM_CCM_MA_FORMAT_8021 0 #define CFM_CCM_MA_FORMAT_VID 1 #define CFM_CCM_MA_FORMAT_CHAR 2 #define CFM_CCM_MA_FORMAT_INT 3 #define CFM_CCM_MA_FORMAT_VPN 4 static const struct tok cfm_ma_nameformat_values[] = { { CFM_CCM_MA_FORMAT_8021, "IEEE 802.1"}, { CFM_CCM_MA_FORMAT_VID, "Primary VID"}, { CFM_CCM_MA_FORMAT_CHAR, "Character string"}, { CFM_CCM_MA_FORMAT_INT, "16Bit Integer"}, { CFM_CCM_MA_FORMAT_VPN, "RFC2685 VPN-ID"}, { 0, NULL} }; struct cfm_lbm_t { uint8_t transaction_id[4]; }; struct cfm_ltm_t { uint8_t transaction_id[4]; uint8_t ttl; uint8_t original_mac[ETHER_ADDR_LEN]; uint8_t target_mac[ETHER_ADDR_LEN]; }; static const struct tok cfm_ltm_flag_values[] = { { 0x80, "Use Forwarding-DB only"}, { 0, NULL} }; struct cfm_ltr_t { uint8_t transaction_id[4]; uint8_t ttl; uint8_t replay_action; }; static const struct tok cfm_ltr_flag_values[] = { { 0x80, "UseFDB Only"}, { 0x40, "FwdYes"}, { 0x20, "Terminal MEP"}, { 0, NULL} }; static const struct tok cfm_ltr_replay_action_values[] = { { 1, "Exact Match"}, { 2, "Filtering DB"}, { 3, "MIP CCM DB"}, { 0, NULL} }; #define CFM_TLV_END 0 #define CFM_TLV_SENDER_ID 1 #define CFM_TLV_PORT_STATUS 2 #define CFM_TLV_INTERFACE_STATUS 3 #define CFM_TLV_DATA 4 #define CFM_TLV_REPLY_INGRESS 5 #define CFM_TLV_REPLY_EGRESS 6 #define CFM_TLV_PRIVATE 31 static const struct tok cfm_tlv_values[] = { { CFM_TLV_END, "End"}, { CFM_TLV_SENDER_ID, "Sender ID"}, { CFM_TLV_PORT_STATUS, "Port status"}, { CFM_TLV_INTERFACE_STATUS, "Interface status"}, { CFM_TLV_DATA, "Data"}, { CFM_TLV_REPLY_INGRESS, "Reply Ingress"}, { CFM_TLV_REPLY_EGRESS, "Reply Egress"}, { CFM_TLV_PRIVATE, "Organization Specific"}, { 0, NULL} }; /* * TLVs */ struct cfm_tlv_header_t { uint8_t type; uint8_t length[2]; }; /* FIXME define TLV formats */ static const struct tok cfm_tlv_port_status_values[] = { { 1, "Blocked"}, { 2, "Up"}, { 0, NULL} }; static const struct tok cfm_tlv_interface_status_values[] = { { 1, "Up"}, { 2, "Down"}, { 3, "Testing"}, { 5, "Dormant"}, { 6, "not present"}, { 7, "lower Layer down"}, { 0, NULL} }; #define CFM_CHASSIS_ID_CHASSIS_COMPONENT 1 #define CFM_CHASSIS_ID_INTERFACE_ALIAS 2 #define CFM_CHASSIS_ID_PORT_COMPONENT 3 #define CFM_CHASSIS_ID_MAC_ADDRESS 4 #define CFM_CHASSIS_ID_NETWORK_ADDRESS 5 #define CFM_CHASSIS_ID_INTERFACE_NAME 6 #define CFM_CHASSIS_ID_LOCAL 7 static const struct tok cfm_tlv_senderid_chassisid_values[] = { { 0, "Reserved"}, { CFM_CHASSIS_ID_CHASSIS_COMPONENT, "Chassis component"}, { CFM_CHASSIS_ID_INTERFACE_ALIAS, "Interface alias"}, { CFM_CHASSIS_ID_PORT_COMPONENT, "Port component"}, { CFM_CHASSIS_ID_MAC_ADDRESS, "MAC address"}, { CFM_CHASSIS_ID_NETWORK_ADDRESS, "Network address"}, { CFM_CHASSIS_ID_INTERFACE_NAME, "Interface name"}, { CFM_CHASSIS_ID_LOCAL, "Locally assigned"}, { 0, NULL} }; static int cfm_network_addr_print(netdissect_options *ndo, register const u_char *tptr, const u_int length) { u_int network_addr_type; u_int hexdump = FALSE; /* * Altough AFIs are tpically 2 octects wide, * 802.1ab specifies that this field width * is only once octet */ if (length < 1) { ND_PRINT((ndo, "\n\t Network Address Type (invalid, no data")); return hexdump; } /* The calling function must make any due ND_TCHECK calls. */ network_addr_type = *tptr; ND_PRINT((ndo, "\n\t Network Address Type %s (%u)", tok2str(af_values, "Unknown", network_addr_type), network_addr_type)); /* * Resolve the passed in Address. */ switch(network_addr_type) { case AFNUM_INET: if (length != 1 + 4) { ND_PRINT((ndo, "(invalid IPv4 address length %u)", length - 1)); hexdump = TRUE; break; } ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1))); break; case AFNUM_INET6: if (length != 1 + 16) { ND_PRINT((ndo, "(invalid IPv6 address length %u)", length - 1)); hexdump = TRUE; break; } ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1))); break; default: hexdump = TRUE; break; } return hexdump; } void cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, "CFMv%u not supported, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, "CFMv%u %s, MD Level %u, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, "unknown (%u)", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, "\n\tFirst TLV offset %u", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, " (too large, must be <= %u)", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, " (too small 1, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, ", Flags [CCM Interval %u%s]", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? ", RDI" : "")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, "\n\t CCM Interval %.3fs" ", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, "\n\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, "\n\t MD Name Format %s (%u), MD Name length %u", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, "\n\t MD Name: ")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, "\n\t MAC (length invalid)")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, "\n\t ", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, "\n\t MD Name Format %s (%u)", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, "\n\t MA Name-Format %s (%u), MA name length %u", tok2str(cfm_ma_nameformat_values, "Unknown", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, "\n\t MA Name: ")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, "\n\t ", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, " (too small 4, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltm_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, "\n\t Original-MAC %s, Target-MAC %s", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, " (too small 5, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltr_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, "\n\t Replay-Action %s (%u)", tok2str(cfm_ltr_replay_action_values, "Unknown", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, "\n\t ", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, "\n\t%s TLV (0x%02x)", tok2str(cfm_tlv_values, "Unknown", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is "Not present if the Type field is 0." */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, ", length %u", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_port_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_interface_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, " (too short, must be >= 4)")); return; } ND_PRINT((ndo, ", Vendor: %s (%u), Sub-Type %u", tok2str(oui_values,"Unknown", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); goto next_tlv; } /* * Get the Chassis ID length and check it. * IEEE 802.1Q-2014 Section 21.5.3.1 */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { /* * IEEE 802.1Q-2014 Section 21.5.3.2: Chassis ID Subtype, references * IEEE 802.1AB-2005 Section 9.5.2.2, subsequently * IEEE 802.1AB-2016 Section 8.5.2.2: chassis ID subtype */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Chassis-ID Type %s (%u), Chassis-ID length %u", tok2str(cfm_tlv_senderid_chassisid_values, "Unknown", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } /* IEEE 802.1Q-2014 Section 21.5.3.3: Chassis ID */ switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: if (chassis_id_length != ETHER_ADDR_LEN) { ND_PRINT((ndo, " (invalid MAC address length)")); hexdump = TRUE; break; } ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr + 1, chassis_id_length); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. * IEEE 802.1Q-2014 Section 21.5.3.4: Management Address Domain Length * This and all subsequent fields are not present if the TLV length * allows only the above fields. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ break; } /* Here mgmt_addr_length stands for the management domain length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Management Address Domain Length %u", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.5: Management Address Domain */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ hex_print(ndo, "\n\t Management Address Domain: ", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; /* * IEEE 802.1Q-2014 Section 21.5.3.6: Management Address Length * This field is present if Management Address Domain Length is not 0. */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (Management Address Length is missing)")); hexdump = TRUE; break; } /* Here mgmt_addr_length stands for the management address length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Management Address Length %u", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.7: Management Address */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ hex_print(ndo, "\n\t Management Address: ", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, "\n\t ", cfm_tlv_len); next_tlv: tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, "\n\t\t packet is too short")); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2728_0
crossvul-cpp_data_good_3396_0
/* Copyright (c) 2013. The YARA Authors. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* This module implements a regular expressions engine based on Thompson's algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html. What the article names a "thread" has been named a "fiber" in this code, in order to avoid confusion with operating system threads. */ #include <assert.h> #include <string.h> #include <limits.h> #include <yara/limits.h> #include <yara/globals.h> #include <yara/utils.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/error.h> #include <yara/threading.h> #include <yara/re_lexer.h> #include <yara/hex_lexer.h> #define EMIT_BACKWARDS 0x01 #define EMIT_DONT_SET_FORWARDS_CODE 0x02 #define EMIT_DONT_SET_BACKWARDS_CODE 0x04 typedef struct _RE_REPEAT_ARGS { uint16_t min; uint16_t max; int32_t offset; } RE_REPEAT_ARGS; typedef struct _RE_REPEAT_ANY_ARGS { uint16_t min; uint16_t max; } RE_REPEAT_ANY_ARGS; typedef struct _RE_EMIT_CONTEXT { YR_ARENA* arena; RE_SPLIT_ID_TYPE next_split_id; } RE_EMIT_CONTEXT; typedef struct _RE_FIBER { uint8_t* ip; // instruction pointer int32_t sp; // stack pointer int32_t rc; // repeat counter uint16_t stack[RE_MAX_STACK]; struct _RE_FIBER* prev; struct _RE_FIBER* next; } RE_FIBER; typedef struct _RE_FIBER_LIST { RE_FIBER* head; RE_FIBER* tail; } RE_FIBER_LIST; typedef struct _RE_FIBER_POOL { int fiber_count; RE_FIBER_LIST fibers; } RE_FIBER_POOL; typedef struct _RE_THREAD_STORAGE { RE_FIBER_POOL fiber_pool; } RE_THREAD_STORAGE; YR_THREAD_STORAGE_KEY thread_storage_key = 0; #define CHAR_IN_CLASS(chr, cls) \ ((cls)[(chr) / 8] & 1 << ((chr) % 8)) int _yr_re_is_word_char( uint8_t* input, uint8_t character_size) { int result = ((isalnum(*input) || (*input) == '_')); if (character_size == 2) result = result && (*(input + 1) == 0); return result; } // // yr_re_initialize // // Should be called by main thread before any other // function from this module. // int yr_re_initialize(void) { return yr_thread_storage_create(&thread_storage_key); } // // yr_re_finalize // // Should be called by main thread after every other thread // stopped using functions from this module. // int yr_re_finalize(void) { yr_thread_storage_destroy(&thread_storage_key); thread_storage_key = 0; return ERROR_SUCCESS; } // // yr_re_finalize_thread // // Should be called by every thread using this module // before exiting. // int yr_re_finalize_thread(void) { RE_FIBER* fiber; RE_FIBER* next_fiber; RE_THREAD_STORAGE* storage; if (thread_storage_key != 0) storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value( &thread_storage_key); else return ERROR_SUCCESS; if (storage != NULL) { fiber = storage->fiber_pool.fibers.head; while (fiber != NULL) { next_fiber = fiber->next; yr_free(fiber); fiber = next_fiber; } yr_free(storage); } return yr_thread_storage_set_value(&thread_storage_key, NULL); } RE_NODE* yr_re_node_create( int type, RE_NODE* left, RE_NODE* right) { RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE)); if (result != NULL) { result->type = type; result->left = left; result->right = right; result->greedy = TRUE; result->forward_code = NULL; result->backward_code = NULL; } return result; } void yr_re_node_destroy( RE_NODE* node) { if (node->left != NULL) yr_re_node_destroy(node->left); if (node->right != NULL) yr_re_node_destroy(node->right); if (node->type == RE_NODE_CLASS) yr_free(node->class_vector); yr_free(node); } int yr_re_ast_create( RE_AST** re_ast) { *re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST)); if (*re_ast == NULL) return ERROR_INSUFFICIENT_MEMORY; (*re_ast)->flags = 0; (*re_ast)->levels = 0; (*re_ast)->root_node = NULL; return ERROR_SUCCESS; } void yr_re_ast_destroy( RE_AST* re_ast) { if (re_ast->root_node != NULL) yr_re_node_destroy(re_ast->root_node); yr_free(re_ast); } // // yr_re_parse // // Parses a regexp but don't emit its code. A further call to // yr_re_emit_code is required to get the code. // int yr_re_parse( const char* re_string, RE_AST** re_ast, RE_ERROR* error) { return yr_parse_re_string(re_string, re_ast, error); } // // yr_re_parse_hex // // Parses a hex string but don't emit its code. A further call to // yr_re_emit_code is required to get the code. // int yr_re_parse_hex( const char* hex_string, RE_AST** re_ast, RE_ERROR* error) { return yr_parse_hex_string(hex_string, re_ast, error); } // // yr_re_compile // // Parses the regexp and emit its code to the provided code_arena. // int yr_re_compile( const char* re_string, int flags, YR_ARENA* code_arena, RE** re, RE_ERROR* error) { RE_AST* re_ast; RE _re; FAIL_ON_ERROR(yr_arena_reserve_memory( code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE)); FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error)); _re.flags = flags; FAIL_ON_ERROR_WITH_CLEANUP( yr_arena_write_data( code_arena, &_re, sizeof(_re), (void**) re), yr_re_ast_destroy(re_ast)); FAIL_ON_ERROR_WITH_CLEANUP( yr_re_ast_emit_code(re_ast, code_arena, FALSE), yr_re_ast_destroy(re_ast)); yr_re_ast_destroy(re_ast); return ERROR_SUCCESS; } // // yr_re_match // // Verifies if the target string matches the pattern // // Args: // RE* re - A pointer to a compiled regexp // char* target - Target string // // Returns: // See return codes for yr_re_exec int yr_re_match( RE* re, const char* target) { int result; yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL, &result); return result; } // // yr_re_ast_extract_literal // // Verifies if the provided regular expression is just a literal string // like "abc", "12345", without any wildcard, operator, etc. In that case // returns the string as a SIZED_STRING, or returns NULL if otherwise. // // The caller is responsible for deallocating the returned SIZED_STRING by // calling yr_free. // SIZED_STRING* yr_re_ast_extract_literal( RE_AST* re_ast) { SIZED_STRING* string; RE_NODE* node = re_ast->root_node; int i, length = 0; char tmp; while (node != NULL) { length++; if (node->type == RE_NODE_LITERAL) break; if (node->type != RE_NODE_CONCAT) return NULL; if (node->right == NULL || node->right->type != RE_NODE_LITERAL) return NULL; node = node->left; } string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length); if (string == NULL) return NULL; string->length = 0; node = re_ast->root_node; while (node->type == RE_NODE_CONCAT) { string->c_string[string->length++] = node->right->value; node = node->left; } string->c_string[string->length++] = node->value; // The string ends up reversed. Reverse it back to its original value. for (i = 0; i < length / 2; i++) { tmp = string->c_string[i]; string->c_string[i] = string->c_string[length - i - 1]; string->c_string[length - i - 1] = tmp; } return string; } int _yr_re_node_contains_dot_star( RE_NODE* re_node) { if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY) return TRUE; if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left)) return TRUE; if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right)) return TRUE; return FALSE; } int yr_re_ast_contains_dot_star( RE_AST* re_ast) { return _yr_re_node_contains_dot_star(re_ast->root_node); } // // yr_re_ast_split_at_chaining_point // // In some cases splitting a regular expression in two is more efficient that // having a single regular expression. This happens when the regular expression // contains a large repetition of any character, for example: /foo.{0,1000}bar/ // In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained" // to /foo/. This means that /foo/ and /bar/ are handled as individual regexps // and when both matches YARA verifies if the distance between the matches // complies with the {0,1000} restriction. // This function traverses the regexp's tree looking for nodes where the regxp // should be split. It expects a left-unbalanced tree where the right child of // a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be // always the left child of its parent if the parent is also a RE_NODE_CONCAT. // int yr_re_ast_split_at_chaining_point( RE_AST* re_ast, RE_AST** result_re_ast, RE_AST** remainder_re_ast, int32_t* min_gap, int32_t* max_gap) { RE_NODE* node = re_ast->root_node; RE_NODE* child = re_ast->root_node->left; RE_NODE* parent = NULL; int result; *result_re_ast = re_ast; *remainder_re_ast = NULL; *min_gap = 0; *max_gap = 0; while (child != NULL && child->type == RE_NODE_CONCAT) { if (child->right != NULL && child->right->type == RE_NODE_RANGE_ANY && child->right->greedy == FALSE && (child->right->start > STRING_CHAINING_THRESHOLD || child->right->end > STRING_CHAINING_THRESHOLD)) { result = yr_re_ast_create(remainder_re_ast); if (result != ERROR_SUCCESS) return result; (*remainder_re_ast)->root_node = child->left; (*remainder_re_ast)->flags = re_ast->flags; child->left = NULL; if (parent != NULL) parent->left = node->right; else (*result_re_ast)->root_node = node->right; node->right = NULL; *min_gap = child->right->start; *max_gap = child->right->end; yr_re_node_destroy(node); return ERROR_SUCCESS; } parent = node; node = child; child = child->left; } return ERROR_SUCCESS; } int _yr_emit_inst( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint8_t** instruction_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); *code_size = sizeof(uint8_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint8( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint8_t argument, uint8_t** instruction_addr, uint8_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint8_t), (void**) argument_addr)); *code_size = 2 * sizeof(uint8_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint16( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint16_t argument, uint8_t** instruction_addr, uint16_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(uint16_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint32( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint32_t argument, uint8_t** instruction_addr, uint32_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint32_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(uint32_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_int16( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, int16_t argument, uint8_t** instruction_addr, int16_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(int16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(int16_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_struct( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, void* structure, size_t structure_size, uint8_t** instruction_addr, void** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, structure, structure_size, (void**) argument_addr)); *code_size = sizeof(uint8_t) + structure_size; return ERROR_SUCCESS; } int _yr_emit_split( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, int16_t argument, uint8_t** instruction_addr, int16_t** argument_addr, size_t* code_size) { assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B); if (emit_context->next_split_id == RE_MAX_SPLIT_ID) return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX; FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &emit_context->next_split_id, sizeof(RE_SPLIT_ID_TYPE), NULL)); emit_context->next_split_id++; FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(int16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t); return ERROR_SUCCESS; } int _yr_re_emit( RE_EMIT_CONTEXT* emit_context, RE_NODE* re_node, int flags, uint8_t** code_addr, size_t* code_size) { size_t branch_size; size_t split_size; size_t inst_size; size_t jmp_size; int emit_split; int emit_repeat; int emit_prolog; int emit_epilog; RE_REPEAT_ARGS repeat_args; RE_REPEAT_ARGS* repeat_start_args_addr; RE_REPEAT_ANY_ARGS repeat_any_args; RE_NODE* left; RE_NODE* right; int16_t* split_offset_addr = NULL; int16_t* jmp_offset_addr = NULL; uint8_t* instruction_addr = NULL; *code_size = 0; switch(re_node->type) { case RE_NODE_LITERAL: FAIL_ON_ERROR(_yr_emit_inst_arg_uint8( emit_context, RE_OPCODE_LITERAL, re_node->value, &instruction_addr, NULL, code_size)); break; case RE_NODE_MASKED_LITERAL: FAIL_ON_ERROR(_yr_emit_inst_arg_uint16( emit_context, RE_OPCODE_MASKED_LITERAL, re_node->mask << 8 | re_node->value, &instruction_addr, NULL, code_size)); break; case RE_NODE_WORD_CHAR: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_WORD_CHAR, &instruction_addr, code_size)); break; case RE_NODE_NON_WORD_CHAR: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_WORD_CHAR, &instruction_addr, code_size)); break; case RE_NODE_WORD_BOUNDARY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_WORD_BOUNDARY, &instruction_addr, code_size)); break; case RE_NODE_NON_WORD_BOUNDARY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_WORD_BOUNDARY, &instruction_addr, code_size)); break; case RE_NODE_SPACE: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_SPACE, &instruction_addr, code_size)); break; case RE_NODE_NON_SPACE: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_SPACE, &instruction_addr, code_size)); break; case RE_NODE_DIGIT: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_DIGIT, &instruction_addr, code_size)); break; case RE_NODE_NON_DIGIT: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_DIGIT, &instruction_addr, code_size)); break; case RE_NODE_ANY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_ANY, &instruction_addr, code_size)); break; case RE_NODE_CLASS: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_CLASS, &instruction_addr, code_size)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, re_node->class_vector, 32, NULL)); *code_size += 32; break; case RE_NODE_ANCHOR_START: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_MATCH_AT_START, &instruction_addr, code_size)); break; case RE_NODE_ANCHOR_END: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_MATCH_AT_END, &instruction_addr, code_size)); break; case RE_NODE_CONCAT: if (flags & EMIT_BACKWARDS) { left = re_node->right; right = re_node->left; } else { left = re_node->left; right = re_node->right; } FAIL_ON_ERROR(_yr_re_emit( emit_context, left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, right, flags, NULL, &branch_size)); *code_size += branch_size; break; case RE_NODE_PLUS: // Code for e+ looks like: // // L1: code for e // split L1, L2 // L2: FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A, -((int16_t) branch_size), NULL, &split_offset_addr, &split_size)); *code_size += split_size; break; case RE_NODE_STAR: // Code for e* looks like: // // L1: split L1, L2 // code for e // jmp L1 // L2: FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B, 0, &instruction_addr, &split_offset_addr, &split_size)); *code_size += split_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, NULL, &branch_size)); *code_size += branch_size; // Emit jump with offset set to 0. FAIL_ON_ERROR(_yr_emit_inst_arg_int16( emit_context, RE_OPCODE_JUMP, -((uint16_t)(branch_size + split_size)), NULL, &jmp_offset_addr, &jmp_size)); *code_size += jmp_size; assert(split_size + branch_size + jmp_size < INT16_MAX); // Update split offset. *split_offset_addr = (int16_t) (split_size + branch_size + jmp_size); break; case RE_NODE_ALT: // Code for e1|e2 looks like: // // split L1, L2 // L1: code for e1 // jmp L3 // L2: code for e2 // L3: // Emit a split instruction with offset set to 0 temporarily. Offset // will be updated after we know the size of the code generated for // the left node (e1). FAIL_ON_ERROR(_yr_emit_split( emit_context, RE_OPCODE_SPLIT_A, 0, &instruction_addr, &split_offset_addr, &split_size)); *code_size += split_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, NULL, &branch_size)); *code_size += branch_size; // Emit jump with offset set to 0. FAIL_ON_ERROR(_yr_emit_inst_arg_int16( emit_context, RE_OPCODE_JUMP, 0, NULL, &jmp_offset_addr, &jmp_size)); *code_size += jmp_size; assert(split_size + branch_size + jmp_size < INT16_MAX); // Update split offset. *split_offset_addr = (int16_t) (split_size + branch_size + jmp_size); FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->right, flags, NULL, &branch_size)); *code_size += branch_size; assert(branch_size + jmp_size < INT16_MAX); // Update offset for jmp instruction. *jmp_offset_addr = (int16_t) (branch_size + jmp_size); break; case RE_NODE_RANGE_ANY: repeat_any_args.min = re_node->start; repeat_any_args.max = re_node->end; FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_ANY_GREEDY : RE_OPCODE_REPEAT_ANY_UNGREEDY, &repeat_any_args, sizeof(repeat_any_args), &instruction_addr, NULL, &inst_size)); *code_size += inst_size; break; case RE_NODE_RANGE: // Code for e{n,m} looks like: // // code for e --- prolog // repeat_start n, m, L1 --+ // L0: code for e | repeat // repeat_end n, m, L0 --+ // L1: split L2, L3 --- split // L2: code for e --- epilog // L3: // // Not all sections (prolog, repeat, split and epilog) are generated in all // cases, it depends on the values of n and m. The following table shows // which sections are generated for the first few values of n and m. // // n,m prolog repeat split epilog // (min,max) // --------------------------------------- // 0,0 - - - - // 0,1 - - X X // 0,2 - 0,1 X X // 0,3 - 0,2 X X // 0,M - 0,M-1 X X // // 1,1 X - - - // 1,2 X - X X // 1,3 X 0,1 X X // 1,4 X 1,2 X X // 1,M X 1,M-2 X X // // 2,2 X - - X // 2,3 X 1,1 X X // 2,4 X 1,2 X X // 2,M X 1,M-2 X X // // 3,3 X 1,1 - X // 3,4 X 2,2 X X // 3,M X 2,M-1 X X // // The code can't consists simply in the repeat section, the prolog and // epilog are required because we can't have atoms pointing to code inside // the repeat loop. Atoms' forwards_code will point to code in the prolog // and backwards_code will point to code in the epilog (or in prolog if // epilog wasn't generated, like in n=1,m=1) emit_prolog = re_node->start > 0; emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2; emit_split = re_node->end > re_node->start; emit_epilog = re_node->end > re_node->start || re_node->end > 1; if (emit_prolog) { FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; } if (emit_repeat) { repeat_args.min = re_node->start; repeat_args.max = re_node->end; if (emit_prolog) { repeat_args.max--; repeat_args.min--; } if (emit_split) repeat_args.max--; else repeat_args.min--; repeat_args.offset = 0; FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_START_GREEDY : RE_OPCODE_REPEAT_START_UNGREEDY, &repeat_args, sizeof(repeat_args), emit_prolog ? NULL : &instruction_addr, (void**) &repeat_start_args_addr, &inst_size)); *code_size += inst_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE, NULL, &branch_size)); *code_size += branch_size; repeat_start_args_addr->offset = (int32_t)(2 * inst_size + branch_size); repeat_args.offset = -((int32_t) branch_size); FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_END_GREEDY : RE_OPCODE_REPEAT_END_UNGREEDY, &repeat_args, sizeof(repeat_args), NULL, NULL, &inst_size)); *code_size += inst_size; } if (emit_split) { FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B, 0, NULL, &split_offset_addr, &split_size)); *code_size += split_size; } if (emit_epilog) { FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags, emit_prolog || emit_repeat ? NULL : &instruction_addr, &branch_size)); *code_size += branch_size; } if (emit_split) { assert(split_size + branch_size < INT16_MAX); *split_offset_addr = (int16_t) (split_size + branch_size); } break; } if (flags & EMIT_BACKWARDS) { if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE)) re_node->backward_code = instruction_addr + *code_size; } else { if (!(flags & EMIT_DONT_SET_FORWARDS_CODE)) re_node->forward_code = instruction_addr; } if (code_addr != NULL) *code_addr = instruction_addr; return ERROR_SUCCESS; } int yr_re_ast_emit_code( RE_AST* re_ast, YR_ARENA* arena, int backwards_code) { RE_EMIT_CONTEXT emit_context; size_t code_size; size_t total_size; // Ensure that we have enough contiguous memory space in the arena to // contain the regular expression code. The code can't span over multiple // non-contiguous pages. FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE)); // Emit code for matching the regular expressions forwards. total_size = 0; emit_context.arena = arena; emit_context.next_split_id = 0; FAIL_ON_ERROR(_yr_re_emit( &emit_context, re_ast->root_node, backwards_code ? EMIT_BACKWARDS : 0, NULL, &code_size)); total_size += code_size; FAIL_ON_ERROR(_yr_emit_inst( &emit_context, RE_OPCODE_MATCH, NULL, &code_size)); total_size += code_size; if (total_size > RE_MAX_CODE_SIZE) return ERROR_REGULAR_EXPRESSION_TOO_LARGE; return ERROR_SUCCESS; } int _yr_re_alloc_storage( RE_THREAD_STORAGE** storage) { *storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value( &thread_storage_key); if (*storage == NULL) { *storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE)); if (*storage == NULL) return ERROR_INSUFFICIENT_MEMORY; (*storage)->fiber_pool.fiber_count = 0; (*storage)->fiber_pool.fibers.head = NULL; (*storage)->fiber_pool.fibers.tail = NULL; FAIL_ON_ERROR( yr_thread_storage_set_value(&thread_storage_key, *storage)); } return ERROR_SUCCESS; } int _yr_re_fiber_create( RE_FIBER_POOL* fiber_pool, RE_FIBER** new_fiber) { RE_FIBER* fiber; if (fiber_pool->fibers.head != NULL) { fiber = fiber_pool->fibers.head; fiber_pool->fibers.head = fiber->next; if (fiber_pool->fibers.tail == fiber) fiber_pool->fibers.tail = NULL; } else { if (fiber_pool->fiber_count == RE_MAX_FIBERS) return ERROR_TOO_MANY_RE_FIBERS; fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER)); if (fiber == NULL) return ERROR_INSUFFICIENT_MEMORY; fiber_pool->fiber_count++; } fiber->ip = NULL; fiber->sp = -1; fiber->rc = -1; fiber->next = NULL; fiber->prev = NULL; *new_fiber = fiber; return ERROR_SUCCESS; } // // _yr_re_fiber_append // // Appends 'fiber' to 'fiber_list' // void _yr_re_fiber_append( RE_FIBER_LIST* fiber_list, RE_FIBER* fiber) { assert(fiber->prev == NULL); assert(fiber->next == NULL); fiber->prev = fiber_list->tail; if (fiber_list->tail != NULL) fiber_list->tail->next = fiber; fiber_list->tail = fiber; if (fiber_list->head == NULL) fiber_list->head = fiber; assert(fiber_list->tail->next == NULL); assert(fiber_list->head->prev == NULL); } // // _yr_re_fiber_exists // // Verifies if a fiber with the same properties (ip, rc, sp, and stack values) // than 'target_fiber' exists in 'fiber_list'. The list is iterated from // the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not // taken into account. // int _yr_re_fiber_exists( RE_FIBER_LIST* fiber_list, RE_FIBER* target_fiber, RE_FIBER* last_fiber) { RE_FIBER* fiber = fiber_list->head; int equal_stacks; int i; if (last_fiber == NULL) return FALSE; while (fiber != last_fiber->next) { if (fiber->ip == target_fiber->ip && fiber->sp == target_fiber->sp && fiber->rc == target_fiber->rc) { equal_stacks = TRUE; for (i = 0; i <= fiber->sp; i++) { if (fiber->stack[i] != target_fiber->stack[i]) { equal_stacks = FALSE; break; } } if (equal_stacks) return TRUE; } fiber = fiber->next; } return FALSE; } // // _yr_re_fiber_split // // Clones a fiber in fiber_list and inserts the cloned fiber just after. // the original one. If fiber_list is: // // f1 -> f2 -> f3 -> f4 // // Splitting f2 will result in: // // f1 -> f2 -> cloned f2 -> f3 -> f4 // int _yr_re_fiber_split( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber, RE_FIBER** new_fiber) { int32_t i; FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber)); (*new_fiber)->sp = fiber->sp; (*new_fiber)->ip = fiber->ip; (*new_fiber)->rc = fiber->rc; for (i = 0; i <= fiber->sp; i++) (*new_fiber)->stack[i] = fiber->stack[i]; (*new_fiber)->next = fiber->next; (*new_fiber)->prev = fiber; if (fiber->next != NULL) fiber->next->prev = *new_fiber; fiber->next = *new_fiber; if (fiber_list->tail == fiber) fiber_list->tail = *new_fiber; assert(fiber_list->tail->next == NULL); assert(fiber_list->head->prev == NULL); return ERROR_SUCCESS; } // // _yr_re_fiber_kill // // Kills a given fiber by removing it from the fiber list and putting it // in the fiber pool. // RE_FIBER* _yr_re_fiber_kill( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber) { RE_FIBER* next_fiber = fiber->next; if (fiber->prev != NULL) fiber->prev->next = next_fiber; if (next_fiber != NULL) next_fiber->prev = fiber->prev; if (fiber_pool->fibers.tail != NULL) fiber_pool->fibers.tail->next = fiber; if (fiber_list->tail == fiber) fiber_list->tail = fiber->prev; if (fiber_list->head == fiber) fiber_list->head = next_fiber; fiber->next = NULL; fiber->prev = fiber_pool->fibers.tail; fiber_pool->fibers.tail = fiber; if (fiber_pool->fibers.head == NULL) fiber_pool->fibers.head = fiber; return next_fiber; } // // _yr_re_fiber_kill_tail // // Kills all fibers from the given one up to the end of the fiber list. // void _yr_re_fiber_kill_tail( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber) { RE_FIBER* prev_fiber = fiber->prev; if (prev_fiber != NULL) prev_fiber->next = NULL; fiber->prev = fiber_pool->fibers.tail; if (fiber_pool->fibers.tail != NULL) fiber_pool->fibers.tail->next = fiber; fiber_pool->fibers.tail = fiber_list->tail; fiber_list->tail = prev_fiber; if (fiber_list->head == fiber) fiber_list->head = NULL; if (fiber_pool->fibers.head == NULL) fiber_pool->fibers.head = fiber; } // // _yr_re_fiber_kill_all // // Kills all fibers in the fiber list. // void _yr_re_fiber_kill_all( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool) { if (fiber_list->head != NULL) _yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head); } // // _yr_re_fiber_sync // // Executes a fiber until reaching an "matching" instruction. A "matching" // instruction is one that actually reads a byte from the input and performs // some matching. If the fiber reaches a split instruction, the new fiber is // also synced. // int _yr_re_fiber_sync( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber_to_sync) { // A array for keeping track of which split instructions has been already // executed. Each split instruction within a regexp has an associated ID // between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is // required to avoid infinite loops in regexps like (a*)* or (a|)* RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID]; RE_SPLIT_ID_TYPE splits_executed_count = 0; RE_SPLIT_ID_TYPE split_id, splits_executed_idx; int split_already_executed; RE_REPEAT_ARGS* repeat_args; RE_REPEAT_ANY_ARGS* repeat_any_args; RE_FIBER* fiber; RE_FIBER* last; RE_FIBER* prev; RE_FIBER* next; RE_FIBER* branch_a; RE_FIBER* branch_b; fiber = fiber_to_sync; prev = fiber_to_sync->prev; last = fiber_to_sync->next; while(fiber != last) { uint8_t opcode = *fiber->ip; switch(opcode) { case RE_OPCODE_SPLIT_A: case RE_OPCODE_SPLIT_B: split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1); split_already_executed = FALSE; for (splits_executed_idx = 0; splits_executed_idx < splits_executed_count; splits_executed_idx++) { if (split_id == splits_executed[splits_executed_idx]) { split_already_executed = TRUE; break; } } if (split_already_executed) { fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber); } else { branch_a = fiber; FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); // With RE_OPCODE_SPLIT_A the current fiber continues at the next // instruction in the stream (branch A), while the newly created // fiber starts at the address indicated by the instruction (branch B) // RE_OPCODE_SPLIT_B has the opposite behavior. if (opcode == RE_OPCODE_SPLIT_B) yr_swap(branch_a, branch_b, RE_FIBER*); // Branch A continues at the next instruction branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3); // Branch B adds the offset encoded in the opcode to its instruction // pointer. branch_b->ip += *(int16_t*)( branch_b->ip + 1 // opcode size + sizeof(RE_SPLIT_ID_TYPE)); splits_executed[splits_executed_count] = split_id; splits_executed_count++; } break; case RE_OPCODE_REPEAT_START_GREEDY: case RE_OPCODE_REPEAT_START_UNGREEDY: repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1); assert(repeat_args->max > 0); branch_a = fiber; if (repeat_args->min == 0) { FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_b->ip += repeat_args->offset; } branch_a->stack[++branch_a->sp] = 0; branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS)); break; case RE_OPCODE_REPEAT_END_GREEDY: case RE_OPCODE_REPEAT_END_UNGREEDY: repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1); fiber->stack[fiber->sp]++; if (fiber->stack[fiber->sp] < repeat_args->min) { fiber->ip += repeat_args->offset; break; } branch_a = fiber; if (fiber->stack[fiber->sp] < repeat_args->max) { FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_END_GREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_a->sp--; branch_b->ip += repeat_args->offset; } branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS)); break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1); // If repetition counter (rc) is -1 it means that we are reaching this // instruction from the previous one in the instructions stream. In // this case let's initialize the counter to 0 and start looping. if (fiber->rc == -1) fiber->rc = 0; if (fiber->rc < repeat_any_args->min) { // Increase repetition counter and continue with next fiber. The // instruction pointer for this fiber is not incremented yet, this // fiber spins in this same instruction until reaching the minimum // number of repetitions. fiber->rc++; fiber = fiber->next; } else if (fiber->rc < repeat_any_args->max) { // Once the minimum number of repetitions are matched one fiber // remains spinning in this instruction until reaching the maximum // number of repetitions while new fibers are created. New fibers // start executing at the next instruction. next = fiber->next; branch_a = fiber; FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_a->rc++; branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS)); branch_b->rc = -1; FAIL_ON_ERROR(_yr_re_fiber_sync( fiber_list, fiber_pool, branch_b)); fiber = next; } else { // When the maximum number of repetitions is reached the fiber keeps // executing at the next instruction. The repetition counter is set // to -1 indicating that we are not spinning in a repeat instruction // anymore. fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS)); fiber->rc = -1; } break; case RE_OPCODE_JUMP: fiber->ip += *(int16_t*)(fiber->ip + 1); break; default: if (_yr_re_fiber_exists(fiber_list, fiber, prev)) fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber); else fiber = fiber->next; } } return ERROR_SUCCESS; } // // yr_re_exec // // Executes a regular expression. The specified regular expression will try to // match the data starting at the address specified by "input". The "input" // pointer can point to any address inside a memory buffer. Arguments // "input_forwards_size" and "input_backwards_size" indicate how many bytes // can be accesible starting at "input" and going forwards and backwards // respectively. // // <--- input_backwards_size -->|<----------- input_forwards_size --------> // |-------- memory buffer -----------------------------------------------| // ^ // input // // Args: // uint8_t* re_code - Regexp code be executed // uint8_t* input - Pointer to input data // size_t input_forwards_size - Number of accessible bytes starting at // "input" and going forwards. // size_t input_backwards_size - Number of accessible bytes starting at // "input" and going backwards // int flags - Flags: // RE_FLAGS_SCAN // RE_FLAGS_BACKWARDS // RE_FLAGS_EXHAUSTIVE // RE_FLAGS_WIDE // RE_FLAGS_NO_CASE // RE_FLAGS_DOT_ALL // RE_MATCH_CALLBACK_FUNC callback - Callback function // void* callback_args - Callback argument // int* matches - Pointer to an integer receiving the // number of matching bytes. Notice that // 0 means a zero-length match, while no // matches is -1. // Returns: // ERROR_SUCCESS or any other error code. int yr_re_exec( uint8_t* re_code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { uint8_t* ip; uint8_t* input; uint8_t mask; uint8_t value; uint8_t character_size; RE_FIBER_LIST fibers; RE_THREAD_STORAGE* storage; RE_FIBER* fiber; RE_FIBER* next_fiber; int bytes_matched; int max_bytes_matched; int match; int input_incr; int kill; int action; #define ACTION_NONE 0 #define ACTION_CONTINUE 1 #define ACTION_KILL 2 #define ACTION_KILL_TAIL 3 #define prolog { \ if ((bytes_matched >= max_bytes_matched) || \ (character_size == 2 && *(input + 1) != 0)) \ { \ action = ACTION_KILL; \ break; \ } \ } if (matches != NULL) *matches = -1; if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS) return -2; if (flags & RE_FLAGS_WIDE) character_size = 2; else character_size = 1; input = input_data; input_incr = character_size; if (flags & RE_FLAGS_BACKWARDS) { max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT); input -= character_size; input_incr = -input_incr; } else { max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT); } // Round down max_bytes_matched to a multiple of character_size, this way if // character_size is 2 and max_bytes_matched is odd we are ignoring the // extra byte which can't match anyways. max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size; bytes_matched = 0; FAIL_ON_ERROR(_yr_re_fiber_create(&storage->fiber_pool, &fiber)); fiber->ip = re_code; fibers.head = fiber; fibers.tail = fiber; FAIL_ON_ERROR_WITH_CLEANUP( _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); while (fibers.head != NULL) { fiber = fibers.head; while(fiber != NULL) { ip = fiber->ip; action = ACTION_NONE; switch(*ip) { case RE_OPCODE_ANY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; // The instruction pointer is not incremented here. The current fiber // spins in this instruction until reaching the required number of // repetitions. The code controlling the number of repetitions is in // _yr_re_fiber_sync. break; case RE_OPCODE_LITERAL: prolog; if (flags & RE_FLAGS_NO_CASE) match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)]; else match = (*input == *(ip + 1)); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 2; break; case RE_OPCODE_MASKED_LITERAL: prolog; value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; // We don't need to take into account the case-insensitive // case because this opcode is only used with hex strings, // which can't be case-insensitive. match = ((*input & mask) == value); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 3; break; case RE_OPCODE_CLASS: prolog; match = CHAR_IN_CLASS(*input, ip + 1); if (!match && (flags & RE_FLAGS_NO_CASE)) match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 33; break; case RE_OPCODE_WORD_CHAR: prolog; match = _yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_WORD_CHAR: prolog; match = !_yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_SPACE: case RE_OPCODE_NON_SPACE: prolog; switch(*input) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': match = TRUE; break; default: match = FALSE; } if (*ip == RE_OPCODE_NON_SPACE) match = !match; action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_DIGIT: prolog; match = isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_DIGIT: prolog; match = !isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_WORD_BOUNDARY: case RE_OPCODE_NON_WORD_BOUNDARY: if (bytes_matched == 0 && input_backwards_size < character_size) { match = TRUE; } else if (bytes_matched >= max_bytes_matched) { match = TRUE; } else { assert(input < input_data + input_forwards_size); assert(input >= input_data - input_backwards_size); assert(input - input_incr < input_data + input_forwards_size); assert(input - input_incr >= input_data - input_backwards_size); match = _yr_re_is_word_char(input, character_size) != \ _yr_re_is_word_char(input - input_incr, character_size); } if (*ip == RE_OPCODE_NON_WORD_BOUNDARY) match = !match; action = match ? ACTION_CONTINUE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_START: if (flags & RE_FLAGS_BACKWARDS) kill = input_backwards_size > (size_t) bytes_matched; else kill = input_backwards_size > 0 || (bytes_matched != 0); action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_END: kill = flags & RE_FLAGS_BACKWARDS || input_forwards_size > (size_t) bytes_matched; action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH: if (matches != NULL) *matches = bytes_matched; if (flags & RE_FLAGS_EXHAUSTIVE) { if (callback != NULL) { if (flags & RE_FLAGS_BACKWARDS) { FAIL_ON_ERROR_WITH_CLEANUP( callback( input + character_size, bytes_matched, flags, callback_args), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); } else { FAIL_ON_ERROR_WITH_CLEANUP( callback( input_data, bytes_matched, flags, callback_args), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); } } action = ACTION_KILL; } else { action = ACTION_KILL_TAIL; } break; default: assert(FALSE); } switch(action) { case ACTION_KILL: fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber); break; case ACTION_KILL_TAIL: _yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber); fiber = NULL; break; case ACTION_CONTINUE: FAIL_ON_ERROR_WITH_CLEANUP( _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); break; default: next_fiber = fiber->next; FAIL_ON_ERROR_WITH_CLEANUP( _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); fiber = next_fiber; } } input += input_incr; bytes_matched += character_size; if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched) { FAIL_ON_ERROR_WITH_CLEANUP( _yr_re_fiber_create(&storage->fiber_pool, &fiber), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); fiber->ip = re_code; _yr_re_fiber_append(&fibers, fiber); FAIL_ON_ERROR_WITH_CLEANUP( _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber), _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool)); } } return ERROR_SUCCESS; } int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { if (bytes_matched + i >= max_bytes_matched) break; next_input = input + i * input_incr; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; bytes_matched = yr_min(bytes_matched, max_bytes_matched); ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; } void _yr_re_print_node( RE_NODE* re_node) { int i; if (re_node == NULL) return; switch(re_node->type) { case RE_NODE_ALT: printf("Alt("); _yr_re_print_node(re_node->left); printf(", "); _yr_re_print_node(re_node->right); printf(")"); break; case RE_NODE_CONCAT: printf("Cat("); _yr_re_print_node(re_node->left); printf(", "); _yr_re_print_node(re_node->right); printf(")"); break; case RE_NODE_STAR: printf("Star("); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_PLUS: printf("Plus("); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_LITERAL: printf("Lit(%02X)", re_node->value); break; case RE_NODE_MASKED_LITERAL: printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask); break; case RE_NODE_WORD_CHAR: printf("WordChar"); break; case RE_NODE_NON_WORD_CHAR: printf("NonWordChar"); break; case RE_NODE_SPACE: printf("Space"); break; case RE_NODE_NON_SPACE: printf("NonSpace"); break; case RE_NODE_DIGIT: printf("Digit"); break; case RE_NODE_NON_DIGIT: printf("NonDigit"); break; case RE_NODE_ANY: printf("Any"); break; case RE_NODE_RANGE: printf("Range(%d-%d, ", re_node->start, re_node->end); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_CLASS: printf("Class("); for (i = 0; i < 256; i++) if (CHAR_IN_CLASS(i, re_node->class_vector)) printf("%02X,", i); printf(")"); break; default: printf("???"); break; } } void yr_re_print( RE_AST* re_ast) { _yr_re_print_node(re_ast->root_node); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3396_0
crossvul-cpp_data_good_4219_0
/* * oracle.c * * Copyright (C) 2013 Remy Mudingay <mudingay@ill.fr> * * This module is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This module 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. * If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_ORACLE #include "ndpi_api.h" static void ndpi_int_oracle_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_ORACLE, NDPI_PROTOCOL_UNKNOWN); } void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n"); if(packet->tcp != NULL) { sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest); NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n"); /* Oracle Database 9g,10g,11g */ if ((dport == 1521 || sport == 1521) && (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00)) || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) && (packet->payload[1] != 0x00) && (packet->payload[2] == 0x00) && (packet->payload[3] == 0x00)))) { NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); ndpi_int_oracle_add_connection(ndpi_struct, flow); } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 && packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 && packet->payload[3] == 0x00 ) { NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); ndpi_int_oracle_add_connection(ndpi_struct, flow); } } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); } } void init_oracle_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("Oracle", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_ORACLE, ndpi_search_oracle, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_4219_0
crossvul-cpp_data_good_1014_0
/* * QLogic iSCSI Offload Driver * Copyright (c) 2016 Cavium Inc. * * This software is available under the terms of the GNU General Public License * (GPL) Version 2, available from the file COPYING in the main directory of * this source tree. */ #include "qedi_dbg.h" #include <linux/vmalloc.h> void qedi_dbg_err(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (likely(qedi) && likely(qedi->pdev)) pr_err("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_err("[0000:00:00.0]:[%s:%d]: %pV", func, line, &vaf); va_end(va); } void qedi_dbg_warn(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_WARN)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_warn("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_warn("[0000:00:00.0]:[%s:%d]: %pV", func, line, &vaf); ret: va_end(va); } void qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_NOTICE)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_notice("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_notice("[0000:00:00.0]:[%s:%d]: %pV", func, line, &vaf); ret: va_end(va); } void qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line, u32 level, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & level)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_info("[0000:00:00.0]:[%s:%d]: %pV", func, line, &vaf); ret: va_end(va); } int qedi_create_sysfs_attr(struct Scsi_Host *shost, struct sysfs_bin_attrs *iter) { int ret = 0; for (; iter->name; iter++) { ret = sysfs_create_bin_file(&shost->shost_gendev.kobj, iter->attr); if (ret) pr_err("Unable to create sysfs %s attr, err(%d).\n", iter->name, ret); } return ret; } void qedi_remove_sysfs_attr(struct Scsi_Host *shost, struct sysfs_bin_attrs *iter) { for (; iter->name; iter++) sysfs_remove_bin_file(&shost->shost_gendev.kobj, iter->attr); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1014_0
crossvul-cpp_data_bad_261_0
/* * Copyright (c) 2000 William C. Fenner. * All rights reserved. * * Kevin Steves <ks@hp.se> July 2000 * Modified to: * - print version, type string and packet length * - print IP address count if > 1 (-v) * - verify checksum (-v) * - print authentication string (-v) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * The name of William C. Fenner may not be used to endorse or * promote products derived from this software without specific prior * written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. */ /* \summary: Virtual Router Redundancy Protocol (VRRP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ip.h" #include "ipproto.h" /* * RFC 2338 (VRRP v2): * * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Version| Type | Virtual Rtr ID| Priority | Count IP Addrs| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Auth Type | Adver Int | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IP Address (1) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IP Address (n) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Authentication Data (1) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Authentication Data (2) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * * RFC 5798 (VRRP v3): * * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IPv4 Fields or IPv6 Fields | * ... ... * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Version| Type | Virtual Rtr ID| Priority |Count IPvX Addr| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |(rsvd) | Max Adver Int | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * + + * | IPvX Address(es) | * + + * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ /* Type */ #define VRRP_TYPE_ADVERTISEMENT 1 static const struct tok type2str[] = { { VRRP_TYPE_ADVERTISEMENT, "Advertisement" }, { 0, NULL } }; /* Auth Type */ #define VRRP_AUTH_NONE 0 #define VRRP_AUTH_SIMPLE 1 #define VRRP_AUTH_AH 2 static const struct tok auth2str[] = { { VRRP_AUTH_NONE, "none" }, { VRRP_AUTH_SIMPLE, "simple" }, { VRRP_AUTH_AH, "ah" }, { 0, NULL } }; void vrrp_print(netdissect_options *ndo, register const u_char *bp, register u_int len, register const u_char *bp2, int ttl) { int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */ const char *type_s; ND_TCHECK(bp[0]); version = (bp[0] & 0xf0) >> 4; type = bp[0] & 0x0f; type_s = tok2str(type2str, "unknown type (%u)", type); ND_PRINT((ndo, "VRRPv%u, %s", version, type_s)); if (ttl != 255) ND_PRINT((ndo, ", (ttl %u)", ttl)); if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT) return; ND_TCHECK(bp[2]); ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2])); ND_TCHECK(bp[5]); if (version == 2) { auth_type = bp[4]; ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type))); ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len)); } else { /* version == 3 */ uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5]; ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len)); } if (ndo->ndo_vflag) { int naddrs = bp[3]; int i; char c; if (version == 2 && ND_TTEST2(bp[0], len)) { struct cksum_vec vec[1]; vec[0].ptr = bp; vec[0].len = len; if (in_cksum(vec, 1)) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } if (version == 3 && ND_TTEST2(bp[0], len)) { uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp, len, len, IPPROTO_VRRP); if (cksum) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } ND_PRINT((ndo, ", addrs")); if (naddrs > 1) ND_PRINT((ndo, "(%d)", naddrs)); ND_PRINT((ndo, ":")); c = ' '; bp += 8; for (i = 0; i < naddrs; i++) { ND_TCHECK(bp[3]); ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp))); c = ','; bp += 4; } if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */ ND_TCHECK(bp[7]); ND_PRINT((ndo, " auth \"")); if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); } } return; trunc: ND_PRINT((ndo, "[|vrrp]")); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_261_0
crossvul-cpp_data_bad_2935_0
/* radare - LGPL - Copyright 2012-2016 - pancake, Fedor Sakharov */ #define D0 if(1) #define D1 if(1) #include <errno.h> #define DWARF_DUMP 0 #if DWARF_DUMP #define DBGFD stdout #else #define DBGFD NULL #endif #include <r_bin.h> #include <r_bin_dwarf.h> #include <r_core.h> #define STANDARD_OPERAND_COUNT_DWARF2 9 #define STANDARD_OPERAND_COUNT_DWARF3 12 #define R_BIN_DWARF_INFO 1 #define READ(x,y) ((x + sizeof (y) < buf_end)? *((y*)x): 0); x += sizeof (y) static const char *dwarf_tag_name_encodings[] = { [DW_TAG_array_type] = "DW_TAG_array_type", [DW_TAG_class_type] = "DW_TAG_class_type", [DW_TAG_entry_point] = "DW_TAG_entry_point", [DW_TAG_enumeration_type] = "DW_TAG_enumeration_type", [DW_TAG_formal_parameter] = "DW_TAG_formal_parameter", [DW_TAG_imported_declaration] = "DW_TAG_imported_declaration", [DW_TAG_label] = "DW_TAG_label", [DW_TAG_lexical_block] = "DW_TAG_lexical_block", [DW_TAG_member] = "DW_TAG_member", [DW_TAG_pointer_type] = "DW_TAG_pointer_type", [DW_TAG_reference_type] = "DW_TAG_reference_type", [DW_TAG_compile_unit] = "DW_TAG_compile_unit", [DW_TAG_string_type] = "DW_TAG_string_type", [DW_TAG_structure_type] = "DW_TAG_structure_type", [DW_TAG_subroutine_type] = "DW_TAG_subroutine_type", [DW_TAG_typedef] = "DW_TAG_typedef", [DW_TAG_union_type] = "DW_TAG_union_type", [DW_TAG_unspecified_parameters] = "DW_TAG_unspecified_parameters", [DW_TAG_variant] = "DW_TAG_variant", [DW_TAG_common_block] = "DW_TAG_common_block", [DW_TAG_common_inclusion] = "DW_TAG_common_inclusion", [DW_TAG_inheritance] = "DW_TAG_inheritance", [DW_TAG_inlined_subroutine] = "DW_TAG_inlined_subroutine", [DW_TAG_module] = "DW_TAG_module", [DW_TAG_ptr_to_member_type] = "DW_TAG_ptr_to_member_type", [DW_TAG_set_type] = "DW_TAG_set_type", [DW_TAG_subrange_type] = "DW_TAG_subrange_type", [DW_TAG_with_stmt] = "DW_TAG_with_stmt", [DW_TAG_access_declaration] = "DW_TAG_access_declaration", [DW_TAG_base_type] = "DW_TAG_base_type", [DW_TAG_catch_block] = "DW_TAG_catch_block", [DW_TAG_const_type] = "DW_TAG_const_type", [DW_TAG_constant] = "DW_TAG_constant", [DW_TAG_enumerator] = "DW_TAG_enumerator", [DW_TAG_file_type] = "DW_TAG_file_type", [DW_TAG_friend] = "DW_TAG_friend", [DW_TAG_namelist] = "DW_TAG_namelist", [DW_TAG_namelist_item] = "DW_TAG_namelist_item", [DW_TAG_packed_type] = "DW_TAG_packed_type", [DW_TAG_subprogram] = "DW_TAG_subprogram", [DW_TAG_template_type_param] = "DW_TAG_template_type_param", [DW_TAG_template_value_param] = "DW_TAG_template_value_param", [DW_TAG_template_alias] = "DW_TAG_template_alias", [DW_TAG_thrown_type] = "DW_TAG_thrown_type", [DW_TAG_try_block] = "DW_TAG_try_block", [DW_TAG_variant_part] = "DW_TAG_variant_part", [DW_TAG_variable] = "DW_TAG_variable", [DW_TAG_volatile_type] = "DW_TAG_volatile_type" }; static const char *dwarf_attr_encodings[] = { [DW_AT_sibling] = "DW_AT_siblings", [DW_AT_location] = "DW_AT_location", [DW_AT_name] = "DW_AT_name", [DW_AT_ordering] = "DW_AT_ordering", [DW_AT_byte_size] = "DW_AT_byte_size", [DW_AT_bit_size] = "DW_AT_bit_size", [DW_AT_stmt_list] = "DW_AT_stmt_list", [DW_AT_low_pc] = "DW_AT_low_pc", [DW_AT_high_pc] = "DW_AT_high_pc", [DW_AT_language] = "DW_AT_language", [DW_AT_discr] = "DW_AT_discr", [DW_AT_discr_value] = "DW_AT_discr_value", [DW_AT_visibility] = "DW_AT_visibility", [DW_AT_import] = "DW_AT_import", [DW_AT_string_length] = "DW_AT_string_length", [DW_AT_common_reference] = "DW_AT_common_reference", [DW_AT_comp_dir] = "DW_AT_comp_dir", [DW_AT_const_value] = "DW_AT_const_value", [DW_AT_containing_type] = "DW_AT_containig_type", [DW_AT_default_value] = "DW_AT_default_value", [DW_AT_inline] = "DW_AT_inline", [DW_AT_is_optional] = "DW_AT_is_optional", [DW_AT_lower_bound] = "DW_AT_lower_bound", [DW_AT_producer] = "DW_AT_producer", [DW_AT_prototyped] = "DW_AT_prototyped", [DW_AT_return_addr] = "DW_AT_return_addr", [DW_AT_start_scope] = "DW_AT_start_scope", [DW_AT_stride_size] = "DW_AT_stride_size", [DW_AT_upper_bound] = "DW_AT_upper_bound", [DW_AT_abstract_origin] = "DW_AT_abstract_origin", [DW_AT_accessibility] = "DW_AT_accessibility", [DW_AT_address_class] = "DW_AT_address_class", [DW_AT_artificial] = "DW_AT_artificial", [DW_AT_base_types] = "DW_AT_base_types", [DW_AT_calling_convention] = "DW_AT_calling_convention", [DW_AT_count] = "DW_AT_count", [DW_AT_data_member_location] = "DW_AT_data_member_location", [DW_AT_decl_column] = "DW_AT_decl_column", [DW_AT_decl_file] = "DW_AT_decl_file", [DW_AT_decl_line] = "DW_AT_decl_line", [DW_AT_declaration] = "DW_AT_declaration", [DW_AT_discr_list] = "DW_AT_discr_list", [DW_AT_encoding] = "DW_AT_encoding", [DW_AT_external] = "DW_AT_external", [DW_AT_frame_base] = "DW_AT_frame_base", [DW_AT_friend] = "DW_AT_friend", [DW_AT_identifier_case] = "DW_AT_identifier_case", [DW_AT_macro_info] = "DW_AT_macro_info", [DW_AT_namelist_item] = "DW_AT_namelist_item", [DW_AT_priority] = "DW_AT_priority", [DW_AT_segment] = "DW_AT_segment", [DW_AT_specification] = "DW_AT_specification", [DW_AT_static_link] = "DW_AT_static_link", [DW_AT_type] = "DW_AT_type", [DW_AT_use_location] = "DW_AT_use_location", [DW_AT_variable_parameter] = "DW_AT_variable_parameter", [DW_AT_virtuality] = "DW_AT_virtuality", [DW_AT_vtable_elem_location] = "DW_AT_vtable_elem_location" }; static const char *dwarf_attr_form_encodings[] = { [DW_FORM_addr] = "DW_FORM_addr", [DW_FORM_block2] = "DW_FORM_block2", [DW_FORM_block4] = "DW_FORM_block4", [DW_FORM_data2] = "DW_FORM_data2", [DW_FORM_data4] = "DW_FORM_data4", [DW_FORM_data8] = "DW_FORM_data8", [DW_FORM_string] = "DW_FORM_string", [DW_FORM_block] = "DW_FORM_block", [DW_FORM_block1] = "DW_FORM_block1", [DW_FORM_data1] = "DW_FORM_data1", [DW_FORM_flag] = "DW_FORM_flag", [DW_FORM_sdata] = "DW_FORM_sdata", [DW_FORM_strp] = "DW_FORM_strp", [DW_FORM_udata] = "DW_FORM_udata", [DW_FORM_ref_addr] = "DW_FORM_ref_addr", [DW_FORM_ref1] = "DW_FORM_ref1", [DW_FORM_ref2] = "DW_FORM_ref2", [DW_FORM_ref4] = "DW_FORM_ref4", [DW_FORM_ref8] = "DW_FORM_ref8", [DW_FORM_ref_udata] = "DW_FORM_ref_udata", [DW_FORM_indirect] = "DW_FORM_indirect" }; static const char *dwarf_langs[] = { [DW_LANG_C89] = "C89", [DW_LANG_C] = "C", [DW_LANG_Ada83] = "Ada83", [DW_LANG_C_plus_plus] = "C++", [DW_LANG_Cobol74] = "Cobol74", [DW_LANG_Cobol85] = "Cobol85", [DW_LANG_Fortran77] = "Fortran77", [DW_LANG_Fortran90] = "Fortran90", [DW_LANG_Pascal83] = "Pascal83", [DW_LANG_Modula2] = "Modula2", [DW_LANG_Java] = "Java", [DW_LANG_C99] = "C99", [DW_LANG_Ada95] = "Ada95", [DW_LANG_Fortran95] = "Fortran95", [DW_LANG_PLI] = "PLI", [DW_LANG_ObjC] = "ObjC", [DW_LANG_ObjC_plus_plus] = "ObjC_plus_plus", [DW_LANG_UPC] = "UPC", [DW_LANG_D] = "D", [DW_LANG_Python] = "Python", [DW_LANG_Rust] = "Rust", [DW_LANG_C11] = "C11", [DW_LANG_Swift] = "Swift", [DW_LANG_Julia] = "Julia", [DW_LANG_Dylan] = "Dylan", [DW_LANG_C_plus_plus_14] = "C++14", [DW_LANG_Fortran03] = "Fortran03", [DW_LANG_Fortran08] = "Fortran08" }; static int add_sdb_include_dir(Sdb *s, const char *incl, int idx) { if (!s || !incl) return false; return sdb_array_set (s, "includedirs", idx, incl, 0); } static const ut8 *r_bin_dwarf_parse_lnp_header ( RBinFile *bf, const ut8 *buf, const ut8 *buf_end, RBinDwarfLNPHeader *hdr, FILE *f, int mode) { int i; Sdb *s; size_t count; const ut8 *tmp_buf = NULL; if (!hdr || !bf || !buf) return NULL; hdr->unit_length.part1 = READ (buf, ut32); if (hdr->unit_length.part1 == DWARF_INIT_LEN_64) { hdr->unit_length.part2 = READ (buf, ut32); } s = sdb_new (NULL, NULL, 0); hdr->version = READ (buf, ut16); if (hdr->unit_length.part1 == DWARF_INIT_LEN_64) { hdr->header_length = READ (buf, ut64); } else { hdr->header_length = READ (buf, ut32); } if (buf_end-buf < 8) { sdb_free (s); return NULL; } hdr->min_inst_len = READ (buf, ut8); //hdr->max_ops_per_inst = READ (buf, ut8); hdr->file_names = NULL; hdr->default_is_stmt = READ (buf, ut8); hdr->line_base = READ (buf, char); hdr->line_range = READ (buf, ut8); hdr->opcode_base = READ (buf, ut8); if (f) { fprintf (f, "DWARF LINE HEADER\n"); fprintf (f, " total_length: %d\n", hdr->unit_length.part1); fprintf (f, " version: %d\n", hdr->version); fprintf (f, " header_length: : %"PFMT64d"\n", hdr->header_length); fprintf (f, " mininstlen: %d\n", hdr->min_inst_len); fprintf (f, " is_stmt: %d\n", hdr->default_is_stmt); fprintf (f, " line_base: %d\n", hdr->line_base); fprintf (f, " line_range: %d\n", hdr->line_range); fprintf (f, " opcode_base: %d\n", hdr->opcode_base); } if (hdr->opcode_base>0) { hdr->std_opcode_lengths = calloc(sizeof(ut8), hdr->opcode_base); for (i = 1; i <= hdr->opcode_base - 1; i++) { if (buf+2>buf_end) break; hdr->std_opcode_lengths[i] = READ (buf, ut8); if (f) { fprintf (f, " op %d %d\n", i, hdr->std_opcode_lengths[i]); } } } else { hdr->std_opcode_lengths = NULL; } i = 0; while (buf+1 < buf_end) { int maxlen = R_MIN ((size_t)(buf_end-buf)-1, 0xfff); int len = r_str_nlen ((const char*)buf, maxlen); char *str = r_str_ndup ((const char *)buf, len); if (len<1 || len >= 0xfff) { buf += 1; free (str); break; } if (*str != '/' && *str != '.') { // no more paths in here free (str); break; } if (f) { fprintf (f, "INCLUDEDIR (%s)\n", str); } add_sdb_include_dir (s, str, i); free (str); i++; buf += len + 1; } tmp_buf = buf; count = 0; for (i = 0; i < 2; i++) { while (buf+1<buf_end) { const char *filename = (const char *)buf; int maxlen = R_MIN ((size_t)(buf_end-buf-1), 0xfff); ut64 id_idx, mod_time, file_len; size_t namelen, len = r_str_nlen (filename, maxlen); if (!len) { buf++; break; } buf += len + 1; if (buf>=buf_end) { buf = NULL; goto beach; } buf = r_uleb128 (buf, buf_end-buf, &id_idx); if (buf>=buf_end) { buf = NULL; goto beach; } buf = r_uleb128 (buf, buf_end-buf, &mod_time); if (buf>=buf_end) { buf = NULL; goto beach; } buf = r_uleb128 (buf, buf_end-buf, &file_len); if (buf>=buf_end) { buf = NULL; goto beach; } if (i) { char *include_dir = NULL, *comp_dir = NULL; char *allocated_id = NULL; if (id_idx > 0) { include_dir = sdb_array_get (s, "includedirs", id_idx - 1, 0); if (include_dir && include_dir[0] != '/') { comp_dir = sdb_get (bf->sdb_addrinfo, "DW_AT_comp_dir", 0); if (comp_dir) { allocated_id = calloc (1, strlen (comp_dir) + strlen (include_dir) + 8); snprintf (allocated_id, strlen (comp_dir) + strlen (include_dir) + 8, "%s/%s/", comp_dir, include_dir); include_dir = allocated_id; } } } else { include_dir = sdb_get (bf->sdb_addrinfo, "DW_AT_comp_dir", 0); if (!include_dir) include_dir = "./"; } namelen = len + (include_dir?strlen (include_dir):0) + 8; if (hdr->file_names) { hdr->file_names[count].name = calloc (sizeof(char), namelen); snprintf (hdr->file_names[count].name, namelen - 1, "%s/%s", include_dir? include_dir : "", filename); hdr->file_names[count].name[namelen - 1] = '\0'; free (allocated_id); hdr->file_names[count].id_idx = id_idx; hdr->file_names[count].mod_time = mod_time; hdr->file_names[count].file_len = file_len; } } count++; if (f && i) { fprintf (f, "FILE (%s)\n", filename); fprintf (f, "| dir idx %"PFMT64d"\n", id_idx); fprintf (f, "| lastmod %"PFMT64d"\n", mod_time); fprintf (f, "| filelen %"PFMT64d"\n", file_len); } } if (i == 0) { if (count>0) { hdr->file_names = calloc(sizeof(file_entry), count); } else { hdr->file_names = NULL; } hdr->file_names_count = count; buf = tmp_buf; count = 0; } } beach: sdb_free (s); return buf; } static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 line, FILE *f, int mode) { const char *p; char *fileline; char offset[64]; char *offset_ptr; if (!s || !file) return; p = r_str_rchr (file, NULL, '/'); if (p) { p++; } else { p = file; } // includedirs and properly check full paths switch (mode) { case 1: case 'r': case '*': if (!f) { f = stdout; } fprintf (f, "CL %s:%d 0x%08"PFMT64x"\n", p, (int)line, addr); break; } #if 0 /* THIS IS TOO SLOW */ if (r_file_exists (file)) { p = file; } #else p = file; #endif fileline = r_str_newf ("%s|%"PFMT64d, p, line); offset_ptr = sdb_itoa (addr, offset, 16); sdb_add (s, offset_ptr, fileline, 0); sdb_add (s, fileline, offset_ptr, 0); free (fileline); } static const ut8* r_bin_dwarf_parse_ext_opcode(const RBin *a, const ut8 *obuf, size_t len, const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs, FILE *f, int mode) { // XXX - list is an unused parameter. const ut8 *buf; const ut8 *buf_end; ut8 opcode; ut64 addr; buf = obuf; st64 op_len; RBinFile *binfile = a ? a->cur : NULL; RBinObject *o = binfile ? binfile->o : NULL; ut32 addr_size = o && o->info && o->info->bits ? o->info->bits / 8 : 4; const char *filename; if (!binfile || !obuf || !hdr || !regs) return NULL; buf = r_leb128 (buf, &op_len); buf_end = buf+len; opcode = *buf++; if (f) { fprintf (f, "Extended opcode %d: ", opcode); } switch (opcode) { case DW_LNE_end_sequence: regs->end_sequence = DWARF_TRUE; if (binfile && binfile->sdb_addrinfo && hdr->file_names) { int fnidx = regs->file - 1; if (fnidx >= 0 && fnidx < hdr->file_names_count) { add_sdb_addrline(binfile->sdb_addrinfo, regs->address, hdr->file_names[fnidx].name, regs->line, f, mode); } } if (f) { fprintf (f, "End of Sequence\n"); } break; case DW_LNE_set_address: if (addr_size == 8) { addr = READ (buf, ut64); } else { addr = READ (buf, ut32); } regs->address = addr; if (f) { fprintf (f, "set Address to 0x%"PFMT64x"\n", addr); } break; case DW_LNE_define_file: filename = (const char*)buf; if (f) { fprintf (f, "define_file\n"); fprintf (f, "filename %s\n", filename); } buf += (strlen (filename) + 1); ut64 dir_idx; if (buf+1 < buf_end) buf = r_uleb128 (buf, ST32_MAX, &dir_idx); break; case DW_LNE_set_discriminator: buf = r_uleb128 (buf, ST32_MAX, &addr); if (f) { fprintf (f, "set Discriminator to %"PFMT64d"\n", addr); } regs->discriminator = addr; break; default: if (f) { fprintf (f, "Unexpeced opcode %d\n", opcode); } break; } return buf; } static const ut8* r_bin_dwarf_parse_spec_opcode( const RBin *a, const ut8 *obuf, size_t len, const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs, ut8 opcode, FILE *f, int mode) { // XXX - list is not used const ut8 *buf = obuf; ut8 adj_opcode = 0; ut64 advance_adr; RBinFile *binfile = a ? a->cur : NULL; if (!obuf || !hdr || !regs) { return NULL; } adj_opcode = opcode - hdr->opcode_base; if (!hdr->line_range) { // line line-range information. move away return NULL; } advance_adr = adj_opcode / hdr->line_range; regs->address += advance_adr; regs->line += hdr->line_base + (adj_opcode % hdr->line_range); if (f) { fprintf (f, "Special opcode %d: ", adj_opcode); fprintf (f, "advance Address by %"PFMT64d" to %"PFMT64x" and Line by %d to %"PFMT64d"\n", advance_adr, regs->address, hdr->line_base + (adj_opcode % hdr->line_range), regs->line); } if (binfile && binfile->sdb_addrinfo && hdr->file_names) { int idx = regs->file -1; if (idx >= 0 && idx < hdr->file_names_count) { add_sdb_addrline (binfile->sdb_addrinfo, regs->address, hdr->file_names[idx].name, regs->line, f, mode); } } regs->basic_block = DWARF_FALSE; regs->prologue_end = DWARF_FALSE; regs->epilogue_begin = DWARF_FALSE; regs->discriminator = 0; return buf; } static const ut8* r_bin_dwarf_parse_std_opcode( const RBin *a, const ut8 *obuf, size_t len, const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs, ut8 opcode, FILE *f, int mode) { const ut8* buf = obuf; const ut8* buf_end = obuf + len; ut64 addr = 0LL; st64 sbuf; ut8 adj_opcode; ut64 op_advance; ut16 operand; RBinFile *binfile = a ? a->cur : NULL; if (!binfile || !hdr || !regs || !obuf) { return NULL; } switch (opcode) { case DW_LNS_copy: if (f) { fprintf (f, "Copy\n"); } if (binfile && binfile->sdb_addrinfo && hdr->file_names) { int fnidx = regs->file - 1; if (fnidx >= 0 && fnidx < hdr->file_names_count) { add_sdb_addrline (binfile->sdb_addrinfo, regs->address, hdr->file_names[fnidx].name, regs->line, f, mode); } } regs->basic_block = DWARF_FALSE; break; case DW_LNS_advance_pc: buf = r_uleb128 (buf, ST32_MAX, &addr); regs->address += addr * hdr->min_inst_len; if (f) { fprintf (f, "Advance PC by %"PFMT64d" to 0x%"PFMT64x"\n", addr * hdr->min_inst_len, regs->address); } break; case DW_LNS_advance_line: buf = r_leb128(buf, &sbuf); regs->line += sbuf; if (f) { fprintf (f, "Advance line by %"PFMT64d", to %"PFMT64d"\n", sbuf, regs->line); } break; case DW_LNS_set_file: buf = r_uleb128 (buf, ST32_MAX, &addr); if (f) { fprintf (f, "Set file to %"PFMT64d"\n", addr); } regs->file = addr; break; case DW_LNS_set_column: buf = r_uleb128 (buf, ST32_MAX, &addr); if (f) { fprintf (f, "Set column to %"PFMT64d"\n", addr); } regs->column = addr; break; case DW_LNS_negate_stmt: regs->is_stmt = regs->is_stmt ? DWARF_FALSE : DWARF_TRUE; if (f) { fprintf (f, "Set is_stmt to %d\n", regs->is_stmt); } break; case DW_LNS_set_basic_block: if (f) { fprintf (f, "set_basic_block\n"); } regs->basic_block = DWARF_TRUE; break; case DW_LNS_const_add_pc: adj_opcode = 255 - hdr->opcode_base; if (hdr->line_range > 0) { op_advance = adj_opcode / hdr->line_range; } else { op_advance = 0; } regs->address += op_advance; if (f) { fprintf (f, "Advance PC by constant %"PFMT64d" to 0x%"PFMT64x"\n", op_advance, regs->address); } break; case DW_LNS_fixed_advance_pc: operand = READ (buf, ut16); regs->address += operand; if (f) { fprintf (f,"Fixed advance pc to %"PFMT64d"\n", regs->address); } break; case DW_LNS_set_prologue_end: regs->prologue_end = ~0; if (f) { fprintf (f, "set_prologue_end\n"); } break; case DW_LNS_set_epilogue_begin: regs->epilogue_begin = ~0; if (f) { fprintf (f, "set_epilogue_begin\n"); } break; case DW_LNS_set_isa: buf = r_uleb128 (buf, ST32_MAX, &addr); regs->isa = addr; if (f) { fprintf (f, "set_isa\n"); } break; default: if (f) { fprintf (f, "Unexpected opcode\n"); } break; } return buf; } static const ut8* r_bin_dwarf_parse_opcodes(const RBin *a, const ut8 *obuf, size_t len, const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs, FILE *f, int mode) { const ut8 *buf, *buf_end; ut8 opcode, ext_opcode; if (!a || !obuf || len < 8) { return NULL; } buf = obuf; buf_end = obuf + len; while (buf && buf + 1 < buf_end) { opcode = *buf++; len--; if (!opcode) { ext_opcode = *buf; buf = r_bin_dwarf_parse_ext_opcode (a, buf, len, hdr, regs, f, mode); if (ext_opcode == DW_LNE_end_sequence) { break; } } else if (opcode >= hdr->opcode_base) { buf = r_bin_dwarf_parse_spec_opcode (a, buf, len, hdr, regs, opcode, f, mode); } else { buf = r_bin_dwarf_parse_std_opcode (a, buf, len, hdr, regs, opcode, f, mode); } len = (int)(buf_end - buf); } return buf; } static void r_bin_dwarf_set_regs_default (const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs) { regs->address = 0; regs->file = 1; regs->line = 1; regs->column = 0; regs->is_stmt = hdr->default_is_stmt; regs->basic_block = DWARF_FALSE; regs->end_sequence = DWARF_FALSE; } R_API int r_bin_dwarf_parse_line_raw2(const RBin *a, const ut8 *obuf, size_t len, int mode) { RBinDwarfLNPHeader hdr = {{0}}; const ut8 *buf = NULL, *buf_tmp = NULL, *buf_end = NULL; RBinDwarfSMRegisters regs; int tmplen; FILE *f = NULL; RBinFile *binfile = a ? a->cur : NULL; if (!binfile || !obuf) { return false; } if (mode == R_CORE_BIN_PRINT) { f = stdout; } buf = obuf; buf_end = obuf + len; while (buf + 1 < buf_end) { buf_tmp = buf; buf = r_bin_dwarf_parse_lnp_header (a->cur, buf, buf_end, &hdr, f, mode); if (!buf) { return false; } r_bin_dwarf_set_regs_default (&hdr, &regs); tmplen = (int)(buf_end - buf); tmplen = R_MIN (tmplen, 4 + hdr.unit_length.part1); if (tmplen < 1) { break; } if (!r_bin_dwarf_parse_opcodes (a, buf, tmplen, &hdr, &regs, f, mode)) { break; } buf = buf_tmp + tmplen; len = (int)(buf_end - buf); } return true; } #define READ_BUF(x,y) if (idx+sizeof(y)>=len) { return false;} \ x=*(y*)buf; idx+=sizeof(y);buf+=sizeof(y) R_API int r_bin_dwarf_parse_aranges_raw(const ut8 *obuf, int len, FILE *f) { ut32 length, offset; ut16 version; ut32 debug_info_offset; ut8 address_size, segment_size; const ut8 *buf = obuf; int idx = 0; if (!buf || len< 4) { return false; } READ_BUF (length, ut32); if (f) { printf("parse_aranges\n"); printf("length 0x%x\n", length); } if (idx+12>=len) return false; READ_BUF (version, ut16); if (f) { printf("Version %d\n", version); } READ_BUF (debug_info_offset, ut32); if (f) { fprintf (f, "Debug info offset %d\n", debug_info_offset); } READ_BUF (address_size, ut8); if (f) { fprintf (f, "address size %d\n", (int)address_size); } READ_BUF (segment_size, ut8); if (f) { fprintf (f, "segment size %d\n", (int)segment_size); } offset = segment_size + address_size * 2; if (offset) { ut64 n = (((ut64) (size_t)buf / offset) + 1) * offset - ((ut64)(size_t)buf); if (idx+n>=len) { return false; } buf += n; idx += n; } while ((buf - obuf) < len) { ut64 adr, length; if ((idx+8)>=len) { break; } READ_BUF (adr, ut64); READ_BUF (length, ut64); if (f) printf("length 0x%"PFMT64x" address 0x%"PFMT64x"\n", length, adr); } return 0; } static int r_bin_dwarf_init_debug_info(RBinDwarfDebugInfo *inf) { if (!inf) { return -1; } inf->comp_units = calloc (sizeof (RBinDwarfCompUnit), DEBUG_INFO_CAPACITY); // XXX - should we be using error codes? if (!inf->comp_units) { return -ENOMEM; } inf->capacity = DEBUG_INFO_CAPACITY; inf->length = 0; return true; } static int r_bin_dwarf_init_die(RBinDwarfDIE *die) { if (!die) { return -EINVAL; } die->attr_values = calloc (sizeof (RBinDwarfAttrValue), 8); if (!die->attr_values) { return -ENOMEM; } die->capacity = 8; die->length = 0; return 0; } static int r_bin_dwarf_expand_die(RBinDwarfDIE* die) { RBinDwarfAttrValue *tmp = NULL; if (!die || die->capacity == 0) { return -EINVAL; } if (die->capacity != die->length) { return -EINVAL; } tmp = (RBinDwarfAttrValue*)realloc (die->attr_values, die->capacity * 2 * sizeof (RBinDwarfAttrValue)); if (!tmp) { return -ENOMEM; } memset ((ut8*)tmp + die->capacity, 0, die->capacity); die->attr_values = tmp; die->capacity *= 2; return 0; } static int r_bin_dwarf_init_comp_unit(RBinDwarfCompUnit *cu) { if (!cu) { return -EINVAL; } cu->dies = calloc (sizeof (RBinDwarfDIE), COMP_UNIT_CAPACITY); if (!cu->dies) { return -ENOMEM; } cu->capacity = COMP_UNIT_CAPACITY; cu->length = 0; return 0; } static int r_bin_dwarf_expand_cu(RBinDwarfCompUnit *cu) { RBinDwarfDIE *tmp; if (!cu || cu->capacity == 0 || cu->capacity != cu->length) { return -EINVAL; } tmp = (RBinDwarfDIE*)realloc(cu->dies, cu->capacity * 2 * sizeof(RBinDwarfDIE)); if (!tmp) { return -ENOMEM; } memset ((ut8*)tmp + cu->capacity, 0, cu->capacity); cu->dies = tmp; cu->capacity *= 2; return 0; } static int r_bin_dwarf_init_abbrev_decl(RBinDwarfAbbrevDecl *ad) { if (!ad) { return -EINVAL; } ad->specs = calloc (sizeof( RBinDwarfAttrSpec), ABBREV_DECL_CAP); if (!ad->specs) { return -ENOMEM; } ad->capacity = ABBREV_DECL_CAP; ad->length = 0; return 0; } static int r_bin_dwarf_expand_abbrev_decl(RBinDwarfAbbrevDecl *ad) { RBinDwarfAttrSpec *tmp; if (!ad || !ad->capacity || ad->capacity != ad->length) { return -EINVAL; } tmp = (RBinDwarfAttrSpec*)realloc (ad->specs, ad->capacity * 2 * sizeof (RBinDwarfAttrSpec)); if (!tmp) { return -ENOMEM; } memset ((ut8*)tmp + ad->capacity, 0, ad->capacity); ad->specs = tmp; ad->capacity *= 2; return 0; } static int r_bin_dwarf_init_debug_abbrev(RBinDwarfDebugAbbrev *da) { if (!da) { return -EINVAL; } da->decls = calloc (sizeof (RBinDwarfAbbrevDecl), DEBUG_ABBREV_CAP); if (!da->decls) { return -ENOMEM; } da->capacity = DEBUG_ABBREV_CAP; da->length = 0; return 0; } static int r_bin_dwarf_expand_debug_abbrev(RBinDwarfDebugAbbrev *da) { RBinDwarfAbbrevDecl *tmp; if (!da || da->capacity == 0 || da->capacity != da->length) { return -EINVAL; } tmp = (RBinDwarfAbbrevDecl*)realloc (da->decls, da->capacity * 2 * sizeof (RBinDwarfAbbrevDecl)); if (!tmp) { return -ENOMEM; } memset ((ut8*)tmp + da->capacity, 0, da->capacity); da->decls = tmp; da->capacity *= 2; return 0; } static void dump_r_bin_dwarf_debug_abbrev(FILE *f, RBinDwarfDebugAbbrev *da) { size_t i, j; ut64 attr_name, attr_form; if (!f || !da) { return; } for (i = 0; i < da->length; i++) { int declstag = da->decls[i].tag; fprintf (f, "Abbreviation Code %"PFMT64d" ", da->decls[i].code); if (declstag>=0 && declstag < DW_TAG_LAST) { fprintf (f, "Tag %s ", dwarf_tag_name_encodings[declstag]); } fprintf (f, "[%s]\n", da->decls[i].has_children ? "has children" : "no children"); fprintf (f, "Offset 0x%"PFMT64x"\n", da->decls[i].offset); for (j = 0; j < da->decls[i].length; j++) { attr_name = da->decls[i].specs[j].attr_name; attr_form = da->decls[i].specs[j].attr_form; if (attr_name && attr_form && attr_name <= DW_AT_vtable_elem_location && attr_form <= DW_FORM_indirect) { fprintf (f, " %s %s\n", dwarf_attr_encodings[attr_name], dwarf_attr_form_encodings[attr_form]); } } } } R_API void r_bin_dwarf_free_debug_abbrev(RBinDwarfDebugAbbrev *da) { size_t i; if (!da) return; for (i = 0; i < da->length; i++) { R_FREE (da->decls[i].specs); } R_FREE (da->decls); } static void r_bin_dwarf_free_attr_value(RBinDwarfAttrValue *val) { if (!val) { return; } switch (val->form) { case DW_FORM_strp: case DW_FORM_string: R_FREE (val->encoding.str_struct.string); break; case DW_FORM_block: case DW_FORM_block1: case DW_FORM_block2: case DW_FORM_block4: R_FREE (val->encoding.block.data); break; default: break; }; } static void r_bin_dwarf_free_die(RBinDwarfDIE *die) { size_t i; if (!die) { return; } for (i = 0; i < die->length; i++) { r_bin_dwarf_free_attr_value (&die->attr_values[i]); } R_FREE (die->attr_values); } static void r_bin_dwarf_free_comp_unit(RBinDwarfCompUnit *cu) { size_t i; if (!cu) { return; } for (i = 0; i < cu->length; i++) { if (cu->dies) { r_bin_dwarf_free_die (&cu->dies[i]); } } R_FREE (cu->dies); } static void r_bin_dwarf_free_debug_info (RBinDwarfDebugInfo *inf) { size_t i; if (!inf) { return; } for (i = 0; i < inf->length; i++) { r_bin_dwarf_free_comp_unit (&inf->comp_units[i]); } R_FREE (inf->comp_units); } static void r_bin_dwarf_dump_attr_value(const RBinDwarfAttrValue *val, FILE *f) { size_t i; if (!val || !f) { return; } switch (val->form) { case DW_FORM_addr: fprintf (f, "0x%"PFMT64x"", val->encoding.address); break; case DW_FORM_block: case DW_FORM_block1: case DW_FORM_block2: case DW_FORM_block4: fprintf (f, "%"PFMT64u" byte block:", val->encoding.block.length); for (i = 0; i < val->encoding.block.length; i++) { fprintf (f, "%02x", val->encoding.block.data[i]); } break; case DW_FORM_data1: case DW_FORM_data2: case DW_FORM_data4: case DW_FORM_data8: fprintf (f, "%"PFMT64u"", val->encoding.data); if (val->name == DW_AT_language) { fprintf (f, " (%s)", dwarf_langs[val->encoding.data]); } break; case DW_FORM_strp: fprintf (f, "(indirect string, offset: 0x%"PFMT64x"): ", val->encoding.str_struct.offset); case DW_FORM_string: if (val->encoding.str_struct.string) { fprintf (f, "%s", val->encoding.str_struct.string); } else { fprintf (f, "No string found"); } break; case DW_FORM_flag: fprintf (f, "%u", val->encoding.flag); break; case DW_FORM_sdata: fprintf (f, "%"PFMT64d"", val->encoding.sdata); break; case DW_FORM_udata: fprintf (f, "%"PFMT64u"", val->encoding.data); break; case DW_FORM_ref_addr: fprintf (f, "<0x%"PFMT64x">", val->encoding.reference); break; case DW_FORM_ref1: case DW_FORM_ref2: case DW_FORM_ref4: case DW_FORM_ref8: fprintf (f, "<0x%"PFMT64x">", val->encoding.reference); break; default: fprintf (f, "Unknown attr value form %"PFMT64d"\n", val->form); }; } static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) continue; if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } } static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len, RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value, const RBinDwarfCompUnitHdr *hdr, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf; const ut8 *buf_end = obuf + obuf_len; size_t j; if (!spec || !value || !hdr || !obuf || obuf_len < 0) { return NULL; } value->form = spec->attr_form; value->name = spec->attr_name; value->encoding.block.data = NULL; value->encoding.str_struct.string = NULL; value->encoding.str_struct.offset = 0; switch (spec->attr_form) { case DW_FORM_addr: switch (hdr->pointer_size) { case 1: value->encoding.address = READ (buf, ut8); break; case 2: value->encoding.address = READ (buf, ut16); break; case 4: value->encoding.address = READ (buf, ut32); break; case 8: value->encoding.address = READ (buf, ut64); break; default: eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size); return NULL; } break; case DW_FORM_block2: value->encoding.block.length = READ (buf, ut16); if (value->encoding.block.length > 0) { value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block4: value->encoding.block.length = READ (buf, ut32); if (value->encoding.block.length > 0) { ut8 *data = calloc (sizeof (ut8), value->encoding.block.length); if (data) { for (j = 0; j < value->encoding.block.length; j++) { data[j] = READ (buf, ut8); } } value->encoding.block.data = data; } break; case DW_FORM_data2: value->encoding.data = READ (buf, ut16); break; case DW_FORM_data4: value->encoding.data = READ (buf, ut32); break; case DW_FORM_data8: value->encoding.data = READ (buf, ut64); break; case DW_FORM_string: value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL; buf += (strlen ((const char*)buf) + 1); break; case DW_FORM_block: buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length); if (!buf) { return NULL; } value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_block1: value->encoding.block.length = READ (buf, ut8); value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } break; case DW_FORM_flag: value->encoding.flag = READ (buf, ut8); break; case DW_FORM_sdata: buf = r_leb128 (buf, &value->encoding.sdata); break; case DW_FORM_strp: value->encoding.str_struct.offset = READ (buf, ut32); if (debug_str && value->encoding.str_struct.offset < debug_str_len) { value->encoding.str_struct.string = strdup ( (const char *)(debug_str + value->encoding.str_struct.offset)); } else { value->encoding.str_struct.string = NULL; } break; case DW_FORM_udata: { ut64 ndata = 0; const ut8 *data = (const ut8*)&ndata; buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata); memcpy (&value->encoding.data, data, sizeof (value->encoding.data)); value->encoding.str_struct.string = NULL; } break; case DW_FORM_ref_addr: value->encoding.reference = READ (buf, ut64); // addr size of machine break; case DW_FORM_ref1: value->encoding.reference = READ (buf, ut8); break; case DW_FORM_ref2: value->encoding.reference = READ (buf, ut16); break; case DW_FORM_ref4: value->encoding.reference = READ (buf, ut32); break; case DW_FORM_ref8: value->encoding.reference = READ (buf, ut64); break; case DW_FORM_data1: value->encoding.data = READ (buf, ut8); break; default: eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form); value->encoding.data = 0; return NULL; } return buf; } static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf, RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da, size_t offset, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7); ut64 abbr_code; size_t i; if (cu->hdr.length > debug_str_len) { //avoid oob read return NULL; } while (buf && buf < buf_end && buf >= obuf) { if (cu->length && cu->capacity == cu->length) { r_bin_dwarf_expand_cu (cu); } buf = r_uleb128 (buf, buf_end - buf, &abbr_code); if (abbr_code > da->length || !buf) { return NULL; } r_bin_dwarf_init_die (&cu->dies[cu->length]); if (!abbr_code) { cu->dies[cu->length].abbrev_code = 0; cu->length++; buf++; continue; } cu->dies[cu->length].abbrev_code = abbr_code; cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag; abbr_code += offset; if (da->capacity < abbr_code) { return NULL; } for (i = 0; i < da->decls[abbr_code - 1].length; i++) { if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) { r_bin_dwarf_expand_die (&cu->dies[cu->length]); } if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) { eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n"); break; } memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i])); buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf, &da->decls[abbr_code - 1].specs[i], &cu->dies[cu->length].attr_values[i], &cu->hdr, debug_str, debug_str_len); if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) { const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string; sdb_set (s, "DW_AT_comp_dir", name, 0); } cu->dies[cu->length].length++; } cu->length++; } return buf; } R_API int r_bin_dwarf_parse_info_raw(Sdb *s, RBinDwarfDebugAbbrev *da, const ut8 *obuf, size_t len, const ut8 *debug_str, size_t debug_str_len, int mode) { const ut8 *buf = obuf, *buf_end = obuf + len; size_t k, offset = 0; int curr_unit = 0; RBinDwarfDebugInfo di = {0}; RBinDwarfDebugInfo *inf = &di; bool ret = true; if (!da || !s || !obuf) { return false; } if (r_bin_dwarf_init_debug_info (inf) < 0) { ret = false; goto out; } while (buf < buf_end) { if (inf->length >= inf->capacity) break; if (r_bin_dwarf_init_comp_unit (&inf->comp_units[curr_unit]) < 0) { ret = false; curr_unit--; goto out_debug_info; } inf->comp_units[curr_unit].offset = buf - obuf; inf->comp_units[curr_unit].hdr.pointer_size = 0; inf->comp_units[curr_unit].hdr.abbrev_offset = 0; inf->comp_units[curr_unit].hdr.length = READ (buf, ut32); inf->comp_units[curr_unit].hdr.version = READ (buf, ut16); if (inf->comp_units[curr_unit].hdr.version != 2) { // eprintf ("DWARF: version %d is not yet supported.\n", // inf->comp_units[curr_unit].hdr.version); ret = false; goto out_debug_info; } if (inf->comp_units[curr_unit].hdr.length > len) { ret = false; goto out_debug_info; } inf->comp_units[curr_unit].hdr.abbrev_offset = READ (buf, ut32); inf->comp_units[curr_unit].hdr.pointer_size = READ (buf, ut8); inf->length++; /* Linear search FIXME */ if (da->decls->length >= da->capacity) { eprintf ("WARNING: malformed dwarf have not enough buckets for decls.\n"); } const int k_max = R_MIN (da->capacity, da->decls->length); for (k = 0; k < k_max; k++) { if (da->decls[k].offset == inf->comp_units[curr_unit].hdr.abbrev_offset) { offset = k; break; } } buf = r_bin_dwarf_parse_comp_unit (s, buf, &inf->comp_units[curr_unit], da, offset, debug_str, debug_str_len); if (!buf) { ret = false; goto out_debug_info; } curr_unit++; } if (mode == R_CORE_BIN_PRINT) { r_bin_dwarf_dump_debug_info (NULL, inf); } out_debug_info: for (; curr_unit >= 0; curr_unit--) { r_bin_dwarf_free_comp_unit (&inf->comp_units[curr_unit]); } r_bin_dwarf_free_debug_info (inf); out: return ret; } static RBinDwarfDebugAbbrev *r_bin_dwarf_parse_abbrev_raw(const ut8 *obuf, size_t len, int mode) { const ut8 *buf = obuf, *buf_end = obuf + len; ut64 tmp, spec1, spec2, offset; ut8 has_children; RBinDwarfAbbrevDecl *tmpdecl; // XXX - Set a suitable value here. if (!obuf || len < 3) { return NULL; } RBinDwarfDebugAbbrev *da = R_NEW0 (RBinDwarfDebugAbbrev); r_bin_dwarf_init_debug_abbrev (da); while (buf && buf+1 < buf_end) { offset = buf - obuf; buf = r_uleb128 (buf, (size_t)(buf_end-buf), &tmp); if (!buf || !tmp) { continue; } if (da->length == da->capacity) { r_bin_dwarf_expand_debug_abbrev(da); } tmpdecl = &da->decls[da->length]; r_bin_dwarf_init_abbrev_decl (tmpdecl); tmpdecl->code = tmp; buf = r_uleb128 (buf, (size_t)(buf_end-buf), &tmp); tmpdecl->tag = tmp; tmpdecl->offset = offset; if (buf >= buf_end) { break; } has_children = READ (buf, ut8); tmpdecl->has_children = has_children; do { if (tmpdecl->length == tmpdecl->capacity) { r_bin_dwarf_expand_abbrev_decl (tmpdecl); } buf = r_uleb128 (buf, (size_t)(buf_end - buf), &spec1); buf = r_uleb128 (buf, (size_t)(buf_end - buf), &spec2); tmpdecl->specs[tmpdecl->length].attr_name = spec1; tmpdecl->specs[tmpdecl->length].attr_form = spec2; tmpdecl->length++; } while (spec1 && spec2); da->length++; } if (mode == R_CORE_BIN_PRINT) { dump_r_bin_dwarf_debug_abbrev (stdout, da); } return da; } RBinSection *getsection(RBin *a, const char *sn) { RListIter *iter; RBinSection *section = NULL; RBinFile *binfile = a ? a->cur: NULL; RBinObject *o = binfile ? binfile->o : NULL; if ( o && o->sections) { r_list_foreach (o->sections, iter, section) { if (strstr (section->name, sn)) { return section; } } } return NULL; } R_API int r_bin_dwarf_parse_info(RBinDwarfDebugAbbrev *da, RBin *a, int mode) { ut8 *buf, *debug_str_buf = 0; int len, debug_str_len = 0, ret; RBinSection *debug_str; RBinSection *section = getsection (a, "debug_info"); RBinFile *binfile = a ? a->cur: NULL; if (binfile && section) { debug_str = getsection (a, "debug_str"); if (debug_str) { debug_str_len = debug_str->size; debug_str_buf = calloc (1, debug_str_len + 1); ret = r_buf_read_at (binfile->buf, debug_str->paddr, debug_str_buf, debug_str_len); if (!ret) { free (debug_str_buf); return false; } } len = section->size; if (len > (UT32_MAX >> 1) || len < 1) { free (debug_str_buf); return false; } buf = calloc (1, len); if (!buf) { free (debug_str_buf); return false; } if (!r_buf_read_at (binfile->buf, section->paddr, buf, len)) { free (debug_str_buf); free (buf); return false; } ret = r_bin_dwarf_parse_info_raw (binfile->sdb_addrinfo, da, buf, len, debug_str_buf, debug_str_len, mode); R_FREE (debug_str_buf); free (buf); return ret; } return false; } static RBinDwarfRow *r_bin_dwarf_row_new (ut64 addr, const char *file, int line, int col) { RBinDwarfRow *row = R_NEW0 (RBinDwarfRow); if (!row) { return NULL; } row->file = strdup (file); row->address = addr; row->line = line; row->column = 0; return row; } static void r_bin_dwarf_row_free(void *p) { RBinDwarfRow *row = (RBinDwarfRow*)p; free (row->file); free (row); } R_API RList *r_bin_dwarf_parse_line(RBin *a, int mode) { ut8 *buf; RList *list = NULL; int len, ret; RBinSection *section = getsection (a, "debug_line"); RBinFile *binfile = a ? a->cur: NULL; if (binfile && section) { len = section->size; if (len < 1) { return NULL; } buf = calloc (1, len + 1); if (!buf) { return NULL; } ret = r_buf_read_at (binfile->buf, section->paddr, buf, len); if (ret != len) { free (buf); return NULL; } list = r_list_new (); // always return empty list wtf if (!list) { free (buf); return NULL; } list->free = r_bin_dwarf_row_free; r_bin_dwarf_parse_line_raw2 (a, buf, len, mode); // k bin/cur/addrinfo/* SdbListIter *iter; SdbKv *kv; SdbList *ls = sdb_foreach_list (binfile->sdb_addrinfo, false); ls_foreach (ls, iter, kv) { if (!strncmp (kv->key, "0x", 2)) { ut64 addr; RBinDwarfRow *row; int line; char *file = strdup (kv->value); if (!file) { free (buf); ls_free (ls); r_list_free (list); return NULL; } char *tok = strchr (file, '|'); if (tok) { *tok++ = 0; line = atoi (tok); addr = r_num_math (NULL, kv->key); row = r_bin_dwarf_row_new (addr, file, line, 0); r_list_append (list, row); } free (file); } } ls_free (ls); free (buf); } return list; } R_API RList *r_bin_dwarf_parse_aranges(RBin *a, int mode) { ut8 *buf; int ret; size_t len; RBinSection *section = getsection (a, "debug_aranges"); RBinFile *binfile = a ? a->cur: NULL; if (binfile && section) { len = section->size; if (len < 1 || len > ST32_MAX) { return NULL; } buf = calloc (1, len); ret = r_buf_read_at (binfile->buf, section->paddr, buf, len); if (!ret) { free (buf); return NULL; } if (mode == R_CORE_BIN_PRINT) { r_bin_dwarf_parse_aranges_raw (buf, len, stdout); } else { r_bin_dwarf_parse_aranges_raw (buf, len, DBGFD); } free (buf); } return NULL; } R_API RBinDwarfDebugAbbrev *r_bin_dwarf_parse_abbrev(RBin *a, int mode) { ut8 *buf; size_t len; RBinSection *section = getsection (a, "debug_abbrev"); RBinDwarfDebugAbbrev *da = NULL; RBinFile *binfile = a ? a->cur: NULL; if (!section || !binfile) return NULL; if (section->size > binfile->size) { return NULL; } len = section->size; buf = calloc (1,len); r_buf_read_at (binfile->buf, section->paddr, buf, len); da = r_bin_dwarf_parse_abbrev_raw (buf, len, mode); free (buf); return da; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2935_0
crossvul-cpp_data_bad_2692_0
/* * Copyright (C) 1998 and 1999 WIDE Project. * 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ /* \summary: IPv6 DHCP printer */ /* * RFC3315: DHCPv6 * supported DHCPv6 options: * RFC3319: Session Initiation Protocol (SIP) Servers options, * RFC3633: IPv6 Prefix options, * RFC3646: DNS Configuration options, * RFC3898: Network Information Service (NIS) Configuration options, * RFC4075: Simple Network Time Protocol (SNTP) Configuration option, * RFC4242: Information Refresh Time option, * RFC4280: Broadcast and Multicast Control Servers options, * RFC5908: Network Time Protocol (NTP) Server Option for DHCPv6 * RFC6334: Dual-Stack Lite option, */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" /* lease duration */ #define DHCP6_DURATION_INFINITE 0xffffffff /* Error Values */ #define DH6ERR_FAILURE 16 #define DH6ERR_AUTHFAIL 17 #define DH6ERR_POORLYFORMED 18 #define DH6ERR_UNAVAIL 19 #define DH6ERR_OPTUNAVAIL 20 /* Message type */ #define DH6_SOLICIT 1 #define DH6_ADVERTISE 2 #define DH6_REQUEST 3 #define DH6_CONFIRM 4 #define DH6_RENEW 5 #define DH6_REBIND 6 #define DH6_REPLY 7 #define DH6_RELEASE 8 #define DH6_DECLINE 9 #define DH6_RECONFIGURE 10 #define DH6_INFORM_REQ 11 #define DH6_RELAY_FORW 12 #define DH6_RELAY_REPLY 13 #define DH6_LEASEQUERY 14 #define DH6_LQ_REPLY 15 static const struct tok dh6_msgtype_str[] = { { DH6_SOLICIT, "solicit" }, { DH6_ADVERTISE, "advertise" }, { DH6_REQUEST, "request" }, { DH6_CONFIRM, "confirm" }, { DH6_RENEW, "renew" }, { DH6_REBIND, "rebind" }, { DH6_REPLY, "reply" }, { DH6_RELEASE, "release" }, { DH6_DECLINE, "decline" }, { DH6_RECONFIGURE, "reconfigure" }, { DH6_INFORM_REQ, "inf-req" }, { DH6_RELAY_FORW, "relay-fwd" }, { DH6_RELAY_REPLY, "relay-reply" }, { DH6_LEASEQUERY, "leasequery" }, { DH6_LQ_REPLY, "leasequery-reply" }, { 0, NULL } }; /* DHCP6 base packet format */ struct dhcp6 { union { nd_uint8_t m; nd_uint32_t x; } dh6_msgtypexid; /* options follow */ }; #define dh6_msgtype dh6_msgtypexid.m #define dh6_xid dh6_msgtypexid.x #define DH6_XIDMASK 0x00ffffff /* DHCPv6 relay messages */ struct dhcp6_relay { nd_uint8_t dh6relay_msgtype; nd_uint8_t dh6relay_hcnt; nd_uint8_t dh6relay_linkaddr[16]; /* XXX: badly aligned */ nd_uint8_t dh6relay_peeraddr[16]; /* options follow */ }; /* options */ #define DH6OPT_CLIENTID 1 #define DH6OPT_SERVERID 2 #define DH6OPT_IA_NA 3 #define DH6OPT_IA_TA 4 #define DH6OPT_IA_ADDR 5 #define DH6OPT_ORO 6 #define DH6OPT_PREFERENCE 7 # define DH6OPT_PREF_MAX 255 #define DH6OPT_ELAPSED_TIME 8 #define DH6OPT_RELAY_MSG 9 /*#define DH6OPT_SERVER_MSG 10 deprecated */ #define DH6OPT_AUTH 11 # define DH6OPT_AUTHPROTO_DELAYED 2 # define DH6OPT_AUTHPROTO_RECONFIG 3 # define DH6OPT_AUTHALG_HMACMD5 1 # define DH6OPT_AUTHRDM_MONOCOUNTER 0 # define DH6OPT_AUTHRECONFIG_KEY 1 # define DH6OPT_AUTHRECONFIG_HMACMD5 2 #define DH6OPT_UNICAST 12 #define DH6OPT_STATUS_CODE 13 # define DH6OPT_STCODE_SUCCESS 0 # define DH6OPT_STCODE_UNSPECFAIL 1 # define DH6OPT_STCODE_NOADDRAVAIL 2 # define DH6OPT_STCODE_NOBINDING 3 # define DH6OPT_STCODE_NOTONLINK 4 # define DH6OPT_STCODE_USEMULTICAST 5 # define DH6OPT_STCODE_NOPREFIXAVAIL 6 # define DH6OPT_STCODE_UNKNOWNQUERYTYPE 7 # define DH6OPT_STCODE_MALFORMEDQUERY 8 # define DH6OPT_STCODE_NOTCONFIGURED 9 # define DH6OPT_STCODE_NOTALLOWED 10 #define DH6OPT_RAPID_COMMIT 14 #define DH6OPT_USER_CLASS 15 #define DH6OPT_VENDOR_CLASS 16 #define DH6OPT_VENDOR_OPTS 17 #define DH6OPT_INTERFACE_ID 18 #define DH6OPT_RECONF_MSG 19 #define DH6OPT_RECONF_ACCEPT 20 #define DH6OPT_SIP_SERVER_D 21 #define DH6OPT_SIP_SERVER_A 22 #define DH6OPT_DNS_SERVERS 23 #define DH6OPT_DOMAIN_LIST 24 #define DH6OPT_IA_PD 25 #define DH6OPT_IA_PD_PREFIX 26 #define DH6OPT_NIS_SERVERS 27 #define DH6OPT_NISP_SERVERS 28 #define DH6OPT_NIS_NAME 29 #define DH6OPT_NISP_NAME 30 #define DH6OPT_SNTP_SERVERS 31 #define DH6OPT_LIFETIME 32 #define DH6OPT_BCMCS_SERVER_D 33 #define DH6OPT_BCMCS_SERVER_A 34 #define DH6OPT_GEOCONF_CIVIC 36 #define DH6OPT_REMOTE_ID 37 #define DH6OPT_SUBSCRIBER_ID 38 #define DH6OPT_CLIENT_FQDN 39 #define DH6OPT_PANA_AGENT 40 #define DH6OPT_NEW_POSIX_TIMEZONE 41 #define DH6OPT_NEW_TZDB_TIMEZONE 42 #define DH6OPT_ERO 43 #define DH6OPT_LQ_QUERY 44 #define DH6OPT_CLIENT_DATA 45 #define DH6OPT_CLT_TIME 46 #define DH6OPT_LQ_RELAY_DATA 47 #define DH6OPT_LQ_CLIENT_LINK 48 #define DH6OPT_NTP_SERVER 56 # define DH6OPT_NTP_SUBOPTION_SRV_ADDR 1 # define DH6OPT_NTP_SUBOPTION_MC_ADDR 2 # define DH6OPT_NTP_SUBOPTION_SRV_FQDN 3 #define DH6OPT_AFTR_NAME 64 #define DH6OPT_MUDURL 112 static const struct tok dh6opt_str[] = { { DH6OPT_CLIENTID, "client-ID" }, { DH6OPT_SERVERID, "server-ID" }, { DH6OPT_IA_NA, "IA_NA" }, { DH6OPT_IA_TA, "IA_TA" }, { DH6OPT_IA_ADDR, "IA_ADDR" }, { DH6OPT_ORO, "option-request" }, { DH6OPT_PREFERENCE, "preference" }, { DH6OPT_ELAPSED_TIME, "elapsed-time" }, { DH6OPT_RELAY_MSG, "relay-message" }, { DH6OPT_AUTH, "authentication" }, { DH6OPT_UNICAST, "server-unicast" }, { DH6OPT_STATUS_CODE, "status-code" }, { DH6OPT_RAPID_COMMIT, "rapid-commit" }, { DH6OPT_USER_CLASS, "user-class" }, { DH6OPT_VENDOR_CLASS, "vendor-class" }, { DH6OPT_VENDOR_OPTS, "vendor-specific-info" }, { DH6OPT_INTERFACE_ID, "interface-ID" }, { DH6OPT_RECONF_MSG, "reconfigure-message" }, { DH6OPT_RECONF_ACCEPT, "reconfigure-accept" }, { DH6OPT_SIP_SERVER_D, "SIP-servers-domain" }, { DH6OPT_SIP_SERVER_A, "SIP-servers-address" }, { DH6OPT_DNS_SERVERS, "DNS-server" }, { DH6OPT_DOMAIN_LIST, "DNS-search-list" }, { DH6OPT_IA_PD, "IA_PD" }, { DH6OPT_IA_PD_PREFIX, "IA_PD-prefix" }, { DH6OPT_SNTP_SERVERS, "SNTP-servers" }, { DH6OPT_LIFETIME, "lifetime" }, { DH6OPT_NIS_SERVERS, "NIS-server" }, { DH6OPT_NISP_SERVERS, "NIS+-server" }, { DH6OPT_NIS_NAME, "NIS-domain-name" }, { DH6OPT_NISP_NAME, "NIS+-domain-name" }, { DH6OPT_BCMCS_SERVER_D, "BCMCS-domain-name" }, { DH6OPT_BCMCS_SERVER_A, "BCMCS-server" }, { DH6OPT_GEOCONF_CIVIC, "Geoconf-Civic" }, { DH6OPT_REMOTE_ID, "Remote-ID" }, { DH6OPT_SUBSCRIBER_ID, "Subscriber-ID" }, { DH6OPT_CLIENT_FQDN, "Client-FQDN" }, { DH6OPT_PANA_AGENT, "PANA-agent" }, { DH6OPT_NEW_POSIX_TIMEZONE, "POSIX-timezone" }, { DH6OPT_NEW_TZDB_TIMEZONE, "POSIX-tz-database" }, { DH6OPT_ERO, "Echo-request-option" }, { DH6OPT_LQ_QUERY, "Lease-query" }, { DH6OPT_CLIENT_DATA, "LQ-client-data" }, { DH6OPT_CLT_TIME, "Clt-time" }, { DH6OPT_LQ_RELAY_DATA, "LQ-relay-data" }, { DH6OPT_LQ_CLIENT_LINK, "LQ-client-link" }, { DH6OPT_NTP_SERVER, "NTP-server" }, { DH6OPT_AFTR_NAME, "AFTR-Name" }, { DH6OPT_MUDURL, "MUD-URL" }, { 0, NULL } }; static const struct tok dh6opt_stcode_str[] = { { DH6OPT_STCODE_SUCCESS, "Success" }, /* RFC3315 */ { DH6OPT_STCODE_UNSPECFAIL, "UnspecFail" }, /* RFC3315 */ { DH6OPT_STCODE_NOADDRAVAIL, "NoAddrsAvail" }, /* RFC3315 */ { DH6OPT_STCODE_NOBINDING, "NoBinding" }, /* RFC3315 */ { DH6OPT_STCODE_NOTONLINK, "NotOnLink" }, /* RFC3315 */ { DH6OPT_STCODE_USEMULTICAST, "UseMulticast" }, /* RFC3315 */ { DH6OPT_STCODE_NOPREFIXAVAIL, "NoPrefixAvail" }, /* RFC3633 */ { DH6OPT_STCODE_UNKNOWNQUERYTYPE, "UnknownQueryType" }, /* RFC5007 */ { DH6OPT_STCODE_MALFORMEDQUERY, "MalformedQuery" }, /* RFC5007 */ { DH6OPT_STCODE_NOTCONFIGURED, "NotConfigured" }, /* RFC5007 */ { DH6OPT_STCODE_NOTALLOWED, "NotAllowed" }, /* RFC5007 */ { 0, NULL } }; struct dhcp6opt { nd_uint16_t dh6opt_type; nd_uint16_t dh6opt_len; /* type-dependent data follows */ }; static const char * dhcp6stcode(const uint16_t code) { return code > 255 ? "INVALID code" : tok2str(dh6opt_stcode_str, "code%u", code); } static void dhcp6opt_print(netdissect_options *ndo, const u_char *cp, const u_char *ep) { const struct dhcp6opt *dh6o; const u_char *tp; size_t i; uint16_t opttype; size_t optlen; uint8_t auth_proto; u_int authinfolen, authrealmlen; int remain_len; /* Length of remaining options */ int label_len; /* Label length */ uint16_t subopt_code; uint16_t subopt_len; if (cp == ep) return; while (cp < ep) { if (ep < cp + sizeof(*dh6o)) goto trunc; dh6o = (const struct dhcp6opt *)cp; ND_TCHECK(*dh6o); optlen = EXTRACT_16BITS(&dh6o->dh6opt_len); if (ep < cp + sizeof(*dh6o) + optlen) goto trunc; opttype = EXTRACT_16BITS(&dh6o->dh6opt_type); ND_PRINT((ndo, " (%s", tok2str(dh6opt_str, "opt_%u", opttype))); ND_TCHECK2(*(cp + sizeof(*dh6o)), optlen); switch (opttype) { case DH6OPT_CLIENTID: case DH6OPT_SERVERID: if (optlen < 2) { /*(*/ ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); switch (EXTRACT_16BITS(tp)) { case 1: if (optlen >= 2 + 6) { ND_PRINT((ndo, " hwaddr/time type %u time %u ", EXTRACT_16BITS(&tp[2]), EXTRACT_32BITS(&tp[4]))); for (i = 8; i < optlen; i++) ND_PRINT((ndo, "%02x", tp[i])); /*(*/ ND_PRINT((ndo, ")")); } else { /*(*/ ND_PRINT((ndo, " ?)")); } break; case 2: if (optlen >= 2 + 8) { ND_PRINT((ndo, " vid ")); for (i = 2; i < 2 + 8; i++) ND_PRINT((ndo, "%02x", tp[i])); /*(*/ ND_PRINT((ndo, ")")); } else { /*(*/ ND_PRINT((ndo, " ?)")); } break; case 3: if (optlen >= 2 + 2) { ND_PRINT((ndo, " hwaddr type %u ", EXTRACT_16BITS(&tp[2]))); for (i = 4; i < optlen; i++) ND_PRINT((ndo, "%02x", tp[i])); /*(*/ ND_PRINT((ndo, ")")); } else { /*(*/ ND_PRINT((ndo, " ?)")); } break; default: ND_PRINT((ndo, " type %d)", EXTRACT_16BITS(tp))); break; } break; case DH6OPT_IA_ADDR: if (optlen < 24) { /*(*/ ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0]))); ND_PRINT((ndo, " pltime:%u vltime:%u", EXTRACT_32BITS(&tp[16]), EXTRACT_32BITS(&tp[20]))); if (optlen > 24) { /* there are sub-options */ dhcp6opt_print(ndo, tp + 24, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_ORO: case DH6OPT_ERO: if (optlen % 2) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); for (i = 0; i < optlen; i += 2) { ND_PRINT((ndo, " %s", tok2str(dh6opt_str, "opt_%u", EXTRACT_16BITS(&tp[i])))); } ND_PRINT((ndo, ")")); break; case DH6OPT_PREFERENCE: if (optlen != 1) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %d)", *tp)); break; case DH6OPT_ELAPSED_TIME: if (optlen != 2) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %d)", EXTRACT_16BITS(tp))); break; case DH6OPT_RELAY_MSG: ND_PRINT((ndo, " (")); tp = (const u_char *)(dh6o + 1); dhcp6_print(ndo, tp, optlen); ND_PRINT((ndo, ")")); break; case DH6OPT_AUTH: if (optlen < 11) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); auth_proto = *tp; switch (auth_proto) { case DH6OPT_AUTHPROTO_DELAYED: ND_PRINT((ndo, " proto: delayed")); break; case DH6OPT_AUTHPROTO_RECONFIG: ND_PRINT((ndo, " proto: reconfigure")); break; default: ND_PRINT((ndo, " proto: %d", auth_proto)); break; } tp++; switch (*tp) { case DH6OPT_AUTHALG_HMACMD5: /* XXX: may depend on the protocol */ ND_PRINT((ndo, ", alg: HMAC-MD5")); break; default: ND_PRINT((ndo, ", alg: %d", *tp)); break; } tp++; switch (*tp) { case DH6OPT_AUTHRDM_MONOCOUNTER: ND_PRINT((ndo, ", RDM: mono")); break; default: ND_PRINT((ndo, ", RDM: %d", *tp)); break; } tp++; ND_PRINT((ndo, ", RD:")); for (i = 0; i < 4; i++, tp += 2) ND_PRINT((ndo, " %04x", EXTRACT_16BITS(tp))); /* protocol dependent part */ authinfolen = optlen - 11; switch (auth_proto) { case DH6OPT_AUTHPROTO_DELAYED: if (authinfolen == 0) break; if (authinfolen < 20) { ND_PRINT((ndo, " ??")); break; } authrealmlen = authinfolen - 20; if (authrealmlen > 0) { ND_PRINT((ndo, ", realm: ")); } for (i = 0; i < authrealmlen; i++, tp++) ND_PRINT((ndo, "%02x", *tp)); ND_PRINT((ndo, ", key ID: %08x", EXTRACT_32BITS(tp))); tp += 4; ND_PRINT((ndo, ", HMAC-MD5:")); for (i = 0; i < 4; i++, tp+= 4) ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp))); break; case DH6OPT_AUTHPROTO_RECONFIG: if (authinfolen != 17) { ND_PRINT((ndo, " ??")); break; } switch (*tp++) { case DH6OPT_AUTHRECONFIG_KEY: ND_PRINT((ndo, " reconfig-key")); break; case DH6OPT_AUTHRECONFIG_HMACMD5: ND_PRINT((ndo, " type: HMAC-MD5")); break; default: ND_PRINT((ndo, " type: ??")); break; } ND_PRINT((ndo, " value:")); for (i = 0; i < 4; i++, tp+= 4) ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp))); break; default: ND_PRINT((ndo, " ??")); break; } ND_PRINT((ndo, ")")); break; case DH6OPT_RAPID_COMMIT: /* nothing todo */ ND_PRINT((ndo, ")")); break; case DH6OPT_INTERFACE_ID: case DH6OPT_SUBSCRIBER_ID: /* * Since we cannot predict the encoding, print hex dump * at most 10 characters. */ tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " ")); for (i = 0; i < optlen && i < 10; i++) ND_PRINT((ndo, "%02x", tp[i])); ND_PRINT((ndo, "...)")); break; case DH6OPT_RECONF_MSG: tp = (const u_char *)(dh6o + 1); switch (*tp) { case DH6_RENEW: ND_PRINT((ndo, " for renew)")); break; case DH6_INFORM_REQ: ND_PRINT((ndo, " for inf-req)")); break; default: ND_PRINT((ndo, " for ?\?\?(%02x))", *tp)); break; } break; case DH6OPT_RECONF_ACCEPT: /* nothing todo */ ND_PRINT((ndo, ")")); break; case DH6OPT_SIP_SERVER_A: case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: case DH6OPT_NIS_SERVERS: case DH6OPT_NISP_SERVERS: case DH6OPT_BCMCS_SERVER_A: case DH6OPT_PANA_AGENT: case DH6OPT_LQ_CLIENT_LINK: if (optlen % 16) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); for (i = 0; i < optlen; i += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[i]))); ND_PRINT((ndo, ")")); break; case DH6OPT_SIP_SERVER_D: case DH6OPT_DOMAIN_LIST: tp = (const u_char *)(dh6o + 1); while (tp < cp + sizeof(*dh6o) + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, cp + sizeof(*dh6o) + optlen)) == NULL) goto trunc; } ND_PRINT((ndo, ")")); break; case DH6OPT_STATUS_CODE: if (optlen < 2) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %s)", dhcp6stcode(EXTRACT_16BITS(&tp[0])))); break; case DH6OPT_IA_NA: case DH6OPT_IA_PD: if (optlen < 12) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " IAID:%u T1:%u T2:%u", EXTRACT_32BITS(&tp[0]), EXTRACT_32BITS(&tp[4]), EXTRACT_32BITS(&tp[8]))); if (optlen > 12) { /* there are sub-options */ dhcp6opt_print(ndo, tp + 12, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_IA_TA: if (optlen < 4) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " IAID:%u", EXTRACT_32BITS(tp))); if (optlen > 4) { /* there are sub-options */ dhcp6opt_print(ndo, tp + 4, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_IA_PD_PREFIX: if (optlen < 25) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %s/%d", ip6addr_string(ndo, &tp[9]), tp[8])); ND_PRINT((ndo, " pltime:%u vltime:%u", EXTRACT_32BITS(&tp[0]), EXTRACT_32BITS(&tp[4]))); if (optlen > 25) { /* there are sub-options */ dhcp6opt_print(ndo, tp + 25, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_LIFETIME: case DH6OPT_CLT_TIME: if (optlen != 4) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %d)", EXTRACT_32BITS(tp))); break; case DH6OPT_REMOTE_ID: if (optlen < 4) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %d ", EXTRACT_32BITS(tp))); /* * Print hex dump first 10 characters. */ for (i = 4; i < optlen && i < 14; i++) ND_PRINT((ndo, "%02x", tp[i])); ND_PRINT((ndo, "...)")); break; case DH6OPT_LQ_QUERY: if (optlen < 17) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); switch (*tp) { case 1: ND_PRINT((ndo, " by-address")); break; case 2: ND_PRINT((ndo, " by-clientID")); break; default: ND_PRINT((ndo, " type_%d", (int)*tp)); break; } ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[1]))); if (optlen > 17) { /* there are query-options */ dhcp6opt_print(ndo, tp + 17, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_CLIENT_DATA: tp = (const u_char *)(dh6o + 1); if (optlen > 0) { /* there are encapsulated options */ dhcp6opt_print(ndo, tp, tp + optlen); } ND_PRINT((ndo, ")")); break; case DH6OPT_LQ_RELAY_DATA: if (optlen < 16) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, " %s ", ip6addr_string(ndo, &tp[0]))); /* * Print hex dump first 10 characters. */ for (i = 16; i < optlen && i < 26; i++) ND_PRINT((ndo, "%02x", tp[i])); ND_PRINT((ndo, "...)")); break; case DH6OPT_NTP_SERVER: if (optlen < 4) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); while (tp < cp + sizeof(*dh6o) + optlen - 4) { subopt_code = EXTRACT_16BITS(tp); tp += 2; subopt_len = EXTRACT_16BITS(tp); tp += 2; if (tp + subopt_len > cp + sizeof(*dh6o) + optlen) goto trunc; ND_PRINT((ndo, " subopt:%d", subopt_code)); switch (subopt_code) { case DH6OPT_NTP_SUBOPTION_SRV_ADDR: case DH6OPT_NTP_SUBOPTION_MC_ADDR: if (subopt_len != 16) { ND_PRINT((ndo, " ?")); break; } ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0]))); break; case DH6OPT_NTP_SUBOPTION_SRV_FQDN: ND_PRINT((ndo, " ")); if (ns_nprint(ndo, tp, tp + subopt_len) == NULL) goto trunc; break; default: ND_PRINT((ndo, " ?")); break; } tp += subopt_len; } ND_PRINT((ndo, ")")); break; case DH6OPT_AFTR_NAME: if (optlen < 3) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); remain_len = optlen; ND_PRINT((ndo, " ")); /* Encoding is described in section 3.1 of RFC 1035 */ while (remain_len && *tp) { label_len = *tp++; if (label_len < remain_len - 1) { (void)fn_printn(ndo, tp, label_len, NULL); tp += label_len; remain_len -= (label_len + 1); if(*tp) ND_PRINT((ndo, ".")); } else { ND_PRINT((ndo, " ?")); break; } } ND_PRINT((ndo, ")")); break; case DH6OPT_NEW_POSIX_TIMEZONE: /* all three of these options */ case DH6OPT_NEW_TZDB_TIMEZONE: /* are encoded similarly */ case DH6OPT_MUDURL: /* although GMT might not work */ if (optlen < 5) { ND_PRINT((ndo, " ?)")); break; } tp = (const u_char *)(dh6o + 1); ND_PRINT((ndo, "=")); (void)fn_printn(ndo, tp, (u_int)optlen, NULL); ND_PRINT((ndo, ")")); break; default: ND_PRINT((ndo, ")")); break; } cp += sizeof(*dh6o) + optlen; } return; trunc: ND_PRINT((ndo, "[|dhcp6ext]")); } /* * Print dhcp6 packets */ void dhcp6_print(netdissect_options *ndo, const u_char *cp, u_int length) { const struct dhcp6 *dh6; const struct dhcp6_relay *dh6relay; const u_char *ep; const u_char *extp; const char *name; ND_PRINT((ndo, "dhcp6")); ep = (const u_char *)ndo->ndo_snapend; if (cp + length < ep) ep = cp + length; dh6 = (const struct dhcp6 *)cp; dh6relay = (const struct dhcp6_relay *)cp; ND_TCHECK(dh6->dh6_xid); name = tok2str(dh6_msgtype_str, "msgtype-%u", dh6->dh6_msgtype); if (!ndo->ndo_vflag) { ND_PRINT((ndo, " %s", name)); return; } /* XXX relay agent messages have to be handled differently */ ND_PRINT((ndo, " %s (", name)); /*)*/ if (dh6->dh6_msgtype != DH6_RELAY_FORW && dh6->dh6_msgtype != DH6_RELAY_REPLY) { ND_PRINT((ndo, "xid=%x", EXTRACT_32BITS(&dh6->dh6_xid) & DH6_XIDMASK)); extp = (const u_char *)(dh6 + 1); dhcp6opt_print(ndo, extp, ep); } else { /* relay messages */ struct in6_addr addr6; ND_TCHECK(dh6relay->dh6relay_peeraddr); memcpy(&addr6, dh6relay->dh6relay_linkaddr, sizeof (addr6)); ND_PRINT((ndo, "linkaddr=%s", ip6addr_string(ndo, &addr6))); memcpy(&addr6, dh6relay->dh6relay_peeraddr, sizeof (addr6)); ND_PRINT((ndo, " peeraddr=%s", ip6addr_string(ndo, &addr6))); dhcp6opt_print(ndo, (const u_char *)(dh6relay + 1), ep); } /*(*/ ND_PRINT((ndo, ")")); return; trunc: ND_PRINT((ndo, "[|dhcp6]")); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2692_0